Unit 9 of 10 · about 5 hours · implement

Native extension contracts: shapes, strides, aliasing and layout

A correct standalone kernel can become incorrect when passed a tensor view or launched on the wrong stream. The wrapper is part of the algorithm's correctness contract.

You'll be able to

  • Specify and enforce shape, dtype, device, stride, alignment and aliasing preconditions at a native tensor boundary.
  • Launch on the input device's current framework stream while preserving tensor ownership and lifetime.
  • Test valid views, empty inputs and rejected inputs against an independent framework reference.

Covers

Tensor shape, stride, dtype, stream and error contracts at a native extensionAlignment, aliasing, layout and compiler optimization constraints
1

Read

In this order, only the parts listed

0 of 4 done

  1. PyTorch: custom C++ and CUDA operators, January 20, 2026PyTorch custom C++/CUDA operators and CUDA semantics

    Setting up the Build System; Defining the custom op and adding backend implementations through the CUDA registration; Testing an operator; Creating mutable operators, schema discussion only

    Choose one API tab compatible with your installation; the non-ABI-stable ATen path is sufficient here. Do not copy the CUDA sample unchanged: it lacks empty-input handling, same-device validation, a device guard and launch-error checks, and narrows the element count to int. Skip fake-kernel, autograd and wheel-packaging implementation. Full opcheck integration follows after those registrations; it is not a numerical oracle.

  2. PyTorch 2.14: CUDA stream order and allocation lifetimePyTorch custom C++/CUDA operators and CUDA semantics

    CUDA streams, including the wait_stream and record_stream examples

  3. CUDA Programming Guide 13.4.2: restricted pointers and access alignmentCUDA Programming Guide

    Section 5.4.1.4, __restrict__

  4. NVIDIA: vector-load alignmentNVIDIA CUDA Pro Tips: grid-stride loops and vectorized memory access

    Vector-type alignment discussion through the aligned int2 pointer-offset example

    Skip the complete vector-copy kernels with faulty remainder ownership.

2

Focus on

  • Choose a layout policy: reject unsupported strides, index actual strides, or explicitly normalize inputs with contiguous(). Include normalization cost in end-to-end measurements.
  • For a simple out-of-place map, accept same-shape float32 CUDA inputs on the same device, allocate a fresh output, and define whether gradients are supported. Do not promise broadcasting or mutation accidentally.
  • A view's data pointer includes its storage offset but says nothing about subsequent strides or vector alignment. Validate vector alignment independently and provide a scalar tail or fallback.
  • Guard the input device and use its current framework stream, not an assumed default stream. If work crosses streams, execution dependencies and caching-allocator lifetime need separate handling.
Common mistakes · 3
  • Using numel() and a raw pointer as proof of contiguous layout. A transposed tensor has the same element count but different strides.
  • Adding __restrict__ while permitting output-input overlap. The promise must match the actual access and aliasing contract; two read-only inputs aliasing each other is a different case.
  • Synchronizing the whole device on every call to hide stream bugs. Preserve asynchronous behavior and synchronize only at the test or measurement boundary.
3

Try it yourself

Closed-book, before checking anything

Build an inference-only out-of-place float32 vector-add extension. Require equal shapes and one CUDA device, explicitly normalize noncontiguous inputs, guard that device, use its current stream and wide grid-stride indices, return an empty output without a zero-block launch, and check launch errors. Compare with a + b on lengths 0, 1, 31, 32, 33 and 1003, a transposed two-dimensional view and a contiguous view offset by one element. Reject mismatched shapes, dtypes, devices and gradient-requiring inputs under the stated inference contract. Confirm fresh output storage, unchanged inputs and non-default-stream execution with an explicit dependency before host validation.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.A float32 allocation is aligned to 16 bytes. Is its view starting one element later safe for an int4 load?Answer

    No. The four-byte offset breaks 16-byte alignment. Use an aligned path or scalar accesses instead.

  2. 2.Does record_stream make a consuming stream wait for a producer?Answer

    No. It tells the allocator about use on another stream. A stream wait or event establishes execution order; lifetime tracking is separate.

  3. 3.Does passing opcheck prove the arithmetic and gradients are correct?Answer

    No. It checks registration behavior. Use an independent numerical reference and, when gradients are supported later, separate gradient tests.

