File size: 3,834 Bytes
89ae45d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Swin: image classification with Transformers

This page is the Transformers contract of the Swin MIC and also a usage example. [doc-builder](https://github.com/huggingface/doc-builder/blob/main/docs/runnable-code-blocks.md) renders the `runnable` blocks below as documentation, and its pytest plugin runs them as written against `microsoft/swin-tiny-patch4-window7-224`. The MIC runner runs the same blocks against the slim fixture and the checkpoint in [`integration.json`](../../integration.json). Lines marked `# doc-builder: hide` only matter there: they swap in the pinned checkpoint or variant and print the result record.

## Classify images

```py runnable:classify
import torch
from transformers import AutoImageProcessor, AutoModelForImageClassification, set_seed
import json  # doc-builder: hide
import os  # doc-builder: hide

model_id = "microsoft/swin-tiny-patch4-window7-224"
model_id = os.environ.get("MIC_MODEL", model_id)  # doc-builder: hide
variant = json.loads(os.environ.get("MIC_MODEL_KWARGS", "{}"))  # doc-builder: hide
device = "cuda" if torch.cuda.is_available() else "cpu"
set_seed(0)  # seeds torch, NumPy, and Python: loading, dropout, and data augmentation draw random numbers

processor = AutoImageProcessor.from_pretrained(model_id)
model = AutoModelForImageClassification.from_pretrained(model_id).to(device)
if variant:  # doc-builder: hide
    del model  # doc-builder: hide
    model = AutoModelForImageClassification.from_pretrained(model_id, **variant).to(device)  # doc-builder: hide

# Two small synthetic images: a red-to-blue gradient and a green-to-white gradient.
# Build each as (3, H, W) explicitly so the channel dimension is unambiguous.
height = width = 224
red_blue = torch.cat([
    torch.linspace(1, 0, width).view(1, 1, width).expand(1, height, width),
    torch.zeros(1, height, width),
    torch.linspace(0, 1, width).view(1, 1, width).expand(1, height, width),
], dim=0).mul(255).byte()
green_white = torch.cat([
    torch.linspace(0, 1, width).view(1, 1, width).expand(1, height, width),
    torch.linspace(1, 0, width).view(1, 1, width).expand(1, height, width),
    torch.ones(1, height, width),
], dim=0).mul(255).byte()
images = [red_blue, green_white]
inputs = processor(images=images, return_tensors="pt")
inputs = inputs.to(device, dtype=model.dtype)  # cast floating pixel_values, keep integer ids

with torch.no_grad():
    logits = model(**inputs).logits
predicted = logits.argmax(dim=-1)
print([model.config.id2label[i] for i in predicted.tolist()])
```

## One training step

```py runnable:classify:2
labels = torch.tensor([0, 1], device=device)

model.train()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
loss = model(**inputs, labels=labels).loss
loss.backward()
before = {n: p.detach().cpu().clone() for n, p in model.named_parameters() if p.requires_grad}  # doc-builder: hide
optimizer.step()
print(f"loss: {loss.item():.4f}")

if os.environ.get("MIC_RUNNER"):  # doc-builder: hide
    named = dict(model.named_parameters())
    checked = ("classifier.weight", "swin.encoder.layers.0.blocks.0.attention.q_proj.weight")
    result = {
        "runtime": {
            "device": model.device.type,
            "dtype": str(model.dtype).removeprefix("torch."),
            "attn_implementation": model.config._attn_implementation,
        },
        "predicted_classes": predicted.tolist(),
        "logits": {"probe": logits[:, :5].float().tolist()},
        "training": {
            "loss": loss.item(),
            "gradients": {n: bool(named[n].grad is not None and torch.count_nonzero(named[n].grad) > 0 and torch.isfinite(named[n].grad).all()) for n in checked},
            "updated": any(not torch.equal(p.detach().cpu(), before[n]) for n, p in model.named_parameters() if n in before),
        },
    }
    print(json.dumps(result))
```