maitri01 commited on
Commit
cbc96dd
·
verified ·
1 Parent(s): 7429eea

Task template: runnable baseline, uint8 NHWC loader

Browse files
Files changed (1) hide show
  1. task_template.py +82 -20
task_template.py CHANGED
@@ -1,12 +1,18 @@
1
- """Machine unlearning challenge - task template.
2
 
3
  You are given
4
  model.pt state dict of a 100-class image classifier (the "original" model)
5
- forget_images.npz the forget set: key "images", uint8 array [N, 224, 224, 3] (RGB). No labels are provided.
 
6
 
7
  Goal: produce a model that behaves like the "gold" model - the same architecture trained with the same recipe on the
8
  same data WITHOUT the forget images - while staying as close as possible to the original model everywhere else.
9
 
 
 
 
 
 
10
  Scoring (computed on the server)
11
  The forget score is measured on the forget images AND on hidden altered copies of them (random crops / flips that you
12
  do not have); the two groups count equally. For each group
@@ -25,39 +31,74 @@ Matching only the average loss is not enough: for every forget image (and unseen
25
  predict what a model that never saw the image would predict, including WHICH wrong class it would choose.
26
 
27
  Submission: a state dict (torch.save(model.state_dict(), "submission.pt")) that loads with strict=True into the
28
- architecture below. float32 weights, no NaN/Inf. The server evaluates in eval mode with float16 autocast.
 
 
 
29
  """
 
 
 
30
  import numpy as np
31
  import timm
32
  import torch
33
 
 
 
 
 
 
34
  NUM_CLASSES = 100
 
 
35
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
36
 
37
 
38
  def build_model() -> torch.nn.Module:
39
  """ViT-B/16 at 224x224 with LayerScale (init 1e-4), exactly as used for the original and gold models."""
40
- return timm.create_model("vit_base_patch16_224", pretrained=False, num_classes=NUM_CLASSES, init_values=1e-4)
 
 
 
 
 
41
 
42
 
43
- def preprocess(images_uint8: torch.Tensor) -> torch.Tensor:
44
- """uint8 [B, 224, 224, 3] -> float32 [B, 3, 224, 224] in [-1, 1] (mean = std = 0.5 per channel)."""
45
- x = images_uint8.to(DEVICE).permute(0, 3, 1, 2).float() / 255.0
46
- return (x - 0.5) / 0.5
 
47
 
48
 
49
- def load_original() -> torch.nn.Module:
50
- model = build_model()
51
- model.load_state_dict(torch.load("model.pt", map_location="cpu"), strict=True)
52
- return model.to(DEVICE)
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
 
55
- def load_forget_images() -> torch.Tensor:
56
- return torch.from_numpy(np.load("forget_images.npz")["images"])
 
 
 
57
 
58
 
59
  @torch.no_grad()
60
  def predict(model: torch.nn.Module, images_uint8: torch.Tensor, batch_size: int = 128) -> torch.Tensor:
 
61
  model.eval()
62
  out = []
63
  for i in range(0, len(images_uint8), batch_size):
