Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Cache-Friendly Matrix Transpose

HardPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Cache-Friendly Matrix Transpose. Start with the requirements on the right.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.

Problem

AMD GPU and CPU runtimes often transpose flat tensor buffers before dispatching kernels. Implement a cache-aware transpose for a row-major matrix stored in a strided buffer. Python cannot dereference raw pointers, so buffer and offset model a raw memory region, while address arithmetic models alignment and cache-line access.

Your function must return the compact transposed matrix and the number of source cache-line transitions produced by the traversal. Select the largest square tile that fits two tile-sized working regions within cache_budget_bytes, capped at 64 elements per side. Traverse each tile in row-major order, reading only logical matrix elements and ignoring row padding.

Formal Specification

Implement transpose_aligned(buffer, rows, cols, stride, offset, element_size, base_address, cache_line_size, cache_budget_bytes).

  • buffer is a list of numeric values containing the matrix and possible padding.
  • The matrix element at row r, column c is buffer[offset + r * stride + c].
  • base_address + offset * element_size is guaranteed to be cache-line aligned.
  • Return a dictionary with data, a row-major flat list of shape cols x rows, and line_transitions, the number of times consecutive source reads belong to different cache lines.

Constraints

  • 1 <= rows, cols <= 2048
  • cols <= stride <= 4096
  • 0 <= offset < len(buffer)
  • The buffer contains every logical element and row padding
  • 1 <= element_size, cache_line_size, cache_budget_bytes <= 10^6
  • base_address + offset * element_size is divisible by cache_line_size
  • The matrix contains at most 10^7 logical elements

Function Signature

def transpose_aligned(buffer, rows, cols, stride, offset, element_size, base_address, cache_line_size, cache_budget_bytes):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output