Unpack int4 weights from bytes

Why it matters GPTQ and AWQ int4 checkpoints store weights packed this way.

4-bit weights are stored two per byte. Unpacking them is the first step of every int4 kernel.

Write unpack_int4(packed). packed is a uint8 array. Each byte holds two signed 4-bit values: the low nibble first, then the high nibble, in two's complement (values -8 .. 7). Return an int array twice as long.

Signaturedef unpack_int4(packed)

Example

unpack_int4([0x1F]) is [-1, 1] because the low nibble 0xF is -1 and the high nibble 0x1 is 1.

Understand the idea

4-bit quantised weights pack two values into each byte: one in the low 4 bits (low nibble) and one in the high 4 bits. Each nibble is a signed number in two's complement, so raw values 0 to 7 mean 0 to 7 and raw values 8 to 15 mean -8 to -1. Worked example: byte 0xA7. Low nibble 0x7 = 7, which stays 7. High nibble 0xA = 10, which is at least 8, so it means 10 - 16 = -6. Output [7, -6]. Byte 0x80 has low nibble 0 and high nibble 8, giving [0, -8]. Rule: low = byte & 0xF; high = (byte >> 4) & 0xF; for each, if value >= 8 subtract 16; interleave so each byte gives low first, then high; the output is twice as long as the input. Convert to a signed int type before subtracting, because uint8 cannot hold negatives. Swapping the nibble order is the usual bug. Used in: GPTQ, AWQ and llama.cpp style int4 weight formats, where kernels unpack nibbles on the fly before the matrix multiply.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleunpack_int4([0x1F])
  • Sample 2: rangeunpack_int4([0x80, 0x7F, 0x00])
  • Test 3: randomunpack_int4(_b)