@@ -67,15 +108,36 @@ def predict(model: torch.nn.Module, images_uint8: torch.Tensor, batch_size: int
67
 
68
 
69
  def unlearn(model: torch.nn.Module, forget_images: torch.Tensor) -> torch.nn.Module:
70
- """TODO: your unlearning method. Must return a model with the same architecture."""
71
  return model
72
 
73
 
74
- if __name__ == "__main__":
75
- model = load_original()
 
 
 
 
 
 
 
 
 
 
76
  forget_images = load_forget_images()
77
- print("forget set:", tuple(forget_images.shape), forget_images.dtype)
 
 
 
78
  print("original predictions on the first forget images:", predict(model, forget_images[:8]).argmax(1).tolist())
 
 
 
79
  model = unlearn(model, forget_images)
80
- torch.save({k: v.detach().cpu().float() for k, v in model.state_dict().items()}, "submission.pt")
81
- print("saved submission.pt")
 
 
 
 
 
 
1
+ """Machine unlearning challenge - task template (ViT-B/16).
2
 
3
  You are given
4
  model.pt state dict of a 100-class image classifier (the "original" model)
5
+ forget_images.npz the forget set: key "images", uint8 array [N, 224, 224, 3] (N = 3500, RGB, channels LAST).
6
+ No labels are provided.
7
 
8
  Goal: produce a model that behaves like the "gold" model - the same architecture trained with the same recipe on the
9
  same data WITHOUT the forget images - while staying as close as possible to the original model everywhere else.
10
 
11
+ IMAGE FORMAT
12
+ The forget images are raw uint8 pixels in [N, H, W, 3] layout (they are NOT preprocessed and NOT channel-first).
13
+ The model expects float32 [B, 3, 224, 224] normalised to [-1, 1]: x = (pixels / 255 - 0.5) / 0.5.
14
+ Use preprocess() below (it does exactly what the server does) - do not resize or normalise a second time.
15
+
16
  Scoring (computed on the server)
17
  The forget score is measured on the forget images AND on hidden altered copies of them (random crops / flips that you
18
  do not have); the two groups count equally. For each group
 
31
  predict what a model that never saw the image would predict, including WHICH wrong class it would choose.
32
 
33
  Submission: a state dict (torch.save(model.state_dict(), "submission.pt")) that loads with strict=True into the
34
+ architecture below. float32 weights, no NaN/Inf, at most 400 MB. The server evaluates in eval mode with float16 autocast.
35
+
36
+ Running this file loads the provided model and forget images, runs checks, and saves the unchanged original model as a
37
+ baseline submission (it scores about 0). Put your method in unlearn().
38
  """
39
+ import sys
40
+ from pathlib import Path
41
+
42
  import numpy as np
43
  import timm
44
  import torch
45
 
46
+ # CONFIG
47
+ MODEL_FILE = Path("model.pt")
48
+ FORGET_IMAGES_FILE = Path("forget_images.npz")
49
+ OUTPUT_FILE = Path("submission.pt")
50
+
51
  NUM_CLASSES = 100
52
+ IMAGE_SIZE = 224
53
+ EXPECTED_FORGET_IMAGES = 3500
54
  DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
55
 
56
 
57
  def build_model() -> torch.nn.Module:
58
  """ViT-B/16 at 224x224 with LayerScale (init 1e-4), exactly as used for the original and gold models."""
59
+ return timm.create_model(
60
+ "vit_base_patch16_224",
61
+ pretrained=False,
62
+ num_classes=NUM_CLASSES,
63
+ init_values=1e-4,
64
+ )
65
 
66
 
67
+ def load_model(path: Path = MODEL_FILE) -> torch.nn.Module:
68
+ model = build_model()
69
+ state_dict = torch.load(path, map_location="cpu", weights_only=True)
70
+ model.load_state_dict(state_dict, strict=True)
71
+ return model.to(DEVICE).eval()
72
 
73
 
74
+ def load_forget_images(path: Path = FORGET_IMAGES_FILE) -> torch.Tensor:
75
+ """Returns the forget images as uint8 [N, 224, 224, 3] (raw pixels, channels last)."""
76
+ with np.load(path, allow_pickle=False) as data:
77
+ if "images" not in data.files:
78
+ raise KeyError(f"{path} does not contain an 'images' array. Available arrays: {data.files}")
79
+ images = torch.from_numpy(data["images"].copy())
80
+
81
+ if images.dtype != torch.uint8:
82
+ raise ValueError(f"Expected uint8 pixels, got {images.dtype}")
83
+ if images.ndim != 4:
84
+ raise ValueError(f"Expected 4 dimensions [N, H, W, 3], got shape {tuple(images.shape)}")
85
+ if images.shape[-1] != 3 and images.shape[1] == 3: # tolerate channels-first input
86
+ images = images.permute(0, 2, 3, 1).contiguous()
87
+ if tuple(images.shape[1:]) != (IMAGE_SIZE, IMAGE_SIZE, 3):
88
+ raise ValueError(f"Expected images of shape [N, {IMAGE_SIZE}, {IMAGE_SIZE}, 3], got {tuple(images.shape)}")
89
+ return images
90
 
91
 
92
+ def preprocess(images_uint8: torch.Tensor) -> torch.Tensor:
93
+ """uint8 [B, 224, 224, 3] -> float32 [B, 3, 224, 224] in [-1, 1] (mean = std = 0.5 per channel).
94
+ This is exactly the preprocessing the evaluation server applies."""
95
+ x = images_uint8.to(DEVICE).permute(0, 3, 1, 2).float() / 255.0
96
+ return (x - 0.5) / 0.5
97
 
98
 
99
  @torch.no_grad()
100
  def predict(model: torch.nn.Module, images_uint8: torch.Tensor, batch_size: int = 128) -> torch.Tensor:
101
+ """Logits [N, 100] for uint8 images [N, 224, 224, 3], computed like the server (eval mode, fp16 autocast on GPU)."""
102
  model.eval()
103
  out = []
104
  for i in range(0, len(images_uint8), batch_size):
 
108
 
109
 
110
  def unlearn(model: torch.nn.Module, forget_images: torch.Tensor) -> torch.nn.Module:
111
+ """TODO: your unlearning method. Must return a model with the same architecture (same parameters and buffers)."""
112
  return model
113
 
114
 
115
+ def main() -> None:
116
+ print("Loading provided model checkpoint...")
117
+ if not MODEL_FILE.exists():
118
+ print(f"Error: {MODEL_FILE} not found.", file=sys.stderr)
119
+ raise SystemExit(1)
120
+ model = load_model()
121
+ print("Model loaded successfully.")
122
+
123
+ print("Loading forget set images...")
124
+ if not FORGET_IMAGES_FILE.exists():
125
+ print(f"Error: {FORGET_IMAGES_FILE} not found.", file=sys.stderr)
126
+ raise SystemExit(1)
127
  forget_images = load_forget_images()
128
+ print(f"Loaded {len(forget_images)} forget set images with shape {tuple(forget_images.shape)} ({forget_images.dtype}).")
129
+ if len(forget_images) != EXPECTED_FORGET_IMAGES:
130
+ print(f"[WARNING] Expected {EXPECTED_FORGET_IMAGES} forget images, got {len(forget_images)}.")
131
+
132
  print("original predictions on the first forget images:", predict(model, forget_images[:8]).argmax(1).tolist())
133
+
134
+ # Baseline: submit the provided model unchanged (replace unlearn() with your method).
135
+ # The final object must remain a plain state_dict that loads strictly into build_model().
136
  model = unlearn(model, forget_images)
137
+ state_dict = {k: v.detach().cpu().float() for k, v in model.state_dict().items()}
138
+ torch.save(state_dict, OUTPUT_FILE)
139
+ print(f"Saved baseline submission to {OUTPUT_FILE}.")
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()