Introduction to ZCache Designs (Preliminary Notes)

In this short note, we will discuss a recent cache design called a ZCache that performs well in reducing conflict misses. This is not a formal paper, but rather an expository note on the topic. Nothing of the discussions in original except perhaps the point of view. The main references we used are [1], [2] and [3] listed at the end of this note.

  • Section 1: Cache:
    Cache is a fundamental concept in the memory hierarchy abstraction. In broad terms it is a storage device (e.g. SRAM) that is served as a staging area for slower memories (e.g. DRAM or hard disk). They are used to fill in the increasing gaps between CPU access speed and main memory and hard disk access speed. In this definition, the main memory (DRAM) can be thought of a cache for the hard disk, and register sets can be thought of as caches for main memory. In today’s computers, there are usually two to three additional levels of caches inserted in between the register sets and main memory, and they are denoted as L1, L2, and L3 caches, respectively. It is important to note that the data between the level k and k+1 memory in the hierarchy are transferred in fixed block-sized units, where the size of the blocks depend on the level of cache memory that we are talking about. For instance, registers, thought of as the L0 cache, and L1 usually transfer data in one word block size, whereas L2 and L1 (and L3 and L2) usually use 8 to 16 words as the block size. When it comes to the main memory and the hard disk, we can have hundreds or thousands of bytes being transferred at once.

    Now let’s focus on L1, L2 or possibly L3 caches for the main memory. There are four characteristics that describe a generic cache memory organization: number of bits in main memory address: m, the number of sets of the cache: S, the number of cache lines each set contains: E, and the block size (in bytes) used as the atomic transfer unit: B. We thus can identify a cache with the tuple: (S, E, B, m). We assume that S and B are both powers of 2, and define s: = \log{S} and b: = \log{B}, thus a s-bit pattern corresponds to a set in the cache, and a b-bit pattern corresponds to the address of a byte in a block. The size of the cache equals to C: = S\times E \times B.

    The pair (S, B) induces a partition on the address space of the main memory: we choose the least significant b bits as the block offset indicator, and the next s bits as the set identifier. Then we have t: = m - s - b bits left at the most significant slots. Those are called the tag bits for that address. For each line in a set of a cache, we not only store the block of bytes, but also some header information including t bits from the tags in the base address of each block of data read in from main memory, as well as a one (flag) bit indicating whether the current line is valid or not. It is important to note that the flag bits uniquely identifies the multiple blocks that are mapped to the same cache set. Within a single block, the flag bits are the same for all the byte addresses in that block, thus it does not matter which byte we take the flag bits from, in particular we can say that it is from the base address.

    Here is how cache works in storing data temporarily: given an address p in main memory, since we transfer in block size, we are going to fetch B bytes containing p (to be more explicit, we fetch all the bytes with addresses having the same tag bits and set bits, and b block offset bits ranging from 00\cdots 0 to 11\cdots 1). p has m bits: we use the middle s bits to determine which set of the cache will p be stored, and the least significant b bits to determine the address of the byte in the cache block will this byte pointed by p be placed. Note that the tag bits together with the set bits uniquely determine each block in main memory. Therefore in order to determine if a byte of data is present in the cache, we need to:

      1. first check the set bits to locate the cache set that this byte should be in;
      2. then check if the flag bit is set to valid and if the tag bits in the address of this byte matches with the tag bits stored in any of the caches lines within that set.

    If we have passed this test, then we know that this byte must be present in the cache since we transfer data in block sized units. Hence what is left to do is to look at the offset bits to determine the address of this byte within the block. In this case we have a cache hit. If a query byte cannot be found within the cache, then we have a cache miss, in which case we have to go to the next level cache to get the block containing that data, replace (or evict) a block in the current cache with it, and return data (now lies in the cache) back to CPU. We won’t discuss any of the replacement policy in choosing the block to be evicted (called a victim block), and simply assume that we either follow the LRU (least recently used) or random policy.

    We can classify the memory caches by the value E, the number of cache lines within each cache set. In the case where E = 1, it is called a direct mapped cache in which case a block in main memory can be mapped to a unique line within some cache set. In the case where 1 < E < C/B, it is called a E-way set-associative cache in which case a block in main memory can be mapped to any of the E cache lines within a cache set. In the case where E = C/B, or equivalently S = 1, we have only one cache set and it is called a fully-associative cache. In this case a cache block can be mapped to any cache line in this cache.

  • Section 2: Skew Associative Cache:
    Suppose we have an n-way set associative cache. Now if a program loads n+1 blocks from memory that have the same set bits, then we will have a conflict in that set. In this case even though there might be other sets available to store the incoming blocks, we are still going to have conflicts, called a conflict miss (on the (n+1)th block). One way to solve this problem is the following: for each way we use a hash function to reconstruct the set number from the address of the incoming block, and map it to each way of the corresponding sets at the same time. Hence there is a unique position in each way/bank (the set of all the ith way in the cache is called the ith bank. Thus our cache has n banks) belonging to different sets for each incoming block. For example when n = 3, and we are reading in data with base address D. We fix three hash functions f_0, f_1 and f_2, and suppose that the set bits of the hashed results of D: f_0 (D), f_1(D), f_2(D) are different. Then D could end up in either of the three different sets. The reason why this is useful is that since we are using different hash functions for different banks, if there is a collision in one bank (i.e. there is a hash function maps two blocks to the same set), there might not be a collision in the other (i.e. some other hash function might be able to map them to different sets), so we can just take the block to the bank where there is no collision. This way we can hope to reduce the occurrences of conflict misses.

    In the case of a cache miss on the data with address D, we see that it could end up in set f_0(D), f_1(D) and f_2(D). Thus we get three candidate victim blocks to evict. We can evict one of the blocks according to certain replacement policy. In ZCache we will see a modification of the skew associative cache in terms of the eviction and replacement scheme.

  • Posted in Cache | Tagged , | Leave a comment

    Path Containing Minimum Value Node

    Given a binary tree such that each node carries an integer value. Return the root-to-leaf path that contains the node with minimum value.

    Analysis: We again use the dynamic path trick. We keep a global vector of TreeNode pointers that is being updated with a path that contains a smaller-valued node. We return nodes when we are done scanning all the paths.

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    int minVal (TreeNode* path[], int pathLen)
    {
        int global_min = INT_MAX;
        int i;
        for (i = 0; i < pathLen, i++) {
            int temp_min = path[i]->val;
            global_min = (global_min < temp_min) ? global_min : temp_min;
        }
        return global_min;
    }
    
    vector<TreeNode *> &minValPath (TreeNode* root, TreeNode* path[], int pathLen, vector<TreeNode *> &minPath, int &MIN)
    {
        if (root == NULL)
            return minPath;
        int temp_min;
        path[pathLen++] = root;
    
        //check if current node is a leaf; if yes then we get a complete path
        if (root->left == NULL && root->right == NULL) {
            //compute the minimum value of this path
            temp_min = minVal(path, pathLen);
            //cout << "debug: temp_min = " << temp_min << endl;
            if (temp_min < MIN) {
                MIN = temp_min;
                //copy the current path into the vector minPath
                //NEED TO OPTIMIZE THIS PART! tempVec is unnecessary!
                vector<TreeNode> tempVec(path, path + pathLen);
                minPath = tempVec;
                //cout << "find a new min path: " << endl;
                //printPath(minPath);
            }
            //otherwise skip this path
        }
        //recurse left and right
        minValPath(root->left, path, pathLen, minPath, MIN);
        minValPath(root->right, path, pathLen, minPath, MIN);
    
        return minPath;
    }
    
    Posted in MISC Problems | Tagged | Leave a comment

    Search Insert Position

    Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

    You may assume no duplicates in the array.

    Here are few examples.
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0
    This is an easy problem:

    class Solution {
    public:
        int searchInsert(int A[], int n, int target) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int i;
            for (i = 0; i < n; i++)
            {
                if (target <= A[i])
                    return i;
            }
            return n;
        }
    };
    
    Posted in LeetCode | Leave a comment

    Plus One

    Given a number represented as an array of digits, plus one to the number.

    This is an easy problem. Two cases to be careful with: when the input vector is empty, return the vector with 1 pushed in; when the input number is like 9999, need to insert 1 at the beginning of the vector.

    class Solution {
    public:
        vector<int> plusOne(vector<int> &digits) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            int flag = 1;
            int i = digits.size() - 1;
            if (i < 0) //digits is empty
            {
                digits.push_back(i);
                return digits;
            }
            for (; i >= 0; i--)
            {
                if (digits[i] + flag >= 10)
                    digits[i] = (digits[i] + flag) % 10;
                else //digits[i] + flag < 10
                {
                    digits[i] += flag;
                    flag = 0; //reset flag to 0
                    return digits; //we can return now
                }
            }
            if (flag == 1) //residual flag: insert 1 at the beginning of the vector
                digits.insert(digits.begin(), 1);
                
            return digits;
        }
    };
    
    Posted in LeetCode | Leave a comment

    Linked List Cycle II

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

    Follow up:
    Can you solve it without using extra space?

    Analysis:
    This is a follow up question to the previous Linked List Cycle post. Previously we showed that the list has a cycle if and only if the fast node and the slow node collide during traversal. Again we assume that there are k nodes before the cycle, and there are C nodes in the cycle. After k steps, slow node enters the cycle, and after another C-k steps, they will collide. At that moment the slow node is C-k nodes into the cycle. In other words, after k steps, the slow node will get to the beginning of the cycle again. Hence our algorithm works as follows:

  • Run the two nodes respectively until they collide; otherwise return NULL;
  • When they collide, use another node p to traverse the list from the beginning, march p and slow node at the same pace until they collide;
  • return the node at which p and slow node collide.
  • /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            ListNode *fast, *slow;
            fast = slow = head;
            while (fast != NULL && fast->next != NULL)
            {
                slow = slow->next;
                fast = fast->next->next;
                if (slow == fast)//there is a collision!
                    break;
            }
            if (fast == NULL || fast->next == NULL)
                return NULL; //no cycle
            else //there is a cycle, find the beginning node now
            {
                ListNode *p = head;
                while (p != slow)
                {
                    p = p->next;
                    slow = slow->next;
                }
                return p;
            }
        }
    };
    
    Posted in LeetCode | Tagged , | Leave a comment

    Linked List Cycle

    Given a linked list, determine if it has a cycle in it.

    Follow up:
    Can you solve it without using extra space?

    Analysis:
    One way to solve this problem is to traverse the linked list while keeping a vector storing the address of each node visited. For each node we visit, we first check if the address of that node is already in our vector. If yes then we have run into a previously visited node, hence there is a cycle. If we do not detect any cycle until the NULL node, then the list has no cycle. This algorithm takes O(n) space and runs in O(n^2) time.

    A better algorithm is based on the following observation: if we have a fast node that traverse the list two nodes at a time, and a slow node that traverse the list one node at a time, then the linked list has a cycle if and only if the fast node and the slow node collide before they run into the NULL node at the end. One direction of this claim is easy to show: if the two nodes collide, then there must be a cycle in the list since otherwise the fast node will arrive at the NULL node and there won’t be any collision. Contradiction.

    On the other hand, if there is cycle in the list, then suppose that the beginning of the cycle starts at node k+1, then after k steps, the slow node will arrive at the beginning of the cycle whereas the fast node is already k nodes into the cycle, and now both of them will be trapped in the cycle. Suppose the cycle has C nodes, then since the fast node catches up with the slow node one node at a time, after C - k steps the fast node will collide with the slow node.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        bool hasCycle(ListNode *head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            
            ListNode *fast, *slow;
            fast = slow = head;
            while (fast != NULL && fast->next != NULL)
            {
                //first increment the fast and slow pointers
                slow = slow->next;
                fast = fast->next->next;
                if (fast == slow) //there is collision!
                    break;
            }//endwhile
            if (fast == NULL || fast->next == NULL)
                return false;
            else
                return true;
        }
    };
    
    Posted in LeetCode | Tagged , | 1 Comment

    Remove Duplicates from Sorted List II

    Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

    For example,
    Given 1->2->3->3->4->4->5, return 1->2->5.
    Given 1->1->1->2->3, return 2->3.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
    ListNode *deleteDuplicates(ListNode *head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if (head == NULL || head->next == NULL)
            return head;
        ListNode *front = head;
        ListNode *back = NULL;
        while (front != NULL)
        {
            //find the first duplicating node
            while (front->next != NULL && front->next->val != front->val)
            {
                back = front;
                front = front->next;
            }
            if (front->next == NULL) //we have arrived at the last node in the list, done searching
                return head;
            else //now front points at the beginning of the duplicating nodes
            {
                //find the end of the duplicating nodes
                while (front->next != NULL && front->next->val == front->val)
                    front = front->next;
                //now front is at the end of the duplicating nodes
                ListNode *nextNode = front->next;
                if (back == NULL) //duplicates start at the beginning of the linked list
                    head = nextNode; //back stays NULL, update the head pointer
                else
                    back->next = nextNode;
                //update front node
                front = nextNode;
            }//endelse
            //printList(L);
        }//endwhile
        return head;
    }
    };
    
    Posted in LeetCode | Tagged , | Leave a comment

    Remove Duplicates from Sorted List

    Given a sorted linked list, delete all duplicates such that each element appear only once.

    For example,
    Given 1->1->2, return 1->2.
    Given 1->1->2->3->3, return 1->2->3.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if (head == NULL || head->next == NULL) //empty list or single elememt list, no duplicates
                return head;
            ListNode *first, *second;
            second = head;
            first = second->next;
            //when we have marched to the NULL node no need to continue
            while (first != NULL) 
            {
                if (first->val == second->val) //found duplicate
                {
                    ListNode *nextNode = first->next;
                    second->next = nextNode;
                    first = nextNode; //update the first node; second node stays for now
                }//endif
                else //no duplicated yet
                {
                    second = first; //march the second node up to the first node
                    first = first->next; //increment the first node
                }
            }//endwhile
            return head;
        }
    };
    
    Posted in LeetCode | Tagged , | Leave a comment

    Binary Tree Maximum Path Sum

    Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int max_sum;
        int dfs (TreeNode *node)
        {
            if (node == NULL)
                return 0;
            int leftSum = dfs (node->left);
            int rightSum = dfs (node->right);
            int localSum = node->val;
            if (leftSum > 0)
                localSum += leftSum;
            if (rightSum > 0)
                localSum += rightSum;
            //update the global max by comparing the previous max with the sum of the local parent-children triangle
            max_sum = max (max_sum, localSum);
            //return back to upper level
            if (max(leftSum, rightSum) > 0)
                //pick the chidl with larger value
                return max(leftSum, rightSum) + node->val;
            else
                return node->val;
        }
        int maxPathSum(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            max_sum = INT_MIN;
            dfs (root);
            return max_sum;
        }
    };
    
    Posted in LeetCode | Tagged , , | Leave a comment

    Flatten Binary Tree to Linked List

    Given a binary tree, flatten it to a linked list in-place (the next pointer is represented by the right pointer, and all the left pointers are muted by setting them to NULL ).

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        void flatten(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if (root == NULL)
                return;
            stack <TreeNode *> nodes;
            TreeNode *prevNode = NULL;
            TreeNode *currNode = NULL;
            nodes.push(root);
            
            while (!nodes.empty())
            {
                currNode = nodes.top(); //currNode records the current node in the preorder traversal
                if (prevNode == NULL)
                    prevNode = currNode;
                else
                {
                    prevNode->right = currNode;
                    prevNode->left = NULL;
                    prevNode = currNode; //update prevNode
                }
                nodes.pop();
                if (currNode->right != NULL)
                    nodes.push (currNode->right);
                if (currNode->left != NULL)
                    nodes.push (currNode->left);
            }
        }
    };
    
    Posted in LeetCode | Tagged , , | Leave a comment