KV memory and quantization · Easy

Token-to-Page Address Translation

Problem 32 of 50 · Python and NumPy

Problem

Translate logical token positions into physical storage slots using a sequence block table. For position p, logical page = p//block_size, offset = p%block_size, physical slot = block_table[logical_page]*block_size+offset. Return slots in the same order as token_positions; repeated or unsorted positions are allowed.

def page_addresses(block_table, block_size, token_positions):

Constraints

  • block_size is an integer in 1..32; block_table has 0..32 nonnegative physical page IDs.
  • Every token position is nonnegative and below len(block_table)*block_size; there are 0..64 positions.
  • Inputs satisfy these constraints; invalid-input handling is not graded. Use only Python standard library and NumPy.

Examples

Example 1

Arguments: [
  [
    7,
    2
  ],
  4,
  [
    0,
    3,
    4,
    7
  ]
]
Expected result: [
  28,
  31,
  8,
  11
]

Positions 0 and 3 map inside physical page 7; positions 4 and 7 map inside page 2.

Example 2

Arguments: [
  [
    3,
    1
  ],
  2,
  [
    3,
    0,
    3
  ]
]
Expected result: [
  3,
  6,
  3
]

Position 3 maps to slot 3, position 0 to slot 6; duplicate lookups remain duplicated.

Sign in to solve this problem

Browse all coding problems · Learn the foundations