You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
[feature request] np.packbits / np.unpackbits, general BitTensors (maybe can be just tensors with dtype torch.bits8 or have a new dtype torch.bits introduced) and bit packed tensors utilities for saving memory / accesses, support for BitTensors wherever BoolTensors are used #292
A usecase: storing a full backtracking pointer matrix can be okay for needleman/ctc alignment (4x memory saving compared to uint8 representation), if 2bit data type is used. Currently it's possible to do this with bit manipulation magic, but probably not very efficient (store and load will require masking and shifting, not fused)
Another usecase: compressed BoolTensor for binary neural networks
Another usecase: extremely low-bit quantized representations.
Is something like this already implemented for quantization? Probably a simple version of this feature could be providing some explicitly utility functions like calculating size of the holder uint8 tensor, fused store and load functions (potentially explicitly batched, e.g. actual store is delayed until some aligned number of memory lines has arrived)
In NumPy the related functionality is np.packbits and np.unpackbits, however these are designed to work only with 1-bit contained type. 2-bit/4-bit would be cool as well.
One difficulty is that in many points of our code we assume all tensor elements are addressable (for example, for views), and this would not be the case with bit-packed tensors.
I wonder if we could design some explicit pack/unpack/load/store/index util methods that would be enough for basic usage (like numpy does with packbits/unpackbits)
Maybe we could have some unpack method that is optimal if the user themselves provided dtype-aligned indexes
This new bittensors wouldn't be first class objects, but still utility methods could be enough for first experimentation.
Maybe unpack method could be some variant of narrow that performs a single memory access if the index/length are aligned with container dtype. NestedTensor/vmap could be used to represent the returned unpacked byte tensor list
A simple interface could be packbits / unpackbits like in NumPy with additional bitness argument (to support 1-bit, 2-bit and 4-bit) and dim argument. It should maybe support out argument for unpacked uint8 tensor. Unpacked dimension could always be a new zeroth dimension.
Arguments that can be helpful for packbits/unpackbits:
mask - a bit mask integer, specifying pack/unpack compress mask like in compressexpand instructions -> this is slightly more flexible than a single nbits=1|2|4 arg)
dim -> packing / unpacking along a given dim (during unpacking it can then only be done across an already existing dim, maybe that's fine for dense dimensions)
target dim size may be needed for unpacking to undo the padding
out argument
I guess on CPU packbits/unpackbits can be implemented with those compress/expand SIMD instructions, if the op is performed across contiguous dimension (actually contiguity doesn't matter after a load to a vector register is done already)
pack and unpack seem worth doing. The other parts (i.e. compress/expand) could be useful, but I'm not sure it's worth doing -- it seems like at that point you'd be writing specialized ops in C++ anyway.
I think it's important to have a manual kernel as a baseline for perf comparison at least for some cases to be sure that the generated code is fast enough (or at least to review it / have some tests so that it doesn't evolve to something inefficient with Inductor evolvement and development - in terms of memory loads/stores and vectorization)
After basic bitpacks, it might be good to be able to produce packed bit outputs instead of booltensors directly of some select functions like torch.gt or being able to use them as input to torch.masked_* functions or for elementwise multiplication (masked_zero_), this can save a lot of memory when one needs to save_for_backward some large boolean mask - and maybe also for occupancy grids
maybe also worth supporting the original numpy's API as well: np.packbits/np.unpackbits - which could redirect under the hood to the more general, versatile interface
I guess, for packbits/unpackbits ao is indeed a better place, but for more general BitTensor support in ops as compressed explicit-pack-calls-less alternative to BoolTensor - not sure if this discussion should stay in ao or back in core
BitTensor would also be useful (maybe not absolutely needed for compiled optimizers though, but for expressiveness still useful) for compact storage/encoding of sign output (pytorch/pytorch#130215) - or if TritTensor can be added to store on of three values: -1, 0, 1
Curious, is now the compiled codegen for the most basic numpy-like packbits/unpackbits (bit-compression of bool tensors - can be used for efficient storage of masks of any kinds) comparable to handwritten kernels? (I saw that #291 got merged)
If so - probably worth adding these specialized packbits/unpackbits versions to core torch
Regarding BitTensor: some opaque dtypes are now in core: torch.bit, torch.bits1x8, torch.bits8. So maybe some of these can be used for representing BitTensor (alternatively uint8 dtype can be used same as in nupy)
Some other ops where it makes sense to produce directly bit tensors: torch.gt and similar. And then for consuming: masked_fill and similar.
Curious, why deemed not planned? It's very useful to be able to un/pack booltensor into a compact storage (and to manipulate compact masks) - also given that numpy has this capability
Activity
ezyang commentedon Feb 3, 2020
One difficulty is that in many points of our code we assume all tensor elements are addressable (for example, for views), and this would not be the case with bit-packed tensors.
vadimkantorov commentedon Feb 3, 2020
I wonder if we could design some explicit pack/unpack/load/store/index util methods that would be enough for basic usage (like numpy does with packbits/unpackbits)
Maybe we could have some unpack method that is optimal if the user themselves provided dtype-aligned indexes
This new bittensors wouldn't be first class objects, but still utility methods could be enough for first experimentation.
Maybe unpack method could be some variant of
narrowthat performs a single memory access if the index/length are aligned with container dtype. NestedTensor/vmap could be used to represent the returned unpacked byte tensor list[-][feature request] Bit packed tensors[/-][+][feature request] Bit packed tensors utilities[/+]vadimkantorov commentedon Feb 4, 2020
A simple interface could be packbits / unpackbits like in NumPy with additional bitness argument (to support 1-bit, 2-bit and 4-bit) and dim argument. It should maybe support out argument for unpacked uint8 tensor. Unpacked dimension could always be a new zeroth dimension.
vadimkantorov commentedon Feb 5, 2020
https://www.microsoft.com/en-us/research/uploads/prod/2018/02/KoPhiliposeTashevZarar_ICASSP_2018.pdf suggests that XNOR and POPCNT functionality is useful for 1-bit networks
vadimkantorov commentedon Feb 14, 2020
Arguments that can be helpful for packbits/unpackbits:
mask- a bit mask integer, specifying pack/unpack compress mask like in compress expand instructions -> this is slightly more flexible than a singlenbits=1|2|4arg)dim -> packing / unpacking along a given dim (during unpacking it can then only be done across an already existing dim, maybe that's fine for dense dimensions)
target dim size may be needed for unpacking to undo the padding
out argument
I guess on CPU packbits/unpackbits can be implemented with those compress/expand SIMD instructions, if the op is performed across contiguous dimension (actually contiguity doesn't matter after a load to a vector register is done already)
vadimkantorov commentedon Feb 14, 2020
in my code I'd do sth like:
torch.packbits(something.argmax(dim = -1), mask = 0b11, dim =-1, out = my_uint8_array[k])vadimkantorov commentedon Feb 14, 2020
I think one can think about this feature request as surfacing compress/expand SIMD functionality to user land and reimplementing it on GPU
gchanan commentedon Feb 25, 2020
pack and unpack seem worth doing. The other parts (i.e. compress/expand) could be useful, but I'm not sure it's worth doing -- it seems like at that point you'd be writing specialized ops in C++ anyway.
vadimkantorov commentedon Feb 25, 2020
I thought that given a mask pack/unpack are precisely equivalent to SIMD compress/expand? Aren’t they?
ezyang commentedon Feb 27, 2020
We haven't looked! You're probably right :)
vadimkantorov commentedon Feb 27, 2020
General int4 support request in pytorch/pytorch#33859 is also related
vadimkantorov commentedon Mar 3, 2020
Another useful functionality would be scatter/gather-like functionality for compressing index tensors.
In a practical usecase it can help to compress the hybrid sparse+dense tensor indices by a lot: https://discuss.pytorch.org/t/sparse-torch-topk/71832/4
vadimkantorov commentedon Mar 15, 2020
It seems that <8bit quantization starts to appear: pytorch/pytorch#34783 and seems somewhat related to this discussion
ezyang commentedon Mar 16, 2020
cc @jspark1105
70 remaining items
vadimkantorov commentedon May 29, 2024
I think it's important to have a manual kernel as a baseline for perf comparison at least for some cases to be sure that the generated code is fast enough (or at least to review it / have some tests so that it doesn't evolve to something inefficient with Inductor evolvement and development - in terms of memory loads/stores and vectorization)
After basic bitpacks, it might be good to be able to produce packed bit outputs instead of booltensors directly of some select functions like torch.gt or being able to use them as input to
torch.masked_*functions or for elementwise multiplication (masked_zero_), this can save a lot of memory when one needs to save_for_backward some large boolean mask - and maybe also for occupancy gridsvadimkantorov commentedon May 29, 2024
maybe also worth supporting the original numpy's API as well: np.packbits/np.unpackbits - which could redirect under the hood to the more general, versatile interface
vadimkantorov commentedon Jun 6, 2024
I guess, for packbits/unpackbits ao is indeed a better place, but for more general BitTensor support in ops as compressed explicit-pack-calls-less alternative to BoolTensor - not sure if this discussion should stay in ao or back in core
cpuhrsch commentedon Jun 6, 2024
@vadimkantorov - I think wherever the discussions happens (here or in core), it becomes easier once we have a prototype.
vadimkantorov commentedon Jul 7, 2024
BitTensor would also be useful (maybe not absolutely needed for compiled optimizers though, but for expressiveness still useful) for compact storage/encoding of sign output (pytorch/pytorch#130215) - or if TritTensor can be added to store on of three values: -1, 0, 1
vadimkantorov commentedon Nov 4, 2024
https://github.com/microsoft/BitNet released code, so having some core support / basic ops support (including pack/unpack and quantize(=torch.gt/lt with bit tensor output instead of bool tensor output)/dequantize) for torch.bit (and ternary tensors) might promote more research in extremely compressed binary nets
arg handling (pytorch#292)
vadimkantorov commentedon Mar 6, 2025
Curious, is now the compiled codegen for the most basic numpy-like
packbits/unpackbits(bit-compression of bool tensors - can be used for efficient storage of masks of any kinds) comparable to handwritten kernels? (I saw that #291 got merged)If so - probably worth adding these specialized packbits/unpackbits versions to core torch
Regarding BitTensor: some opaque dtypes are now in core:
torch.bit,torch.bits1x8,torch.bits8. So maybe some of these can be used for representing BitTensor (alternatively uint8 dtype can be used same as in nupy)Some other ops where it makes sense to produce directly bit tensors: torch.gt and similar. And then for consuming: masked_fill and similar.
vadimkantorov commentedon May 12, 2025
Also, on BitTensor / bitmask in the wild usecase:
token bitmasks: https://github.com/vllm-project/vllm/pull/16577/files/5cf804d7f69a4d81fad2399e36724f3c992f8192#diff-a0726d18a97a553ef12f020d2ab9d3878129690b5d379ad5d1de45e4d9a5af27
Hopefully support for BitTensors and packbits can be promoted to core
vadimkantorov commentedon May 15, 2025
For BitNet representation (with values -1, 0, 1) (e.g. https://falcon-lm.github.io/blog/falcon-edge/), maybe a good name would be TritTensor :)
vadimkantorov commentedon Aug 3, 2025
Regarding TritTensor:
More ternary kernels just released https://x.com/imtejas13/status/1951821672602099995
vadimkantorov commentedon Sep 25, 2025
Related:
vadimkantorov commentedon Aug 11, 2026
Curious, why deemed not planned? It's very useful to be able to un/pack booltensor into a compact storage (and to manipulate compact masks) - also given that numpy has this capability