> ## 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.

# Train a classifier on .serva files

> Servamind · Serva Encoder — classify `.serva` file bytes with a Walsh-Hadamard transform and MLP: data-agnostic, non-spatial, plain PyTorch, no decoding.

This tutorial classifies **opaque `.serva` byte streams** without decoding, parsing, or reshaping them into images. The pipeline:

1. **Zero-pad** raw bytes to the next power of 2
2. **Fast Walsh-Hadamard Transform** (FWHT) — a fixed, orthogonal projection that preserves distances in high-dimensional byte space
3. **Truncate** to the first 4 096 low-frequency coefficients
4. **MLP** classifier with LayerNorm, GELU, and Dropout

No convolutions, no spatial assumptions, no pretrained weights. The transform exploits the fact that `.serva` files live in a high-dimensional byte space where distance-preserving projections (Johnson-Lindenstrauss) retain class structure.

***

## Before you start

**Dependencies:** **`torch`** only. No `torchvision`, no `numpy` at runtime. Use a GPU when available (**CUDA** on NVIDIA, **MPS** on Apple Silicon).

**Dataset layout:** one **subfolder per class**, with **`.serva` files** inside each:

```text theme={null}
data/serva_hymenoptera/
  train/
    ants/
      img_00001.serva
      ...
    bees/
      img_00001.serva
      ...
  val/
    ants/
      ...
    bees/
      ...
```

Each `.serva` file is **one training example**. Repeat the same **class folder names** under `train/` and `val/` so label indices stay aligned.

