Add train.py, README.md, config.json, training_args.json, model.safetensors
Browse filesFiles changed (5)
- README.mdAdded+64
- config.jsonAdded+16
- model.safetensorsAdded+3
- train.pyAdded+53
- training_args.jsonAdded+9
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364---
license: bsd-3-clause
tags:
- pytorch
- perceiver
- classification
---
# Perceiver for Classification
## Overview
This repository is a compact, custom PyTorch implementation of **Perceiver** for **Classification**. The **giant** configuration is intended for code review, smoke tests, and small controlled experiments rather than as a production-ready pretrained release.
## Repository status
- The Python file contains the model and runnable example or training entry point.
- `config.json` records the generated architecture settings.
- `training_args.json` records the default experiment recipe.
- `model.safetensors` is a valid initialization checkpoint for smoke tests; it is **not** presented as a trained benchmark checkpoint.
- No benchmark score is claimed in this repository.
## Architecture
| Item | Value |
|---|---|
| Architecture | Perceiver |
| Scale | giant |
| Attention | multi query |
| Fusion | tucker |
| Activation | mish |
| Normalization | groupnorm |
## Default experiment recipe
The included configuration uses **lion** with a **step** schedule. These are starting values in the script, not evidence of a completed run. For a meaningful evaluation, train all baselines with the same data exposure, tuning budget, and random seeds.
## Quick check
```bash
python train.py --help
```
Inspect the script's `__main__` block for its generated smoke-test example. Because this is a custom implementation, generic automatic loading APIs require an explicit adapter before use.
## Evaluation guidance
A useful first evaluation would use **a task-specific labeled split**, report the task metric across at least three seeds, and include a matched-capacity baseline. Keep training logs and environment versions with any published result.
## Limitations
The initialization checkpoint has not been trained or audited for robustness, fairness, or domain transfer. The implementation should be treated as an experimental starting point. Results from a future trained checkpoint must be documented separately from the defaults shipped here.
## Files
- `train.py` — primary artifact
- `README.md` — this documentation
- `config.json` — architecture configuration
- `training_args.json` — default experiment settings
- `model.safetensors` — initialization checkpoint
## License
Released under **bsd-3-clause**. Review the source-data terms separately when this repository is used with external datasets.12345678910111213141516{
"architectures": [
"CustomResearchModel"
],
"architecture": "perceiver",
"model_type": "perceiver",
"hidden_size": 192,
"num_hidden_layers": 8,
"num_attention_heads": 8,
"intermediate_size": 384,
"hidden_act": "mish",
"max_position_embeddings": 512,
"layer_norm_eps": 1e-12,
"checkpoint_status": "initialization-only",
"notes": "Untrained checkpoint for smoke tests; no benchmark claim."
}123version https://git-lfs.github.com/spec/v1oid sha256:1758a04d5fd54449b4eb33bfe859f9d6418d1aa9e3b08166e84259271358c2e4size 998081234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import torch, torch.nn as nn, math
class M(nn.Module):
def __init__(self, d=768, L=16, H=12, nc=10):
super().__init__()
self.pe = nn.Conv2d(3, d, 16, 16)
self.cls = nn.Parameter(torch.randn(1,1,d)*.02)
self.pos = nn.Parameter(torch.randn(1,197,d)*.02)
self.blks = nn.ModuleList([nn.TransformerEncoderLayer(d, H, d*4, .1, activation='gelu', batch_first=True, norm_first=True) for _ in range(L)])
self.ln = nn.LayerNorm(d)
self.te = nn.Embedding(30522, d, padding_idx=0)
self.tpos = nn.Parameter(torch.randn(1,128,d)*.02)
self.tblks = nn.ModuleList([nn.TransformerEncoderLayer(d, H, d*4, .1, activation='gelu', batch_first=True, norm_first=True) for _ in range(L)])
self.tln = nn.LayerNorm(d)
self.fuse = nn.ModuleList([nn.TransformerEncoderLayer(d, H, d*4, .1, activation='gelu', batch_first=True, norm_first=True) for _ in range(2)])
self.fln = nn.LayerNorm(d)
self.head = nn.Sequential(nn.Linear(d,d), nn.Mish(), nn.Dropout(.1), nn.Linear(d,nc))
self._init()
def _init(self):
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.kaiming_normal_(m.weight, mode='fan_out')
if m.bias is not None: nn.init.zeros_(m.bias)
def enc_img(self, x):
x = self.pe(x).flatten(2).transpose(1,2)
x = torch.cat([self.cls.expand(x.size(0),-1,-1), x], 1)
x = x + self.pos
for b in self.blks: x = b(x)
return self.ln(x)
def enc_txt(self, ids, mask=None):
x = self.te(ids) + self.tpos[:, :ids.size(1)]
m = (mask == 0) if mask is not None else None
for b in self.tblks: x = b(x, src_key_padding_mask=m)
return self.tln(x)
def forward(self, img, ids, mask=None, lbl=None):
fi = self.enc_img(img)
ft = self.enc_txt(ids, mask)
x = ft
for f in self.fuse: x = f(x)
x = self.fln(x[:, 0])
logits = self.head(x)
loss = nn.functional.cross_entropy(logits, lbl) if lbl is not None else None
return {'logits': logits, 'loss': loss}
if __name__ == '__main__':
m = M()
print(f'Params: {sum(p.numel() for p in m.parameters()):,}')
o = m(torch.randn(2,3,224,224), torch.randint(0,30522,(2,128)), torch.ones(2,128), torch.tensor([0,1]))
print(o['logits'].shape, o['loss'].item())123456789{
"optimizer": "lion",
"scheduler": "step",
"learning_rate": 0.0001,
"batch_size": 32,
"epochs": 20,
"seed": 42,
"status": "default recipe; not a completed run"
}README.mdAdded+64
config.jsonAdded+16
model.safetensorsAdded+3
train.pyAdded+53
training_args.jsonAdded+9