> ## Documentation Index
> Fetch the complete documentation index at: https://servamind.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Unpack a `.serva` file

> Load .serva bytes into a buffer, a NumPy array, a PyTorch tensor, or read the blocks inside, with no decoding and no password.

A `.serva` file is bytes on disk like any other file. **Unpacking** means loading those bytes into something you can compute on, so a training job or an analysis can read the file as it stands.

**Dependencies:** none for reading the bytes, `numpy` and `torch` for the sections that use them.

***

## Open one file

`Path.read_bytes` returns the whole file as a `bytes` object. There is no reader to install and no password to supply, because nothing is being decoded at this point.

```python theme={null}
from pathlib import Path

raw = Path("sample.serva").read_bytes()
print(len(raw), "bytes")
print(raw[:16].hex())   # the first 16 bytes, as hex
```

***

## Into a NumPy array

Bytes map straight onto `uint8`, one value per byte, in the range 0 to 255.

```python theme={null}
import numpy as np
from pathlib import Path

raw = Path("sample.serva").read_bytes()
x = np.frombuffer(raw, dtype=np.uint8)

print(x.shape, x.dtype)   # (41231,) uint8
```

`np.frombuffer` does not copy, so the array is a view over the bytes you read. Call `.copy()` if you plan to write to it.

***

## Into a PyTorch tensor

Same idea, with one wrinkle worth knowing.

```python theme={null}
import torch
from pathlib import Path

raw = Path("sample.serva").read_bytes()
x = torch.frombuffer(bytearray(raw), dtype=torch.uint8)

print(x.shape, x.dtype)   # torch.Size([41231]) torch.uint8
```

The `bytearray` is worth keeping. `read_bytes` hands back an immutable `bytes` object, and PyTorch has no read only tensor, so passing one straight in warns that the tensor can write into a buffer that is meant to be immutable. Wrapping it gives PyTorch a buffer it is allowed to own and the warning goes away. Cast to `float()` when your model wants floats.

***

## The blocks inside

Everything above treats the file as one flat run of bytes. `get_blocks` reads its structure instead it slices the container on disk and returns each block's hypervector as `uint8`. No request, no key, and nothing is decoded.

```python theme={null}
from serva import get_blocks, get_block

blocks = get_blocks("talk.serva")
print(len(blocks), "blocks")               # 26 blocks
print(blocks[0].shape, blocks[0].dtype)    # (9802,) uint8
print(get_block("talk.serva", 0).shape)    # (9802,) the same block
```

***

## A folder of files

One file is easy. A dataset is where the real work is, because **every `.serva` file has a different length** and nothing stacks into a batch until they all match.

Start by looking at the spread:

```python theme={null}
from pathlib import Path
import numpy as np

files = sorted(Path("data/train").rglob("*.serva"))
sizes = np.array([p.stat().st_size for p in files])

print(f"{len(files)} files")
print(f"smallest {sizes.min():,}  largest {sizes.max():,}  median {int(np.median(sizes)):,}")
```

The simplest thing that works is to pad every file to the largest one:

```python theme={null}
width = int(sizes.max())
X = np.zeros((len(files), width), dtype=np.uint8)

for i, p in enumerate(files):
    raw = p.read_bytes()
    X[i, : len(raw)] = np.frombuffer(raw, dtype=np.uint8)

print(X.shape)   # (n_files, width)
```

That is fine when your files are roughly the same size. When they are not, it is wasteful: a set whose largest file is ten times the median spends most of its memory on zeros. Two ways out:

* **Pick a fixed width** and pad or truncate to it. Cheap and predictable, but anything past the cut is thrown away, so choose it from the size spread rather than by guessing.
* **Pad per batch** instead of per dataset, to the longest file in that batch only, and carry a mask marking which positions are real. Keeps every byte and adds the least padding possible.

> [!TIP]
>
> Whichever you choose, keep the padding value at zero and stay consistent across train and validation. A model that learns where the padding starts is learning file size, not content.

***

## Or let the SDK do it

`ServaDataset` in the Python SDK does everything above for you: it walks the folder, reads each file, handles the length problem, and hands your loader a tensor.

```python theme={null}
from serva.torch import ServaDataset
from torch.utils.data import DataLoader

ds = ServaDataset("data/train")
loader = DataLoader(ds, batch_size=32, shuffle=True)

for batch in loader:
    ...   # your model, your training step
```

Class subfolders become labels, a flat folder gives you bare tensors, and `length=None` with `pad_collate` is the per batch padding described above. The [PyTorch page](https://servamind.mintlify.site/sdk/pytorch.md) covers the options in full.

***

## Where to go next

* [Train a classifier on `.serva` files](https://servamind.mintlify.site/tutorials/training/serva-resnet-tutorial) takes the loaded bytes through feature extraction and a full training run.
* [Visualize `.serva` files](https://servamind.mintlify.site/tutorials/visualization/visualize-serva-files) projects a folder of them to see how they sit relative to each other.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.