To **create** `.serva` files, use the **[Serva web app](https://serva.servamind.com)**, upload sources, encode, and download.

> [!NOTE]
>
> Every `.serva` file may have a different byte length. The loader **pads** shorter files with zeros to the next power of 2 so every sample has the same feature dimension. No bytes are truncated.

***

## Load data: read `.serva` bytes into tensors

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

import torch
from torch.utils.data import DataLoader, TensorDataset


def load_serva_dataset(root):
    """Load .serva files from class subdirectories."""
    root = Path(root)
    classes = sorted(d.name for d in root.iterdir() if d.is_dir())
    class_to_idx = {c: i for i, c in enumerate(classes)}
    samples = []
    for name in classes:
        for p in sorted((root / name).glob("*.serva")):
            raw = torch.frombuffer(bytearray(p.read_bytes()), dtype=torch.uint8)
            samples.append((raw, class_to_idx[name]))
    return samples, classes


data_dir = Path("data/serva_hymenoptera")

train_samples, class_names = load_serva_dataset(data_dir / "train")
val_samples, _ = load_serva_dataset(data_dir / "val")

print(f"Classes: {class_names}")
print(f"Train: {len(train_samples)}, Val: {len(val_samples)}")
```

> [!TIP]
>
> All files are read into memory once. For small-to-medium datasets this is fast and avoids per-epoch I/O. For very large datasets, wrap the loading in a `Dataset` that reads on demand.

***

## Feature extraction: Walsh-Hadamard transform

The **Fast Walsh-Hadamard Transform** is an orthogonal, distance-preserving projection — analogous to an FFT but over `{+1, −1}` basis vectors. It maps variable-length byte sequences into a fixed-size feature vector without learning any parameters.

```python theme={null}
def fwht(x):
    """Batched Fast Walsh-Hadamard Transform (butterfly, normalized)."""
    N = x.shape[-1]
    h = 1
    while h < N:
        xe = x.view(-1, N // (2 * h), 2, h)
        a, b = xe[:, :, 0, :], xe[:, :, 1, :]
        xe = torch.stack([a + b, a - b], dim=2)
        x = xe.view(-1, N)
        h *= 2
    return x / (N ** 0.5)


def build_features(samples, pad_len, had_dim=4096):
    """Zero-pad raw bytes, apply FWHT, truncate to had_dim."""
    n = len(samples)
    X = torch.zeros(n, pad_len)
    y = torch.empty(n, dtype=torch.long)
    for i, (raw, label) in enumerate(samples):
        k = min(len(raw), pad_len)
        X[i, :k] = raw[:k].float()
        y[i] = label
    H = fwht(X)[:, :had_dim]
    return H, y


# Next power of 2 for padding
max_len = max(len(s[0]) for s in train_samples + val_samples)
pad_len = 1 << (max_len - 1).bit_length()

HAD_DIM = 4096

H_train, y_train = build_features(train_samples, pad_len, HAD_DIM)
H_val, y_val = build_features(val_samples, pad_len, HAD_DIM)

print(f"Max file: {max_len} bytes, Pad: {pad_len}, Features: {HAD_DIM}")
```

> [!NOTE]
>
> Truncating to the first 4 096 coefficients keeps the lowest-frequency components of the Hadamard spectrum. This acts as dimensionality reduction while preserving the most informative structure. The truncation point was validated empirically — 4 096 is the sweet spot for this dataset size.

***

## Model: MLP classifier

A two-hidden-layer MLP with **LayerNorm** on the input (the Hadamard coefficients have varying scale), **GELU** activations, and **Dropout** for regularization.

```python theme={null}
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler


class MLP(nn.Module):
    def __init__(self, in_features, num_classes, hidden=(256, 128), dropout=0.3):
        super().__init__()
        layers = [nn.LayerNorm(in_features)]
        prev = in_features
        for w in hidden:
            layers += [nn.Linear(prev, w), nn.GELU(), nn.Dropout(dropout)]
            prev = w
        layers.append(nn.Linear(prev, num_classes))
        self.net = nn.Sequential(*layers)

    def forward(self, x):
        return self.net(x)


def pick_device():
    if torch.cuda.is_available():
        return torch.device("cuda")
    if torch.backends.mps.is_available():
        return torch.device("mps")
    return torch.device("cpu")


device = pick_device()

torch.manual_seed(42)
model = MLP(HAD_DIM, len(class_names)).to(device)

criterion = nn.CrossEntropyLoss()
optimizer = optim.AdamW(model.parameters(), lr=1e-3, weight_decay=1e-2)
scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=150)

num_params = sum(p.numel() for p in model.parameters())
print(f"Model: MLP[256, 128], {num_params:,} params")
```

> [!NOTE]
>
> **`pin_memory=True`** in the DataLoader is only useful with **CUDA**; on **MPS** (Apple GPU), omit it. **`running_corrects.float()`** in the training loop keeps accuracy math in float32, which works on **CUDA**, **MPS**, and **CPU** — **`.double()`** can error on **MPS** (no float64).

***

## Training loop

Same phase pattern as the standard PyTorch classification tutorial: `train` / `val`, `model.train()` / `model.eval()`, `torch.set_grad_enabled`, scheduler step after each train epoch, keep **best val accuracy** weights.

```python theme={null}
import copy
import time


BATCH = 16
EPOCHS = 150

dataloaders = {
    "train": DataLoader(TensorDataset(H_train, y_train), BATCH, shuffle=True,
                        generator=torch.Generator().manual_seed(42)),
    "val": DataLoader(TensorDataset(H_val, y_val), BATCH, shuffle=False),
}
dataset_sizes = {"train": len(train_samples), "val": len(val_samples)}


def train_model(model, criterion, optimizer, scheduler, num_epochs=EPOCHS):
    since = time.time()
    best_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0

    for epoch in range(num_epochs):
        for phase in ["train", "val"]:
            model.train() if phase == "train" else model.eval()
            running_loss = 0.0
            running_corrects = 0

            for inputs, labels in dataloaders[phase]:
                inputs = inputs.to(device)
                labels = labels.to(device)
                optimizer.zero_grad(set_to_none=True)

                with torch.set_grad_enabled(phase == "train"):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)
                    loss = criterion(outputs, labels)
                    if phase == "train":
                        loss.backward()
                        optimizer.step()

                running_loss += loss.item() * inputs.size(0)
                running_corrects += torch.sum(preds == labels)

            if phase == "train":
                scheduler.step()

            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects.float() / dataset_sizes[phase]

            if phase == "val" and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_wts = copy.deepcopy(model.state_dict())

        if (epoch + 1) % 25 == 0:
            print(f"Epoch {epoch:3d}  loss={epoch_loss:.4f}  val_acc={epoch_acc:.4f}  best={best_acc:.4f}")

    elapsed = time.time() - since
    print(f"\nTraining complete in {elapsed:.1f}s")
    print(f"Best val acc: {best_acc:.4f}")
    model.load_state_dict(best_wts)
    return model


model = train_model(model, criterion, optimizer, scheduler)
```

> [!TIP]
>
> On the hymenoptera dataset (244 train, 152 val), this reaches **\~69% val accuracy** in about 10 seconds on a modern GPU. The Hadamard features are precomputed, so the training loop is purely MLP forward/backward — very fast.


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