torch.frombuffer#
- torch.frombuffer(buffer,*,dtype,count=-1,offset=0,requires_grad=False)→Tensor#
Creates a 1-dimensional
Tensorfrom an object that implementsthe Python buffer protocol.Skips the first
offsetbytes in the buffer, and interprets the rest ofthe raw bytes as a 1-dimensional tensor of typedtypewithcountelements.Note that either of the following must be true:
1.
countis a positive non-zero number, and the total number of bytesin the buffer is more thanoffsetpluscounttimes the size(in bytes) ofdtype.2.
countis negative, and the length (number of bytes) of the buffersubtracted by theoffsetis a multiple of the size (in bytes) ofdtype.The returned tensor and buffer share the same memory. Modifications tothe tensor will be reflected in the buffer and vice versa. The returnedtensor is not resizable.
Note
This function increments the reference count for the object thatowns the shared memory. Therefore, such memory will not be deallocatedbefore the returned tensor goes out of scope.
Warning
This function’s behavior is undefined when passed an object implementingthe buffer protocol whose data is not on the CPU. Doing so is likely tocause a segmentation fault.
Warning
This function does not try to infer the
dtype(hence, it is notoptional). Passing a differentdtypethan its source may resultin unexpected behavior.- Parameters
buffer (object) – a Python object that exposes the buffer interface.
- Keyword Arguments
dtype (
torch.dtype) – the desired data type of returned tensor.count (int,optional) – the number of desired elements to be read.If negative, all the elements (until the end of the buffer) will beread. Default: -1.
offset (int,optional) – the number of bytes to skip at the start ofthe buffer. Default: 0.
requires_grad (bool,optional) – If autograd should record operations on thereturned tensor. Default:
False.
Example:
>>>importarray>>>a=array.array('i',[1,2,3])>>>t=torch.frombuffer(a,dtype=torch.int32)>>>ttensor([ 1, 2, 3])>>>t[0]=-1>>>aarray([-1, 2, 3])>>># Interprets the signed char bytes as 32-bit integers.>>># Each 4 signed char elements will be interpreted as>>># 1 signed 32-bit integer.>>>importarray>>>a=array.array('b',[-1,0,0,0])>>>torch.frombuffer(a,dtype=torch.int32)tensor([255], dtype=torch.int32)