You're done when

Your wrapper passes the valid-input reference matrix and rejects unsupported inputs before launch, with documented layout, aliasing, stream and lifetime policies.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 8 more in the section
  • CUDA Programming GuideNVIDIA · required

    Read the Basics and Programming Model chapters plus the sections on memory, synchronization, hardware implementation and compute capabilities used by your kernels. Record the toolkit documentation version alongside every claim.

  • NVIDIA CUDA Pro Tips: grid-stride loops and vectorized memory accessNVIDIA · required

    Read the grid-stride SAXPY loop and its scalability and debugging discussion (April 22, 2013), plus the scalar-copy SASS and vector-type alignment discussion in Increase Performance with Vectorized Memory Access (August 4, 2025). Skip the latter article's full vector-copy kernels: their tail-thread condition can omit remainders. These fill the pool's grid-stride and vector-width coverage gaps.

  • PyTorch custom C++/CUDA operators and CUDA semanticsPyTorch · required

    Custom C++ and CUDA Operators: build system, backend registration, Testing an operator and mutable schema; CUDA semantics 2.14: CUDA streams. These fill the native tensor-boundary gap in the CUDA-only pool. Stop before fake-kernel and autograd implementation; harden the tutorial's CUDA example for empty inputs, same-device checks, device guards, indexing width and launch errors.

Also in this section

  • Programming Massively Parallel Processors, 4th edition - Chapters 2 to 6Wen-mei Hwu, David Kirk and Izzat El Hajj · primary

    Read Chapters 2 to 6: data-parallel kernels, multidimensional grids, compute architecture and scheduling, memory architecture and data locality, and performance considerations. Work the chapter exercises on warps, occupancy, memory and coalescing, and predict three altered launch or address patterns before running them.

  • MIT 6.S894 Accelerated Computing (Fall 2025) - Lectures 2 to 5 and Labs 2 and 3MIT · required

    Use Lecture 2 (Throughput Processors), Lectures 3 and 4 (Memory, Parts 1 and 2) and Lecture 5 with its continuation (scratchpads, bank conflicts, register shuffles, overlap) for why the hardware looks as it does. Do Lab 2 (Massively-Parallel Mandelbrot, with its FMA-latency and warp-scheduler probes) and Lab 3 (Wave Simulation, with its coalesced-load and memory-latency probes) from the public lab repositories, built with nvcc for your own GPU instead of the course service. The labs were written for an RTX 4000 Ada, so recompute any SM count or bandwidth the questions assume.

  • CUDA C++ Best Practices GuideNVIDIA · required

    Study Assess, Parallelize, Optimize, Deploy; Getting the Right Answer; memory optimization; execution configuration; instruction optimization; and deployment compatibility. Convert recommendations into hypotheses, not universal rules.

  • Parallel Thread Execution ISANVIDIA · reference

    Read the PTX purpose, machine model, state spaces, memory consistency and target directives. Compile two tiny kernels, map source to PTX and SASS, and explain what PTX does and does not guarantee across devices.

  • GPU MODE Foundations LecturesGPU MODE · support

    Use Lectures 2, 3, 4, 5, 8, 37 and 41 for PMPP review, CUDA setup, architecture, optimization checklists, SASS and documentation reading. Reproduce only the examples that test a prediction from this stage.

  • TensorTonic Language Modeling from Scratch - GPU analysis problemsTensorTonic · support

    Solve GPU Occupancy Calculator, Shared-Memory Bank Conflict Analyzer and Global-Memory Coalescing Counter after the matching units, and check each answer against your own derivation.

  • AI Performance Engineering - GPU FundamentalsWafer · reference

    A curated index. Use Section 1 only to find a CUDA, PTX or architecture source the other entries lack.

  • CUDA Binary Utilities 13.4NVIDIA · reference

    Sections 1.1 to 1.2, 2.1.1 to 2.1.3, 3.1.1 and 3.1.4 for cubin extraction, resource reports and line-correlated SASS. The existing compiler and PTX references lack a worked binary-tool workflow.