hyttyh111222333 commited on
Commit
91e9bc4
·
verified ·
1 Parent(s): cc5b729

Upload FAI-Bench task files batch 51

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/README.md +47 -0
  2. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/__init__.py +0 -0
  3. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/_eval.py +209 -0
  4. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/README.md +8 -0
  5. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/generate.py +506 -0
  6. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/model.py +464 -0
  7. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/run.sh +39 -0
  8. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/convert_hf_checkpoint.py +115 -0
  9. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/download.py +48 -0
  10. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/prepare.sh +2 -0
  11. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/.gitignore +3 -0
  12. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/README.md +23 -0
  13. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/benchmark.sh +17 -0
  14. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/data.py +308 -0
  15. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/eval_combo.py +692 -0
  16. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/flash_4_configs.p +0 -0
  17. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/metrics.py +76 -0
  18. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/results.csv +7 -0
  19. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/setup.sh +26 -0
  20. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/__init__.py +11 -0
  21. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/automatic_mask_generator.py +759 -0
  22. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/build_sam.py +166 -0
  23. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1/sam2.1_hiera_l.yaml +120 -0
  24. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1/sam2.1_hiera_t.yaml +121 -0
  25. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1_training/sam2.1_hiera_b+_MOSE_finetune.yaml +339 -0
  26. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/csrc/connected_components.cu +289 -0
  27. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/map_tensor.py +781 -0
  28. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/__init__.py +5 -0
  29. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/__init__.py +5 -0
  30. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/hieradet.py +332 -0
  31. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/image_encoder.py +141 -0
  32. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/utils.py +95 -0
  33. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/memory_attention.py +166 -0
  34. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/memory_encoder.py +181 -0
  35. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/position_encoding.py +226 -0
  36. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/__init__.py +5 -0
  37. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/mask_decoder.py +317 -0
  38. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/prompt_encoder.py +214 -0
  39. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/transformer.py +373 -0
  40. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam2_base.py +929 -0
  41. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam2_utils.py +323 -0
  42. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_b+.yaml +113 -0
  43. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_l.yaml +117 -0
  44. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_s.yaml +116 -0
  45. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_t.yaml +118 -0
  46. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_image_predictor.py +571 -0
  47. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_video_predictor.py +1192 -0
  48. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/__init__.py +5 -0
  49. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/amg.py +523 -0
  50. tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/misc.py +382 -0
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LLAMA
2
+
3
+ ## Eval on Llama 3.1 8B and Llama 3.2 3B
4
+
5
+ We use lm-eval tasks for evaluating TorchAO Quantization APIs on HuggingFace models. The results are in the table below:
6
+
7
+ | Model Name | Quantization Technique | Acc |Acc Norm| Word perplexity| Model Size (GB) |
8
+ |------------|---------------------------|-------|--------|----------------|-------------------|
9
+ | Llama 3.1 8B | None | 60.01 | 78.84 | 7.33 | 15.01 |
10
+ | Llama 3.1 8B | int4wo-128 | 58.10 | 77.06 | 8.25 | 4.76 |
11
+ | Llama 3.1 8B | int8wo | 59.92 | 78.95 | 7.34 | 8.04 |
12
+ | Llama 3.1 8B | int8dq | 60.01 | 78.82 | 7.45 | 8.03 |
13
+ | Llama 3.1 8B | float8wo | 59.83 | 78.61 | 7.37 | 8.03 |
14
+ | Llama 3.1 8B | float8dq (PerRow) | 59.86 | 78.57 | 7.41 | 8.04 |
15
+ | Llama 3.1 8B | float8dq (PerTensor) | 59.95 | 78.66 | 7.42 | 8.03 |
16
+ | Llama 3.1 8B | gemlite (gp=128) | 58.48 | 77.34 | 8.07 | 4.76 |
17
+
18
+ | Model Name | Quantization Technique | Acc |Acc Norm| Word perplexity| Model Size (GB) |
19
+ |------------|---------------------------|-------|--------|----------------|-------------------|
20
+ | Llama 3.2 3B | None | 55.27 | 73.70 | 9.26 | 6.43 |
21
+ | Llama 3.2 3B | int4wo-128 | 53.13 | 71.31 | 10.36 | 2.29 |
22
+ | Llama 3.2 3B | int8wo | 55.15 | 73.44 | 9.28 | 3.61 |
23
+ | Llama 3.2 3B | int8dq | 55.00 | 73.29 | 9.43 | 3.61 |
24
+ | Llama 3.2 3B | float8wo | 55.18 | 73.58 | 9.31 | 3.61 |
25
+ | Llama 3.2 3B | float8dq (PerRow) | 55.18 | 73.37 | 9.33 | 3.61 |
26
+ | Llama 3.2 3B | float8dq (PerTensor) | 55.16 | 73.53 | 9.35 | 3.61 |
27
+ | Llama 3.2 3B | gemlite (gp=128) | 53.71 | 71.99 | 10.05 | 2.29 |
28
+
29
+ To generate the above results run:
30
+ ```
31
+ sh benchmarks/_models/eval_hf_models.sh
32
+ ```
33
+
34
+ To run lm-eval for a different hf-model with AO quantization technique, run:
35
+ ```
36
+ python benchmarks/_models/eval_hf_models.py --model_id meta-llama/Llama-3.1-8B --quantization float8dq-row --tasks wikitext hellaswag
37
+ ```
38
+ Replace model id, quantization and tasks with your desired values Please refer to ([HuggingFace <-> TorchAO](https://huggingface.co/docs/transformers/main/en//quantization/torchao)) integration docs for more details about the supported quantization techniques.
39
+
40
+ # SAM2
41
+ sam2 is a fork of https://github.com/facebookresearch/sam2 at commit c2ec8e14a185632b0a5d8b161928ceb50197eddc
42
+
43
+ It includes
44
+ - modifications to enable fullgraph=True compile
45
+ - `mask_to_rle_pytorch_2`
46
+ - small performance changes and fixes
47
+ - integration into torchao's packaging
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/__init__.py ADDED
File without changes
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/_eval.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD-style license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+
8
+ # This source code is licensed under the license found in the
9
+ # LICENSE file in the root directory of this source tree.
10
+
11
+ import lm_eval
12
+ import torch
13
+ import torch.nn.functional as F
14
+
15
+ from torchao.quantization.GPTQ import MultiTensorInputRecorder
16
+
17
+ try: # lm_eval version 0.4
18
+ from lm_eval.evaluator import evaluate # pyre-ignore[21]
19
+ from lm_eval.models.huggingface import HFLM as eval_wrapper # pyre-ignore[21]
20
+ from lm_eval.tasks import get_task_dict # pyre-ignore[21]
21
+ except: # lm_eval version 0.3
22
+ from lm_eval import base, evaluator, tasks
23
+
24
+ eval_wrapper = base.BaseLM
25
+ get_task_dict = tasks.get_task_dict
26
+ evaluate = evaluator.evaluate
27
+
28
+
29
+ class TransformerEvalWrapper(eval_wrapper):
30
+ """
31
+ A wrapper class for GPTFast, providing integration with the lm-evaluation-harness library.
32
+ """
33
+
34
+ def __init__(
35
+ self, model, tokenizer, max_seq_length, input_prep_func=None, device="cuda"
36
+ ):
37
+ try:
38
+ super().__init__(device=device)
39
+ except TypeError:
40
+ # lm_eval 0.4.2 removed the default init
41
+ super().__init__("gpt2", device="cpu")
42
+
43
+ self._model = model
44
+ self.tokenizer = tokenizer
45
+ self._device = torch.device(device)
46
+ self._max_seq_length = max_seq_length
47
+
48
+ # need to take inps and convert to corrent input
49
+ # for model
50
+ self.input_prep_func = (
51
+ input_prep_func if input_prep_func is not None else lambda x: (x,)
52
+ )
53
+
54
+ def _model_call(self, inps):
55
+ # TODO: make batches work
56
+ input = self.input_prep_func(inps)
57
+
58
+ max_seq_length = min(max(inps.size()), self.max_length)
59
+ with torch.device(self._device):
60
+ self._model.setup_caches(self.batch_size, max_seq_length)
61
+ logits = self._model(*input)
62
+ return logits
63
+
64
+ def run_eval(self, tasks, limit):
65
+ try:
66
+ lm_eval.tasks.initialize_tasks()
67
+ except:
68
+ pass
69
+
70
+ task_dict = get_task_dict(tasks)
71
+ print("Evaluating Model On: ", task_dict)
72
+ with torch.no_grad():
73
+ result = evaluate(
74
+ self,
75
+ task_dict,
76
+ limit=limit,
77
+ )
78
+ for task, res in result["results"].items():
79
+ print(f"{task}: {res}")
80
+ return result
81
+
82
+ @property
83
+ def eot_token_id(self):
84
+ try:
85
+ return self.tokenizer.eos_id()
86
+ except:
87
+ return self.tokenizer.eos_id
88
+
89
+ @property
90
+ def max_length(self):
91
+ return self._max_seq_length
92
+
93
+ @property
94
+ def max_gen_toks(self):
95
+ return 50
96
+
97
+ @property
98
+ def batch_size(self):
99
+ return 1
100
+
101
+ @property
102
+ def device(self):
103
+ return self._device
104
+
105
+ def tok_decode(self, tokens):
106
+ decoded = self.tokenizer.decode(tokens)
107
+ return decoded
108
+
109
+ def tok_encode(self, string: str, **kwargs):
110
+ tokens = self.tokenizer.encode(string)
111
+ if hasattr(self.tokenizer, "bos_id"):
112
+ try:
113
+ tokens = [self.tokenizer.bos_id()] + tokens
114
+ except:
115
+ tokens = [self.tokenizer.bos_id] + tokens
116
+ return tokens
117
+
118
+ def _model_generate(self, context, max_length, eos_token_id):
119
+ raise Exception("unimplemented")
120
+
121
+
122
+ class LMEvalInputRecorder(TransformerEvalWrapper):
123
+ def __init__(
124
+ self,
125
+ tokenizer,
126
+ calibration_seq_length,
127
+ input_prep_func=None,
128
+ vocab_size=32000,
129
+ pad_calibration_inputs=False,
130
+ pad_token=0,
131
+ device="cpu",
132
+ base_input_recorder_class=MultiTensorInputRecorder,
133
+ ):
134
+ super().__init__(
135
+ model=None,
136
+ tokenizer=tokenizer,
137
+ max_seq_length=calibration_seq_length,
138
+ input_prep_func=input_prep_func,
139
+ device=device,
140
+ )
141
+ self.vocab_size = vocab_size
142
+ self.calibration_seq_length = calibration_seq_length
143
+
144
+ self.pad_calibration_inputs = pad_calibration_inputs
145
+ self.pad_token = pad_token
146
+
147
+ # Initialize inputs as a list of two empty lists for input tensors and indices
148
+ self.base_input_recorder = base_input_recorder_class()
149
+
150
+ def record_inputs(self, calibration_tasks, calibration_limit):
151
+ try:
152
+ lm_eval.tasks.initialize_tasks()
153
+ except:
154
+ pass
155
+
156
+ task_dict = get_task_dict(calibration_tasks)
157
+ print("Obtaining GPTQ calibration inputs on: ", calibration_tasks)
158
+
159
+ evaluate(
160
+ self,
161
+ task_dict,
162
+ limit=calibration_limit,
163
+ )
164
+ return self
165
+
166
+ def get_inputs(self): # for BC
167
+ return self.get_recorded_inputs()
168
+
169
+ def get_recorded_inputs(self):
170
+ return self.base_input_recorder.get_recorded_inputs()
171
+
172
+ def get_recorded_args_and_kwargs(self):
173
+ return self.base_input_recorder.get_recorded_args_and_kwargs()
174
+
175
+ def _model_call(self, inps):
176
+ inps = inps.squeeze(0)
177
+ T = len(inps)
178
+ if (
179
+ # Can't use inputs that are too short when padding is disabled
180
+ (T < self.calibration_seq_length and not self.pad_calibration_inputs)
181
+ or
182
+ # Can't use inputs that actually use the token we use for padding
183
+ (self.pad_calibration_inputs and self.pad_token in inps)
184
+ ):
185
+ # Give random output
186
+ return torch.randn(
187
+ (1, T, self.vocab_size), dtype=torch.bfloat16, device=self._device
188
+ )
189
+
190
+ # Pad or truncate to the correct size
191
+ if T >= self.calibration_seq_length:
192
+ inps = inps[: self.calibration_seq_length]
193
+ else:
194
+ inps = F.pad(
195
+ inps, (0, self.calibration_seq_length - T), value=self.pad_token
196
+ )
197
+
198
+ inps = inps.unsqueeze(0)
199
+ model_in = self.input_prep_func(inps)
200
+
201
+ self.base_input_recorder(*model_in)
202
+
203
+ # Output `something` with the correct shape to keep eval going
204
+ return torch.randn(
205
+ (1, T, self.vocab_size), dtype=torch.bfloat16, device=self._device
206
+ )
207
+
208
+
209
+ InputRecorder = LMEvalInputRecorder # for BC
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/README.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ## Mixtral-MoE
2
+
3
+ This folder contains code and scripts for benchmarking the Mixtral-MoE model.
4
+ Running
5
+
6
+ `sh scripts/prepare.sh`
7
+
8
+ should download the model and `sh run.sh` will run teh benchmarks.
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/generate.py ADDED
@@ -0,0 +1,506 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import itertools
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Optional, Tuple
11
+
12
+ import torch
13
+ import torch._dynamo.config
14
+ import torch._inductor.config
15
+
16
+ from torchao.utils import get_model_size_in_bytes
17
+
18
+ torch.manual_seed(0)
19
+
20
+
21
+ def device_sync(device):
22
+ if "cuda" in device:
23
+ torch.cuda.synchronize(device)
24
+ elif "cpu" in device:
25
+ pass
26
+ else:
27
+ print(f"device={device} is not yet suppported")
28
+
29
+
30
+ torch._inductor.config.coordinate_descent_tuning = True
31
+ torch._inductor.config.triton.unique_kernel_names = True
32
+ torch._inductor.config.fx_graph_cache = True # Experimental feature to reduce compilation times, will be on by default in future
33
+ torch._dynamo.config.capture_scalar_outputs = True
34
+
35
+ # support running without installing as a package
36
+ wd = Path(__file__).parent.parent.resolve()
37
+ sys.path.append(str(wd))
38
+
39
+ from model import Transformer
40
+ from sentencepiece import SentencePieceProcessor
41
+
42
+
43
+ def multinomial_sample_one_no_sync(
44
+ probs_sort,
45
+ ): # Does multinomial sampling without a cuda synchronization
46
+ q = torch.empty_like(probs_sort).exponential_(1)
47
+ return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int)
48
+
49
+
50
+ def logits_to_probs(logits, temperature: float = 1.0, top_k: Optional[int] = None):
51
+ logits = logits / max(temperature, 1e-5)
52
+
53
+ if top_k is not None:
54
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
55
+ pivot = v.select(-1, -1).unsqueeze(-1)
56
+ logits = torch.where(logits < pivot, -float("Inf"), logits)
57
+ probs = torch.nn.functional.softmax(logits, dim=-1)
58
+ return probs
59
+
60
+
61
+ def sample(logits, temperature: float = 1.0, top_k: Optional[int] = None):
62
+ probs = logits_to_probs(logits[:, -1], temperature, top_k)
63
+ idx_next = multinomial_sample_one_no_sync(probs)
64
+ return idx_next, probs
65
+
66
+
67
+ def prefill(
68
+ model: Transformer, x: torch.Tensor, input_pos: torch.Tensor, **sampling_kwargs
69
+ ) -> torch.Tensor:
70
+ # input_pos: [B, S]
71
+ logits = model(x, input_pos)
72
+ return sample(logits, **sampling_kwargs)[0]
73
+
74
+
75
+ def decode_one_token(
76
+ model: Transformer, x: torch.Tensor, input_pos: torch.Tensor, **sampling_kwargs
77
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
78
+ # input_pos: [B, 1]
79
+ assert input_pos.shape[-1] == 1
80
+ logits = model(x, input_pos)
81
+ return sample(logits, **sampling_kwargs)
82
+
83
+
84
+ def decode_n_tokens(
85
+ model: Transformer,
86
+ cur_token: torch.Tensor,
87
+ input_pos: torch.Tensor,
88
+ num_new_tokens: int,
89
+ callback=lambda _: _,
90
+ **sampling_kwargs,
91
+ ):
92
+ new_tokens, new_probs = [], []
93
+ for i in range(num_new_tokens):
94
+ with torch.backends.cuda.sdp_kernel(
95
+ enable_flash=False, enable_mem_efficient=False, enable_math=True
96
+ ): # Actually better for Inductor to codegen attention here
97
+ next_token, next_prob = decode_one_token(
98
+ model, cur_token, input_pos, **sampling_kwargs
99
+ )
100
+ next_token, next_prob = next_token.clone(), next_prob.clone()
101
+
102
+ input_pos += 1
103
+ new_tokens.append(next_token.clone())
104
+ callback(new_tokens[-1])
105
+ new_probs.append(next_prob.clone())
106
+ cur_token = next_token
107
+
108
+ return new_tokens, new_probs
109
+
110
+
111
+ def model_forward(model, x, input_pos):
112
+ return model(x, input_pos)
113
+
114
+
115
+ @torch.no_grad()
116
+ def generate(
117
+ model: Transformer,
118
+ prompt: torch.Tensor,
119
+ max_new_tokens: int,
120
+ batch_size: int,
121
+ *,
122
+ interactive: bool,
123
+ callback=lambda x: x,
124
+ **sampling_kwargs,
125
+ ) -> torch.Tensor:
126
+ """
127
+ Takes a conditioning sequence (prompt) as input and continues to generate as many tokens as requested.
128
+ """
129
+ device, _ = prompt.device, prompt.dtype
130
+
131
+ T = prompt.size(-1)
132
+ max_seq_length = (
133
+ min(T + max_new_tokens, model.config.block_size) if not interactive else 350
134
+ )
135
+ new_tokens = max_seq_length - T
136
+
137
+ # duplicate prompt for batch_size
138
+ prompt = prompt.repeat(batch_size, 1)
139
+
140
+ # create an empty tensor of the expected final shape and fill in the current tokens
141
+ seq = torch.empty(batch_size, max_seq_length, dtype=prompt.dtype, device=device)
142
+ seq[:, :T] = prompt
143
+
144
+ with torch.device(device):
145
+ model.setup_caches(max_batch_size=batch_size, max_seq_length=max_seq_length)
146
+
147
+ input_pos = torch.arange(0, T, device=device)
148
+ next_token = prefill(
149
+ model, prompt.view(batch_size, -1), input_pos, **sampling_kwargs
150
+ )
151
+ seq[:, T] = next_token.squeeze()
152
+
153
+ input_pos = torch.tensor([T], device=device, dtype=torch.int)
154
+ generated_tokens, _ = decode_n_tokens(
155
+ model,
156
+ next_token.view(batch_size, -1),
157
+ input_pos,
158
+ new_tokens - 1,
159
+ callback=callback,
160
+ **sampling_kwargs,
161
+ )
162
+ seq = torch.cat((seq[:, : T + 1], *generated_tokens), dim=-1)
163
+
164
+ return seq
165
+
166
+
167
+ def encode_tokens(tokenizer, string, bos=True, device="cuda"):
168
+ tokens = tokenizer.encode(string)
169
+ if bos:
170
+ tokens = [tokenizer.bos_id()] + tokens
171
+ return torch.tensor(tokens, dtype=torch.int, device=device)
172
+
173
+
174
+ def _load_model(checkpoint_path, device, precision):
175
+ with torch.device("meta"):
176
+ model = Transformer.from_name(checkpoint_path.parent.name)
177
+
178
+ try:
179
+ checkpoint = torch.load(str(checkpoint_path), mmap=True, weights_only=True)
180
+ model.load_state_dict(checkpoint, assign=True)
181
+ except:
182
+ model = Transformer.from_name(checkpoint_path.parent.name)
183
+
184
+ model = model.to(device=device, dtype=precision)
185
+ return model.eval()
186
+
187
+
188
+ B_INST, E_INST = "[INST]", "[/INST]"
189
+
190
+
191
+ def main(
192
+ prompt: str = "Hello, my name is",
193
+ interactive: bool = False,
194
+ num_samples: int = 5,
195
+ max_new_tokens: int = 100,
196
+ batch_size: int = 1,
197
+ top_k: int = 200,
198
+ temperature: float = 0.8,
199
+ checkpoint_path: Path = Path("checkpoints/mistralai/Mixtral-8x7B-v0.1/model.pth"),
200
+ compile: bool = True,
201
+ compile_prefill: bool = False,
202
+ moe_quant: Optional[str] = None,
203
+ profile: Optional[Path] = None,
204
+ memory_profile: Optional[Path] = None,
205
+ device="cuda",
206
+ ) -> None:
207
+ """Generates text samples based on a pre-trained Transformer model and tokenizer."""
208
+ assert checkpoint_path.is_file(), checkpoint_path
209
+ tokenizer_path = checkpoint_path.parent / "tokenizer.model"
210
+ assert tokenizer_path.is_file(), str(tokenizer_path)
211
+ print(f"Using device={device}")
212
+ precision = torch.bfloat16
213
+ is_chat = "chat" in str(checkpoint_path)
214
+
215
+ if device == "cuda" and memory_profile is not None:
216
+ torch.cuda.memory._record_memory_history(
217
+ True, trace_alloc_max_entries=500000, trace_alloc_record_context=True
218
+ )
219
+
220
+ print("Loading model ...")
221
+ t0 = time.time()
222
+ model = _load_model(checkpoint_path, "cpu", precision)
223
+
224
+ print(f"Time to load model: {time.time() - t0:.02f} seconds")
225
+ t0 = time.time()
226
+
227
+ tokenizer = SentencePieceProcessor(model_file=str(tokenizer_path))
228
+ encoded = encode_tokens(tokenizer, prompt, bos=True, device=device)
229
+ prompt_length = encoded.size(0)
230
+
231
+ torch.manual_seed(1234)
232
+ model_size = sum(
233
+ [
234
+ p.numel() * p.dtype.itemsize
235
+ for p in itertools.chain(model.parameters(), model.buffers())
236
+ ]
237
+ )
238
+
239
+ from torchao.prototype.moe_quant.utils import (
240
+ MoEQuantConfig,
241
+ UseFakeExtraDimTensor,
242
+ cond_ffn_filter,
243
+ )
244
+ from torchao.quantization.quant_api import (
245
+ Float8DynamicActivationFloat8WeightConfig,
246
+ Float8WeightOnlyConfig,
247
+ Int4WeightOnlyConfig,
248
+ Int8DynamicActivationInt8WeightConfig,
249
+ Int8DynamicActivationIntxWeightConfig,
250
+ Int8WeightOnlyConfig,
251
+ PackedLinearInt8DynamicActivationIntxWeightLayout,
252
+ PerRow,
253
+ quantize_,
254
+ )
255
+
256
+ if moe_quant:
257
+ torch._dynamo.config.capture_dynamic_output_shape_ops = True
258
+ config = None
259
+ if "int8wo-base" in moe_quant:
260
+ config = MoEQuantConfig(Int8WeightOnlyConfig())
261
+
262
+ elif "int8wo" in moe_quant:
263
+ config = MoEQuantConfig(
264
+ Int8WeightOnlyConfig(),
265
+ use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE,
266
+ )
267
+
268
+ elif "int8dq-base" in moe_quant:
269
+ config = MoEQuantConfig(Int8DynamicActivationInt8WeightConfig())
270
+
271
+ elif "int8dq" in moe_quant:
272
+ config = MoEQuantConfig(
273
+ Int8DynamicActivationInt8WeightConfig(),
274
+ use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE,
275
+ )
276
+
277
+ elif "int4wo-base" in moe_quant:
278
+ config = MoEQuantConfig(Int4WeightOnlyConfig())
279
+
280
+ elif "int4wo" in moe_quant:
281
+ config = MoEQuantConfig(
282
+ Int4WeightOnlyConfig(),
283
+ use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE,
284
+ )
285
+
286
+ elif "fp8wo-base" in moe_quant:
287
+ config = MoEQuantConfig(Float8WeightOnlyConfig())
288
+
289
+ elif "fp8wo" in moe_quant:
290
+ config = MoEQuantConfig(
291
+ Float8WeightOnlyConfig(),
292
+ use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE,
293
+ )
294
+
295
+ elif "fp8dq-base" in moe_quant:
296
+ config = MoEQuantConfig(
297
+ Float8DynamicActivationFloat8WeightConfig(granularity=PerRow())
298
+ )
299
+
300
+ elif "fp8dq" in moe_quant:
301
+ config = MoEQuantConfig(
302
+ Float8DynamicActivationFloat8WeightConfig(granularity=PerRow()),
303
+ use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE,
304
+ )
305
+
306
+ elif "intxdq" in moe_quant:
307
+ config = MoEQuantConfig(
308
+ Int8DynamicActivationIntxWeightConfig(
309
+ layout=PackedLinearInt8DynamicActivationIntxWeightLayout(),
310
+ ),
311
+ use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE,
312
+ )
313
+ else:
314
+ assert config is not None, (
315
+ f"expected moe_quant to match one of the options but got {moe_quant}"
316
+ )
317
+
318
+ if config is not None:
319
+ quantize_(model, config, filter_fn=cond_ffn_filter, device=device)
320
+ print(
321
+ f"Time to apply quantization with config {config} to model: {time.time() - t0:.02f} seconds"
322
+ )
323
+
324
+ model.to(device=device)
325
+ device_sync(device=device)
326
+
327
+ if compile:
328
+ # moe quant + compile causes repeated warnings
329
+ import warnings
330
+
331
+ warnings.simplefilter("ignore", lineno=84)
332
+ warnings.simplefilter("ignore", lineno=105)
333
+
334
+ torch._inductor.config.assert_indirect_indexing = False
335
+
336
+ global decode_one_token, prefill
337
+
338
+ if batch_size == 1 and (isinstance(moe_quant, str) and "base" in moe_quant):
339
+ decode_one_token = torch.compile(
340
+ decode_one_token, mode="reduce-overhead", fullgraph=True
341
+ )
342
+ else:
343
+ decode_one_token = torch.compile(decode_one_token, mode="reduce-overhead")
344
+
345
+ if args.compile_prefill:
346
+ prefill = torch.compile(prefill, fullgraph=True, dynamic=True)
347
+
348
+ aggregate_metrics = {
349
+ "tokens_per_sec": [],
350
+ }
351
+ start = -1 if compile else 0
352
+
353
+ for i in range(start, num_samples):
354
+ device_sync(device=device) # MKG
355
+ if i >= 0 and interactive:
356
+ prompt = input("What is your prompt? ")
357
+ if is_chat:
358
+ prompt = f"{B_INST} {prompt.strip()} {E_INST}"
359
+ encoded = encode_tokens(tokenizer, prompt, bos=True, device=device)
360
+
361
+ if interactive and i >= 0:
362
+ buffer = []
363
+ period_id = tokenizer.encode(".")[0]
364
+ done_generating = False
365
+
366
+ def callback(x):
367
+ nonlocal done_generating
368
+ if done_generating:
369
+ return
370
+ buffer.append(tokenizer.decode([period_id] + x.tolist())[1:])
371
+ if x.item() == tokenizer.eos_id():
372
+ done_generating = True
373
+ if len(buffer) == 4 or done_generating:
374
+ print("".join(buffer), end="", flush=True)
375
+ buffer.clear()
376
+ # print(, end='', flush=True)
377
+ else:
378
+ callback = lambda x: x
379
+ t0 = time.perf_counter()
380
+ import contextlib
381
+
382
+ if i != num_samples - 1 or not profile:
383
+ prof = contextlib.nullcontext()
384
+ else:
385
+ torch.profiler._utils._init_for_cuda_graphs()
386
+ prof = torch.profiler.profile()
387
+ with prof:
388
+ y = generate(
389
+ model,
390
+ encoded,
391
+ max_new_tokens,
392
+ batch_size,
393
+ interactive=interactive,
394
+ callback=callback,
395
+ temperature=temperature,
396
+ top_k=top_k,
397
+ )
398
+ if i == -1:
399
+ print(f"Compilation time: {time.perf_counter() - t0:.2f} seconds")
400
+ continue
401
+ if hasattr(prof, "export_chrome_trace"):
402
+ prof.export_chrome_trace(f"{profile}.json")
403
+ device_sync(device=device) # MKG
404
+ t = time.perf_counter() - t0
405
+
406
+ if not interactive:
407
+ pass
408
+ print(tokenizer.decode(y[0].tolist()))
409
+ else:
410
+ print()
411
+ tokens_generated = y.size(-1) - prompt_length
412
+ tokens_sec = tokens_generated / t
413
+ aggregate_metrics["tokens_per_sec"].append(tokens_sec)
414
+ print(
415
+ f"Time for inference {i + 1}: {t:.02f} sec total, {tokens_sec:.02f} tokens/sec"
416
+ )
417
+ print(f"Bandwidth achieved: {model_size * tokens_sec / 1e9:.02f} GB/s")
418
+
419
+ if i == 0 and device == "cuda" and memory_profile is not None:
420
+ snapshot = torch.cuda.memory._snapshot()
421
+ with open(f"{memory_profile}.pickle", "wb") as f:
422
+ from pickle import dump
423
+
424
+ dump(snapshot, f)
425
+ print(
426
+ f"\nmemory profile {memory_profile}.pickle saved, to convert that to a usable file, use",
427
+ "python pytorch/torch/cuda/_memory_viz.py trace_plot <pickle file> -o <desired output name>.html",
428
+ )
429
+ break
430
+
431
+ tokpersec = torch.mean(torch.tensor(aggregate_metrics["tokens_per_sec"])).item()
432
+ print(f"Average tokens/sec: {tokpersec:.2f}")
433
+ if batch_size > 1:
434
+ print(f"Average tokens/sec including batches {batch_size * tokpersec:.2f}")
435
+ print(f"Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB")
436
+ print(f"model size: {get_model_size_in_bytes(model) / 1e9:.02f}")
437
+
438
+
439
+ if __name__ == "__main__":
440
+ import argparse
441
+
442
+ parser = argparse.ArgumentParser(description="Your CLI description.")
443
+
444
+ parser.add_argument(
445
+ "--prompt", type=str, default="Hello, my name is", help="Input prompt."
446
+ )
447
+ parser.add_argument(
448
+ "--interactive",
449
+ action="store_true",
450
+ help="Whether to launch in interactive mode",
451
+ )
452
+ parser.add_argument("--num_samples", type=int, default=5, help="Number of samples.")
453
+ parser.add_argument(
454
+ "--max_new_tokens", type=int, default=200, help="Maximum number of new tokens."
455
+ )
456
+ parser.add_argument(
457
+ "--batch_size", type=int, default=1, help="Batch size to benchmark with"
458
+ )
459
+ parser.add_argument("--top_k", type=int, default=200, help="Top-k for sampling.")
460
+ parser.add_argument(
461
+ "--temperature", type=float, default=0.8, help="Temperature for sampling."
462
+ )
463
+ parser.add_argument(
464
+ "--checkpoint_path",
465
+ type=Path,
466
+ default=Path("checkpoints/meta-Transformer/Transformer-2-7b-chat-hf/model.pth"),
467
+ help="Model checkpoint path.",
468
+ )
469
+ parser.add_argument(
470
+ "--compile", action="store_true", help="Whether to compile the model."
471
+ )
472
+ parser.add_argument(
473
+ "--compile_prefill",
474
+ action="store_true",
475
+ help="Whether to compile the prefill (improves prefill perf, but higher compile times)",
476
+ )
477
+ # parser.add_argument('-q', '--quantization', type=str, help='Which quantization techniques to apply: int8dq, int8wo, int4wo, fp8')
478
+ parser.add_argument(
479
+ "--moe_quant",
480
+ type=str,
481
+ help="Which quantization techniques to apply: int8dq, int8wo, int4wo, fp8wo, fp8dq",
482
+ )
483
+ parser.add_argument("--profile", type=Path, default=None, help="Profile path.")
484
+ parser.add_argument(
485
+ "--memory_profile", type=Path, default=None, help="filename for memory profile."
486
+ )
487
+ parser.add_argument("--device", type=str, default="cuda", help="device to use")
488
+
489
+ args = parser.parse_args()
490
+ print(args)
491
+ main(
492
+ args.prompt,
493
+ args.interactive,
494
+ args.num_samples,
495
+ args.max_new_tokens,
496
+ args.batch_size,
497
+ args.top_k,
498
+ args.temperature,
499
+ args.checkpoint_path,
500
+ args.compile,
501
+ args.compile_prefill,
502
+ args.moe_quant,
503
+ args.profile,
504
+ args.memory_profile,
505
+ args.device,
506
+ )
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/model.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ from dataclasses import dataclass
7
+ from typing import Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ from torch import Tensor
12
+ from torch.nn import functional as F
13
+
14
+ from torchao.prototype.moe_quant.utils import FakeExtraDimTensor
15
+
16
+
17
+ def find_multiple(n: int, k: int) -> int:
18
+ if n % k == 0:
19
+ return n
20
+ return n + k - (n % k)
21
+
22
+
23
+ @dataclass
24
+ class ModelArgs:
25
+ block_size: int = 2048
26
+ vocab_size: int = 32000
27
+ n_layer: int = 32
28
+ n_head: int = 32
29
+ dim: int = 4096
30
+ intermediate_size: int = None
31
+ n_local_heads: int = -1
32
+ head_dim: int = 64
33
+ rope_base: float = 10000
34
+ norm_eps: float = 1e-5
35
+ num_experts: int = 8
36
+ num_activated_experts: int = 2
37
+
38
+ def __post_init__(self):
39
+ if self.n_local_heads == -1:
40
+ self.n_local_heads = self.n_head
41
+ if self.intermediate_size is None:
42
+ hidden_dim = 4 * self.dim
43
+ n_hidden = int(2 * hidden_dim / 3)
44
+ self.intermediate_size = find_multiple(n_hidden, 256)
45
+ self.head_dim = self.dim // self.n_head
46
+
47
+ @classmethod
48
+ def from_name(cls, name: str):
49
+ if name in transformer_configs:
50
+ return cls(**transformer_configs[name])
51
+ # fuzzy search
52
+ config = [
53
+ config
54
+ for config in transformer_configs
55
+ if config in str(name).upper() or config in str(name)
56
+ ]
57
+ assert len(config) == 1, name
58
+ return cls(**transformer_configs[config[0]])
59
+
60
+
61
+ transformer_configs = {
62
+ "Mixtral-8x7B-Instruct-v0.1": dict(
63
+ block_size=32768,
64
+ n_layer=32,
65
+ n_head=32,
66
+ n_local_heads=8,
67
+ dim=4096,
68
+ intermediate_size=14336,
69
+ rope_base=1000000.0,
70
+ num_experts=8,
71
+ num_activated_experts=2,
72
+ ),
73
+ }
74
+
75
+
76
+ class KVCache(nn.Module):
77
+ def __init__(
78
+ self, max_batch_size, max_seq_length, n_heads, head_dim, dtype=torch.bfloat16
79
+ ):
80
+ super().__init__()
81
+ cache_shape = (max_batch_size, n_heads, max_seq_length, head_dim)
82
+ self.register_buffer("k_cache", torch.zeros(cache_shape, dtype=dtype))
83
+ self.register_buffer("v_cache", torch.zeros(cache_shape, dtype=dtype))
84
+
85
+ def update(self, input_pos, k_val, v_val):
86
+ # input_pos: [S], k_val: [B, H, S, D]
87
+ assert input_pos.shape[0] == k_val.shape[2]
88
+
89
+ k_out = self.k_cache
90
+ v_out = self.v_cache
91
+ k_out[:, :, input_pos] = k_val
92
+ v_out[:, :, input_pos] = v_val
93
+
94
+ return k_out, v_out
95
+
96
+
97
+ class Transformer(nn.Module):
98
+ def __init__(self, config: ModelArgs) -> None:
99
+ super().__init__()
100
+ self.config = config
101
+
102
+ self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim)
103
+ self.layers = nn.ModuleList(
104
+ TransformerBlock(config) for _ in range(config.n_layer)
105
+ )
106
+ self.norm = RMSNorm(config.dim, eps=config.norm_eps)
107
+ self.output = nn.Linear(config.dim, config.vocab_size, bias=False)
108
+
109
+ self.freqs_cis: Optional[Tensor] = None
110
+ self.mask_cache: Optional[Tensor] = None
111
+ self.max_batch_size = -1
112
+ self.max_seq_length = -1
113
+
114
+ def setup_caches(self, max_batch_size, max_seq_length):
115
+ if (
116
+ self.max_seq_length >= max_seq_length
117
+ and self.max_batch_size >= max_batch_size
118
+ ):
119
+ return
120
+ head_dim = self.config.dim // self.config.n_head
121
+ max_seq_length = find_multiple(max_seq_length, 8)
122
+ self.max_seq_length = max_seq_length
123
+ self.max_batch_size = max_batch_size
124
+ for b in self.layers:
125
+ b.attention.kv_cache = KVCache(
126
+ max_batch_size, max_seq_length, self.config.n_local_heads, head_dim
127
+ )
128
+
129
+ self.freqs_cis = precompute_freqs_cis(
130
+ self.config.block_size,
131
+ self.config.dim // self.config.n_head,
132
+ self.config.rope_base,
133
+ )
134
+ self.causal_mask = torch.tril(
135
+ torch.ones(self.max_seq_length, self.max_seq_length, dtype=torch.bool)
136
+ )
137
+
138
+ def forward(self, idx: Tensor, input_pos: Optional[Tensor] = None) -> Tensor:
139
+ assert self.freqs_cis is not None, "Caches must be initialized first"
140
+ mask = self.causal_mask[None, None, input_pos]
141
+ freqs_cis = self.freqs_cis[input_pos]
142
+ x = self.tok_embeddings(idx)
143
+
144
+ for i, layer in enumerate(self.layers):
145
+ x = layer(x, input_pos, freqs_cis, mask)
146
+ x = self.norm(x)
147
+ logits = self.output(x)
148
+ return logits
149
+
150
+ @classmethod
151
+ def from_name(cls, name: str):
152
+ return cls(ModelArgs.from_name(name))
153
+
154
+
155
+ class TransformerBlock(nn.Module):
156
+ def __init__(self, config: ModelArgs) -> None:
157
+ super().__init__()
158
+ self.attention = Attention(config)
159
+ self.block_sparse_moe = MOEFeedForwardAOQuantizable(config)
160
+ self.ffn_norm = RMSNorm(config.dim, config.norm_eps)
161
+ self.attention_norm = RMSNorm(config.dim, config.norm_eps)
162
+
163
+ def forward(
164
+ self, x: Tensor, input_pos: Tensor, freqs_cis: Tensor, mask: Tensor
165
+ ) -> Tensor:
166
+ h = x + self.attention(self.attention_norm(x), freqs_cis, mask, input_pos)
167
+ out = h + self.block_sparse_moe(self.ffn_norm(h))
168
+ return out
169
+
170
+
171
+ class Attention(nn.Module):
172
+ def __init__(self, config: ModelArgs):
173
+ super().__init__()
174
+ assert config.dim % config.n_head == 0
175
+
176
+ total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim
177
+ # key, query, value projections for all heads, but in a batch
178
+ self.wqkv = nn.Linear(config.dim, total_head_dim, bias=False)
179
+ self.wo = nn.Linear(config.dim, config.dim, bias=False)
180
+ self.kv_cache = None
181
+
182
+ self.n_head = config.n_head
183
+ self.head_dim = config.head_dim
184
+ self.n_local_heads = config.n_local_heads
185
+ self.dim = config.dim
186
+ self._register_load_state_dict_pre_hook(self.load_hook)
187
+
188
+ def load_hook(self, state_dict, prefix, *args):
189
+ if prefix + "wq.weight" in state_dict:
190
+ wq = state_dict.pop(prefix + "wq.weight")
191
+ wk = state_dict.pop(prefix + "wk.weight")
192
+ wv = state_dict.pop(prefix + "wv.weight")
193
+ state_dict[prefix + "wqkv.weight"] = torch.cat([wq, wk, wv])
194
+
195
+ def forward(
196
+ self,
197
+ x: Tensor,
198
+ freqs_cis: Tensor,
199
+ mask: Tensor,
200
+ input_pos: Optional[Tensor] = None,
201
+ ) -> Tensor:
202
+ bsz, seqlen, _ = x.shape
203
+
204
+ kv_size = self.n_local_heads * self.head_dim
205
+ q, k, v = self.wqkv(x).split([self.dim, kv_size, kv_size], dim=-1)
206
+
207
+ q = q.view(bsz, seqlen, self.n_head, self.head_dim)
208
+ k = k.view(bsz, seqlen, self.n_local_heads, self.head_dim)
209
+ v = v.view(bsz, seqlen, self.n_local_heads, self.head_dim)
210
+
211
+ q = apply_rotary_emb(q, freqs_cis)
212
+ k = apply_rotary_emb(k, freqs_cis)
213
+
214
+ q, k, v = map(lambda x: x.transpose(1, 2), (q, k, v))
215
+
216
+ if self.kv_cache is not None:
217
+ k, v = self.kv_cache.update(input_pos, k, v)
218
+
219
+ k = k.repeat_interleave(self.n_head // self.n_local_heads, dim=1)
220
+ v = v.repeat_interleave(self.n_head // self.n_local_heads, dim=1)
221
+ y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0)
222
+
223
+ y = y.transpose(1, 2).contiguous().view(bsz, seqlen, self.dim)
224
+
225
+ y = self.wo(y)
226
+ return y
227
+
228
+
229
+ # class ConditionalFeedForward(nn.Module):
230
+ # def __init__(self, config):
231
+ # super().__init__()
232
+ # self.w1 = nn.Parameter(torch.empty(config.num_experts, config.intermediate_size, config.dim))
233
+ # self.w2 = nn.Parameter(torch.empty(config.num_experts, config.dim, config.intermediate_size))
234
+ # self.w3 = nn.Parameter(torch.empty(config.num_experts, config.intermediate_size, config.dim))
235
+
236
+ # def forward(self, x: Tensor, expert_indices: Tensor) -> Tensor:
237
+ # w1_weights = self.w1[expert_indices] # [T, A, D, D]
238
+ # w3_weights = self.w3[expert_indices] # [T, A, D, D]
239
+ # w2_weights = self.w2[expert_indices] # [T, A, D, D]
240
+ # x1 = F.silu(torch.einsum('ti,taoi -> tao', x, w1_weights))
241
+ # x3 = torch.einsum('ti, taoi -> tao', x, w3_weights)
242
+ # expert_outs = torch.einsum('tao, taio -> tai', (x1 * x3), w2_weights)
243
+ # return expert_outs
244
+
245
+
246
+ # class MOEFeedForward(nn.Module):
247
+ # def __init__(self, config) -> None:
248
+ # super().__init__()
249
+ # self.gate = nn.Linear(config.dim, config.num_experts, bias=False)
250
+ # self.cond_ffn = ConditionalFeedForward(config)
251
+ # self.dim = config.dim
252
+ # self.num_activated_experts = config.num_activated_experts
253
+ # def forward(self, x: Tensor) -> Tensor:
254
+ # x = x.view(-1, self.dim)
255
+ # # T = num_tokens, E = num_experts, D = hidden dim, A = activated experts
256
+ # # x: [T, D]
257
+ # scores = self.gate(x) # [T, E]
258
+ # expert_weights = F.softmax(scores, dim=-1)
259
+ # expert_weights, expert_indices = torch.topk(expert_weights, self.num_activated_experts, dim=-1) # [T, A], [T, A]
260
+ # expert_weights /= expert_weights.sum(dim=-1, keepdim=True) # [T, A]
261
+ # expert_outs = self.cond_ffn(x, expert_indices)
262
+ # return torch.einsum('tai,ta -> ti', expert_outs, expert_weights)
263
+
264
+
265
+ class RMSNorm(nn.Module):
266
+ def __init__(self, dim: int, eps: float = 1e-5):
267
+ super().__init__()
268
+ self.eps = eps
269
+ self.weight = nn.Parameter(torch.ones(dim))
270
+
271
+ def _norm(self, x):
272
+ return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps)
273
+
274
+ def forward(self, x: Tensor) -> Tensor:
275
+ output = self._norm(x.float()).type_as(x)
276
+ return output * self.weight
277
+
278
+
279
+ def precompute_freqs_cis(seq_len: int, n_elem: int, base: int = 10000) -> Tensor:
280
+ freqs = 1.0 / (
281
+ base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem)
282
+ )
283
+ t = torch.arange(seq_len, device=freqs.device)
284
+ freqs = torch.outer(t, freqs)
285
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
286
+ cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1)
287
+ return cache.to(dtype=torch.bfloat16)
288
+
289
+
290
+ def apply_rotary_emb(x: Tensor, freqs_cis: Tensor) -> Tensor:
291
+ xshaped = x.float().reshape(*x.shape[:-1], -1, 2)
292
+ freqs_cis = freqs_cis.view(1, xshaped.size(1), 1, xshaped.size(3), 2)
293
+ x_out2 = torch.stack(
294
+ [
295
+ xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1],
296
+ xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1],
297
+ ],
298
+ -1,
299
+ )
300
+
301
+ x_out2 = x_out2.flatten(3)
302
+ return x_out2.type_as(x)
303
+
304
+
305
+ # T tokens
306
+ # E experts
307
+ # D dim
308
+ # I intermediate dim
309
+ # A activated experts
310
+ # T'(e) tokens for expert e
311
+
312
+
313
+ class MOEFeedForwardAOQuantizable(nn.Module):
314
+ def __init__(self, config) -> None:
315
+ super().__init__()
316
+ self.gate = nn.Linear(config.dim, config.num_experts, bias=False)
317
+ self.cond_ffn = ConditionalFeedForwardAOQuantizable(config)
318
+ self.dim = config.dim
319
+ self.num_activated_experts = config.num_activated_experts
320
+
321
+ def forward(self, x: Tensor) -> Tensor:
322
+ batch_size = x.shape[0]
323
+ x = x.view(-1, self.dim) # x: [T, D]
324
+ scores = self.gate(x) # [T, E]
325
+ expert_weights = F.softmax(scores, dim=-1)
326
+ expert_weights, expert_indices = torch.topk(
327
+ expert_weights, self.num_activated_experts, dim=-1
328
+ ) # [T, A], [T, A]
329
+ expert_weights /= expert_weights.sum(dim=-1, keepdim=True).to(x.dtype) # [T, A]
330
+ out = self.cond_ffn(
331
+ x, expert_indices, expert_weights, self.num_activated_experts
332
+ )
333
+ return out.reshape(batch_size, -1, self.dim)
334
+
335
+
336
+ class ConditionalFeedForwardAOQuantizable(nn.Module):
337
+ def __init__(self, config):
338
+ super().__init__()
339
+ self.config = config
340
+ self.w1 = nn.Parameter(
341
+ torch.empty(config.num_experts, config.intermediate_size, config.dim)
342
+ ) # E, I, D
343
+ self.w2 = nn.Parameter(
344
+ torch.empty(config.num_experts, config.dim, config.intermediate_size)
345
+ ) # E, D, I
346
+ self.w3 = nn.Parameter(
347
+ torch.empty(config.num_experts, config.intermediate_size, config.dim)
348
+ ) # E, I, D
349
+ self.num_experts = config.num_experts
350
+
351
+ def forward(
352
+ self,
353
+ x: Tensor, # T, D
354
+ expert_indices: Tensor, # T, A
355
+ expert_weights: Tensor, # T, A
356
+ num_activated_experts: int,
357
+ ) -> Tensor:
358
+ num_tokens, dim = x.shape
359
+ num_token_activations = num_tokens * num_activated_experts
360
+ if x.shape[0] == 1 and not isinstance(
361
+ self.w1, FakeExtraDimTensor
362
+ ): # only 1 token (can be done without graph breaks when compiled)
363
+ outs = []
364
+ expert_indices = expert_indices.view(num_activated_experts)
365
+ # collect used experts
366
+ w1 = self.w1[expert_indices]
367
+ w2 = self.w2[expert_indices]
368
+ w3 = self.w3[expert_indices]
369
+
370
+ # run token through each expert
371
+ for index in range(num_activated_experts):
372
+ y1 = F.silu(F.linear(x, w1[index]))
373
+ y3 = F.linear(x, w3[index])
374
+ y2 = w2[index]
375
+ cur_out = F.linear(y1 * y3, y2)
376
+ outs.append(cur_out)
377
+
378
+ # combine outputs
379
+ final_out = (
380
+ (torch.cat(outs, dim=0) * expert_weights.view(-1, 1))
381
+ .sum(dim=0)
382
+ .unsqueeze(-1)
383
+ )
384
+ return final_out
385
+ else:
386
+ expert_list = [x for x in range(self.num_experts)]
387
+
388
+ # shuffle tokens into groups for each expert
389
+ ordered_token_activations = expert_indices.view(-1).argsort(
390
+ stable=True
391
+ ) # [A]
392
+ ordered_token_indices = (
393
+ ordered_token_activations.div(num_activated_experts)
394
+ .floor()
395
+ .to(torch.int64)
396
+ ) # [T]
397
+
398
+ if not expert_indices.is_cuda: # histc doesn't work on cpu for integers
399
+ num_tokens_per_expert = torch.bincount(
400
+ expert_indices.view(-1) + 1, minlength=self.num_experts + 1
401
+ )
402
+ else:
403
+ num_tokens_per_expert = torch.histc(
404
+ expert_indices,
405
+ bins=self.num_experts + 1,
406
+ min=-1,
407
+ max=self.num_experts,
408
+ ) # [E+1] (added leading 0 so can be used for indexing)
409
+ cum_tokens_per_expert = num_tokens_per_expert.cumsum(0).to(
410
+ torch.int64
411
+ ) # [E+1]
412
+
413
+ @torch._dynamo.disable()
414
+ def group_tokens_by_expert(
415
+ ordered_token_indices, cum_tokens_per_expert, expert_list
416
+ ):
417
+ token_indices_per_expert = [
418
+ ordered_token_indices[
419
+ cum_tokens_per_expert[expert] : cum_tokens_per_expert[
420
+ expert + 1
421
+ ]
422
+ ]
423
+ for expert in expert_list
424
+ ] # [T'(e1)], [T'(e2)] ...
425
+ return token_indices_per_expert
426
+
427
+ token_indices_per_expert = group_tokens_by_expert(
428
+ ordered_token_indices, cum_tokens_per_expert, expert_list
429
+ )
430
+ tokens_grouped_by_expert = [
431
+ x[indices] for indices in token_indices_per_expert
432
+ ]
433
+
434
+ # calculate outputs for each expert
435
+ outs = []
436
+ for cur_x, expert in zip(tokens_grouped_by_expert, expert_list):
437
+ w1 = self.w1[expert] # I, D
438
+ w2 = self.w2[expert] # D, I
439
+ w3 = self.w3[expert] # I, D
440
+
441
+ cur_out = F.linear(
442
+ F.silu(F.linear(cur_x, w1)) * F.linear(cur_x, w3), w2
443
+ ) # [T'(e), D]
444
+ outs.append(cur_out)
445
+
446
+ # weigh outputs
447
+ ordered_outs = torch.cat(outs, dim=0) # [T*A, D]
448
+ ordered_token_activation_weights = expert_weights.view(-1, 1)[
449
+ ordered_token_activations
450
+ ].view(-1, 1) # [T*A, 1]
451
+ weighted_ordered_outs = (
452
+ ordered_outs * ordered_token_activation_weights
453
+ ) # [T*A, D]
454
+
455
+ # sum weighted token-activation outputs together for each token
456
+ final_out = torch.zeros_like(x) # [T, D]
457
+ final_out = final_out.scatter_add(
458
+ dim=0,
459
+ index=ordered_token_indices.unsqueeze(-1)
460
+ .expand(num_token_activations, dim)
461
+ .to(torch.int64),
462
+ src=weighted_ordered_outs,
463
+ )
464
+ return final_out
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/run.sh ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export MODEL_REPO=mistralai/Mixtral-8x7B-Instruct-v0.1
2
+ export CHECKPOINT_PATH=checkpoints/
3
+
4
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --compile
5
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --compile
6
+
7
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int8wo --compile
8
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int8wo --compile
9
+
10
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int8wo-base --compile
11
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int8wo-base --compile
12
+
13
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int4wo --compile
14
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int4wo --compile
15
+
16
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int4wo-base --compile
17
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int4wo-base --compile
18
+
19
+ # # EXPERT CHOICE
20
+ # # python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int8dq --compile
21
+ # # # # python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int8dq --compile
22
+ # # python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int8dq-base --compile
23
+ # # # # python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int8dq-base --compile
24
+
25
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant fp8wo --compile
26
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant fp8wo --compile
27
+
28
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant fp8wo-base --compile
29
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant fp8wo-base --compile
30
+
31
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant fp8dq --compile
32
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant fp8dq --compile
33
+
34
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant fp8dq-base --compile
35
+ python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant fp8dq-base --compile
36
+
37
+ # ARM
38
+ # python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant intxdq --device cpu
39
+ # python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant intxdq --compile --device cpu
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/convert_hf_checkpoint.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import glob
7
+ import re
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Optional
11
+
12
+ import torch
13
+
14
+ # support running without installing as a package
15
+ wd = Path(__file__).parent.parent.resolve()
16
+ sys.path.append(str(wd))
17
+
18
+ from model import ModelArgs
19
+
20
+
21
+ @torch.inference_mode()
22
+ def convert_hf_checkpoint(
23
+ *,
24
+ checkpoint_dir: Path = Path("checkpoints/mistralai/Mixtral-8x7B-v0.1"),
25
+ model_name: Optional[str] = None,
26
+ ) -> None:
27
+ if model_name is None:
28
+ model_name = checkpoint_dir.name
29
+
30
+ config = ModelArgs.from_name(model_name)
31
+ print(f"Model config {config.__dict__}")
32
+
33
+ weight_map = {
34
+ "tok_embeddings.weight": "tok_embeddings.weight",
35
+ "layers.{}.attention.wq.weight": "layers.{}.attention.wq.weight",
36
+ "layers.{}.attention.wk.weight": "layers.{}.attention.wk.weight",
37
+ "layers.{}.attention.wv.weight": "layers.{}.attention.wv.weight",
38
+ "layers.{}.attention.wo.weight": "layers.{}.attention.wo.weight",
39
+ "layers.{}.block_sparse_moe.w1": "layers.{}.block_sparse_moe.cond_ffn.w1",
40
+ "layers.{}.block_sparse_moe.w2": "layers.{}.block_sparse_moe.cond_ffn.w2",
41
+ "layers.{}.block_sparse_moe.w3": "layers.{}.block_sparse_moe.cond_ffn.w3",
42
+ "layers.{}.block_sparse_moe.gate.weight": "layers.{}.block_sparse_moe.gate.weight",
43
+ "layers.{}.attention_norm.weight": "layers.{}.attention_norm.weight",
44
+ "layers.{}.ffn_norm.weight": "layers.{}.ffn_norm.weight",
45
+ "norm.weight": "norm.weight",
46
+ "output.weight": "output.weight",
47
+ }
48
+
49
+ pt_files = glob.glob(str(checkpoint_dir / "*.pt"))
50
+
51
+ merged_result = {}
52
+ for file in sorted(pt_files):
53
+ state_dict = torch.load(
54
+ str(file), map_location="cpu", mmap=True, weights_only=True
55
+ )
56
+ merged_result.update(state_dict)
57
+ final_result = {}
58
+ for key, value in merged_result.items():
59
+ if "layers" in key:
60
+ abstract_key = re.sub(r".(\d+).", ".{}.", key)
61
+ layer_num = re.search(r"\d+", key).group(0)
62
+ new_key = weight_map[abstract_key]
63
+ if new_key is None:
64
+ continue
65
+ new_key = new_key.format(layer_num)
66
+ else:
67
+ new_key = weight_map[key]
68
+
69
+ final_result[new_key] = value
70
+
71
+ for key in tuple(final_result.keys()):
72
+ if "wq" in key:
73
+ q = final_result[key]
74
+ k = final_result[key.replace("wq", "wk")]
75
+ v = final_result[key.replace("wq", "wv")]
76
+ final_result[key.replace("wq", "wqkv")] = torch.cat([q, k, v])
77
+ del final_result[key]
78
+ del final_result[key.replace("wq", "wk")]
79
+ del final_result[key.replace("wq", "wv")]
80
+ elif "w1" in key or "w3" in key:
81
+ final_result[key] = (
82
+ final_result[key]
83
+ .reshape(config.num_experts, config.intermediate_size, config.dim)
84
+ .contiguous()
85
+ )
86
+ elif "w2" in key:
87
+ final_result[key] = (
88
+ final_result[key]
89
+ .reshape(config.num_experts, config.intermediate_size, config.dim)
90
+ .permute(0, 2, 1)
91
+ .contiguous()
92
+ )
93
+ elif "gate" in key:
94
+ final_result[key] = final_result[key].contiguous()
95
+
96
+ print(f"Saving checkpoint to {checkpoint_dir / 'model.pth'}")
97
+ torch.save(final_result, checkpoint_dir / "model.pth")
98
+
99
+
100
+ if __name__ == "__main__":
101
+ import argparse
102
+
103
+ parser = argparse.ArgumentParser(description="Convert HuggingFace checkpoint.")
104
+ parser.add_argument(
105
+ "--checkpoint_dir",
106
+ type=Path,
107
+ default=Path("checkpoints/mistralai/Mixtral-8x7B-v0.1"),
108
+ )
109
+ parser.add_argument("--model_name", type=str, default=None)
110
+
111
+ args = parser.parse_args()
112
+ convert_hf_checkpoint(
113
+ checkpoint_dir=args.checkpoint_dir,
114
+ model_name=args.model_name,
115
+ )
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/download.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import os
7
+ from typing import Optional
8
+
9
+ from requests.exceptions import HTTPError
10
+
11
+
12
+ def hf_download(repo_id: Optional[str] = None, hf_token: Optional[str] = None) -> None:
13
+ from huggingface_hub import snapshot_download
14
+
15
+ os.makedirs(f"checkpoints/{repo_id}", exist_ok=True)
16
+ try:
17
+ snapshot_download(
18
+ repo_id,
19
+ local_dir=f"checkpoints/{repo_id}",
20
+ local_dir_use_symlinks=False,
21
+ token=hf_token,
22
+ ignore_patterns="*.safetensors",
23
+ )
24
+ except HTTPError as e:
25
+ if e.response.status_code == 401:
26
+ print(
27
+ "You need to pass a valid `--hf_token=...` to download private checkpoints."
28
+ )
29
+ else:
30
+ raise e
31
+
32
+
33
+ if __name__ == "__main__":
34
+ import argparse
35
+
36
+ parser = argparse.ArgumentParser(description="Download data from HuggingFace Hub.")
37
+ parser.add_argument(
38
+ "--repo_id",
39
+ type=str,
40
+ default="mistralai/Mixtral-8x7B-Instruct-v0.1",
41
+ help="Repository ID to download from.",
42
+ )
43
+ parser.add_argument(
44
+ "--hf_token", type=str, default=None, help="HuggingFace API token."
45
+ )
46
+
47
+ args = parser.parse_args()
48
+ hf_download(args.repo_id, args.hf_token)
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/prepare.sh ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ python scripts/download.py --repo_id mistralai/Mixtral-8x7B-Instruct-v0.1
2
+ python scripts/convert_hf_checkpoint.py --checkpoint_dir checkpoints/mistralai/Mixtral-8x7B-Instruct-v0.1
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ tmp
2
+ checkpoints
3
+ datasets
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/README.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # benchmarking instructions:
2
+
3
+ Setup your enviornment with:
4
+ ```
5
+ conda env create -n "saf-ao" python=3.10
6
+ conda activate saf-ao
7
+ pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu126
8
+ pip3 install git+https://github.com/pytorch-labs/segment-anything-fast.git
9
+ pip3 install tqdm fire pandas
10
+ cd ../.. && python setup.py install
11
+ ```
12
+
13
+ Then download data and models by running
14
+ ```
15
+ sh setup.sh
16
+ ```
17
+
18
+ Finally, you can run benchmarks with
19
+ ```
20
+ sh benchmark.sh
21
+ ```
22
+
23
+ You can check out the result in results.csv
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/benchmark.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ # baseline
7
+ python eval_combo.py --coco_root_dir datasets/coco2017 --coco_slice_name val2017 --sam_checkpoint_base_path checkpoints --sam_model_type vit_h --point_sampling_cache_dir tmp/sam_coco_mask_center_cache --mask_debug_out_dir tmp/sam_eval_masks_out --batch_size 32 --num_workers 32 --use_compile max-autotune --use_half bfloat16 --device cuda --print_header True
8
+ # int8 dynamic quant (all)
9
+ python eval_combo.py --coco_root_dir datasets/coco2017 --coco_slice_name val2017 --sam_checkpoint_base_path checkpoints --sam_model_type vit_h --point_sampling_cache_dir tmp/sam_coco_mask_center_cache --mask_debug_out_dir tmp/sam_eval_masks_out --batch_size 32 --num_workers 32 --use_compile max-autotune --use_half bfloat16 --device cuda --compress int8_dynamic_quant
10
+ # 2:4 sparsity (all)
11
+ python eval_combo.py --coco_root_dir datasets/coco2017 --coco_slice_name val2017 --sam_checkpoint_base_path checkpoints --sam_model_type vit_h --point_sampling_cache_dir tmp/sam_coco_mask_center_cache --mask_debug_out_dir tmp/sam_eval_masks_out --batch_size 32 --num_workers 32 --use_compile max-autotune --use_half bfloat16 --device cuda --compress sparse_mlp_only
12
+ # 2:4 sparsity (mlp only)
13
+ python eval_combo.py --coco_root_dir datasets/coco2017 --coco_slice_name val2017 --sam_checkpoint_base_path checkpoints --sam_model_type vit_h --point_sampling_cache_dir tmp/sam_coco_mask_center_cache --mask_debug_out_dir tmp/sam_eval_masks_out --batch_size 32 --num_workers 32 --use_compile max-autotune --use_half bfloat16 --device cuda --compress sparse
14
+ # int8 dynamic quant + 2:4 sparsity (attn: int8, mlp lin1: int8+2:4 fuse mul, mlp lin2: 2:4 sparse)
15
+ python eval_combo.py --coco_root_dir datasets/coco2017 --coco_slice_name val2017 --sam_checkpoint_base_path checkpoints --sam_model_type vit_h --point_sampling_cache_dir tmp/sam_coco_mask_center_cache --mask_debug_out_dir tmp/sam_eval_masks_out --batch_size 32 --num_workers 32 --use_compile max-autotune --use_half bfloat16 --device cuda --compress int8_dynamic_quant_sparse
16
+ # int8 dynamic quant attn + int4 wo + sparse marlin lin 1 + 2:4 sparse lin2
17
+ python eval_combo.py --coco_root_dir datasets/coco2017 --coco_slice_name val2017 --sam_checkpoint_base_path checkpoints --sam_model_type vit_h --point_sampling_cache_dir tmp/sam_coco_mask_center_cache --mask_debug_out_dir tmp/sam_eval_masks_out --batch_size 32 --num_workers 32 --use_compile max-autotune --use_half float16 --device cuda --compress int4_weight_only_sparse
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/data.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import diskcache
7
+ import numpy as np
8
+ import skimage.color as color
9
+ import skimage.io as io
10
+ import torch
11
+ from pycocotools.coco import COCO
12
+ from scipy import ndimage
13
+
14
+
15
+ def _get_center_point(mask, ann_id, cache):
16
+ """
17
+ This is a rudimentary version of https://arxiv.org/pdf/2304.02643.pdf,
18
+ section D.1.Point Sampling
19
+
20
+ From the paper: "The first point is chosen deterministically as the point
21
+ farthest from the object boundary."
22
+
23
+ The code below is an approximation of this.
24
+
25
+ First, we try to calculate the center of mass. If it's inside the mask, we
26
+ stop here.
27
+
28
+ The centroid may be outside of the mask for some mask shapes. In this case
29
+ we do a slow hack, specifically, we check for the
30
+ minumum of the maximum distance from the boundary in four directions
31
+ (up, right, down, left), and take the point with the maximum of these
32
+ minimums. Note: this is not performant for large masks.
33
+
34
+ Returns the center point in (x, y) format
35
+ """
36
+ if ann_id in cache:
37
+ return cache[ann_id]
38
+
39
+ # try the center of mass, keep it if it's inside the mask
40
+ com_y, com_x = ndimage.center_of_mass(mask)
41
+ com_y, com_x = int(round(com_y, 0)), int(round(com_x, 0))
42
+ if mask[com_y][com_x]:
43
+ cache[ann_id] = (com_x, com_y)
44
+ return (com_x, com_y)
45
+
46
+ # if center of mass didn't work, do the slow manual approximation
47
+
48
+ # up, right, down, left
49
+ # TODO(future): approximate better by adding more directions
50
+ distances_to_check_deg = [0, 90, 180, 270]
51
+
52
+ global_min_max_distance = float("-inf")
53
+ global_coords = None
54
+ # For now, terminate early to speed up the calculation as long as
55
+ # the point sample is gooe enough. This sacrifices the quality of point
56
+ # sampling for speed. In the future we can make this more accurate.
57
+ DISTANCE_GOOD_ENOUGH_THRESHOLD = 20
58
+
59
+ # Note: precalculating the bounding box could be somewhat
60
+ # helpful, but checked the performance gain and it's not much
61
+ # so leaving it out to keep the code simple.
62
+ # Note: tried binary search instead of incrementing by one to
63
+ # travel up/right/left/down, but that does not handle masks
64
+ # with all shapes properly (there could be multiple boundaries).
65
+ for row_idx in range(mask.shape[0]):
66
+ for col_idx in range(mask.shape[1]):
67
+ cur_point = mask[row_idx, col_idx]
68
+
69
+ # skip points inside bounding box but outside mask
70
+ if not cur_point:
71
+ continue
72
+
73
+ max_distances = []
74
+ for direction in distances_to_check_deg:
75
+ # TODO(future) binary search instead of brute forcing it if we
76
+ # need a speedup, with the cache it doesn't really matter though
77
+ if direction == 0:
78
+ # UP
79
+ cur_row_idx = row_idx
80
+
81
+ while cur_row_idx >= 0 and mask[cur_row_idx, col_idx]:
82
+ cur_row_idx = cur_row_idx - 1
83
+ cur_row_idx += 1
84
+ distance = row_idx - cur_row_idx
85
+ max_distances.append(distance)
86
+
87
+ elif direction == 90:
88
+ # RIGHT
89
+ cur_col_idx = col_idx
90
+
91
+ while (
92
+ cur_col_idx <= mask.shape[1] - 1 and mask[row_idx, cur_col_idx]
93
+ ):
94
+ cur_col_idx += 1
95
+ cur_col_idx -= 1
96
+ distance = cur_col_idx - col_idx
97
+ max_distances.append(distance)
98
+
99
+ elif direction == 180:
100
+ # DOWN
101
+ cur_row_idx = row_idx
102
+ while (
103
+ cur_row_idx <= mask.shape[0] - 1 and mask[cur_row_idx, col_idx]
104
+ ):
105
+ cur_row_idx = cur_row_idx + 1
106
+ cur_row_idx -= 1
107
+ distance = cur_row_idx - row_idx
108
+ max_distances.append(distance)
109
+
110
+ elif direction == 270:
111
+ # LEFT
112
+ cur_col_idx = col_idx
113
+ while cur_col_idx >= 0 and mask[row_idx, cur_col_idx]:
114
+ cur_col_idx -= 1
115
+ cur_col_idx += 1
116
+ distance = col_idx - cur_col_idx
117
+ max_distances.append(distance)
118
+
119
+ min_max_distance = min(max_distances)
120
+ if min_max_distance > global_min_max_distance:
121
+ global_min_max_distance = min_max_distance
122
+ global_coords = (col_idx, row_idx)
123
+ if global_min_max_distance >= DISTANCE_GOOD_ENOUGH_THRESHOLD:
124
+ break
125
+
126
+ cache[ann_id] = global_coords
127
+ return global_coords
128
+
129
+
130
+ def build_datapoint(
131
+ imgId,
132
+ coco,
133
+ pixel_mean,
134
+ pixel_std,
135
+ coco_root_dir,
136
+ coco_slice_name,
137
+ catIds,
138
+ cache,
139
+ predictor,
140
+ pad_input_image_batch,
141
+ ):
142
+ img = coco.loadImgs(imgId)[0]
143
+
144
+ file_location = f"{coco_root_dir}/{coco_slice_name}/{img['file_name']}"
145
+ I = io.imread(file_location)
146
+ if len(I.shape) == 2:
147
+ # some images, like img_id==61418, are grayscale
148
+ # convert to RGB to ensure the rest of the pipeline works
149
+ I = color.gray2rgb(I)
150
+
151
+ # load and display instance annotations
152
+ annIds = coco.getAnnIds(imgIds=img["id"], catIds=catIds, iscrowd=None)
153
+ anns = coco.loadAnns(annIds)
154
+
155
+ # approximate the center point of each mask
156
+ coords_list = []
157
+ gt_masks_list = []
158
+ for ann in anns:
159
+ ann_id = ann["id"]
160
+ mask = coco.annToMask(ann)
161
+ gt_masks_list.append(torch.tensor(mask))
162
+ coords = _get_center_point(mask, ann_id, cache)
163
+ coords_list.append(coords)
164
+
165
+ image = I
166
+
167
+ # predictor_set_image begin
168
+ # Transform the image to the form expected by the model
169
+ input_image = predictor.transform.apply_image(image)
170
+ input_image_torch = torch.as_tensor(input_image)
171
+ input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :]
172
+ predictor_input_size = input_image_torch.shape[-2:]
173
+
174
+ # Preprocess
175
+ x = input_image_torch
176
+ # Normalize colors
177
+ x = (x - pixel_mean) / pixel_std
178
+
179
+ if pad_input_image_batch:
180
+ # Pad
181
+ h, w = x.shape[-2:]
182
+ padh = predictor.model.image_encoder.img_size - h
183
+ padw = predictor.model.image_encoder.img_size - w
184
+ x = torch.nn.functional.pad(x, (0, padw, 0, padh))
185
+ else:
186
+ x = x.squeeze(0)
187
+
188
+ gt_masks_list = torch.stack(gt_masks_list) if len(gt_masks_list) else None
189
+ return image, coords_list, gt_masks_list, anns, x, predictor_input_size
190
+
191
+
192
+ def build_data(
193
+ coco_img_ids,
194
+ coco,
195
+ catIds,
196
+ coco_root_dir,
197
+ coco_slice_name,
198
+ point_sampling_cache_dir,
199
+ predictor,
200
+ use_half,
201
+ pad_input_image_batch,
202
+ ):
203
+ cache = diskcache.Cache(point_sampling_cache_dir)
204
+ # make sure you clear the cache if you change the point sampling algorithm
205
+ # cache.clear()
206
+
207
+ pixel_mean = predictor.model.pixel_mean.cpu()
208
+ pixel_std = predictor.model.pixel_std.cpu()
209
+
210
+ def build_batch(indicies):
211
+ batch = [[], [], [], [], [], [], [], [], [], [], []]
212
+ batch[3] = [0]
213
+ batch[6] = [0]
214
+ for img_idx in indicies:
215
+ imgId = coco_img_ids[img_idx]
216
+
217
+ datapoint = build_datapoint(
218
+ imgId,
219
+ coco,
220
+ pixel_mean,
221
+ pixel_std,
222
+ coco_root_dir,
223
+ coco_slice_name,
224
+ catIds,
225
+ cache,
226
+ predictor,
227
+ pad_input_image_batch,
228
+ )
229
+ I, coords_list, gt_masks_list, anns, x, predictor_input_size = datapoint
230
+ if len(coords_list) == 0:
231
+ continue
232
+ batch[0].append(x)
233
+ # batch[0].append(x[0])
234
+ coords_list = predictor.transform.apply_coords(
235
+ np.array(coords_list), I.shape[:2]
236
+ )
237
+ coords_list = torch.tensor(coords_list, dtype=torch.float)
238
+
239
+ batch[1].append(coords_list.reshape(-1))
240
+ batch[2].append(coords_list.size())
241
+ batch[3].append(coords_list.numel() + batch[3][-1])
242
+
243
+ batch[4].append(gt_masks_list.reshape(-1))
244
+ batch[5].append(gt_masks_list.size())
245
+ batch[6].append(gt_masks_list.numel() + batch[6][-1])
246
+
247
+ batch[7].append(anns)
248
+ batch[8].append(I)
249
+ batch[9].append(predictor_input_size)
250
+ batch[10].append(img_idx)
251
+
252
+ def cat_and_cast(b, use_half):
253
+ b = torch.cat(b) if len(b) > 0 else None
254
+ if use_half is not None and b is not None:
255
+ return b.to(use_half)
256
+ return b
257
+
258
+ def to_nested_tensor(data, sizes=None, use_half=None):
259
+ if len(data) == 0:
260
+ return None
261
+ dtype = use_half if use_half is not None else torch.float32
262
+
263
+ if sizes is not None:
264
+ data = [d.view(s) for (d, s) in zip(data, sizes)]
265
+
266
+ return torch.nested.nested_tensor(data, dtype=dtype, layout=torch.jagged)
267
+
268
+ if pad_input_image_batch:
269
+ batch[0] = cat_and_cast(batch[0], use_half)
270
+ else:
271
+ batch[0] = to_nested_tensor(batch[0], use_half=use_half)
272
+
273
+ batch[1] = cat_and_cast(batch[1], use_half)
274
+
275
+ batch[4] = cat_and_cast(batch[4], False)
276
+
277
+ return batch
278
+
279
+ return build_batch
280
+
281
+
282
+ def setup_coco_img_ids(coco_root_dir, coco_slice_name, coco_category_names, img_id):
283
+ annFile = "{}/annotations/instances_{}.json".format(coco_root_dir, coco_slice_name)
284
+
285
+ # initialize COCO api for instance annotations
286
+ coco = COCO(annFile)
287
+
288
+ # display COCO categories and supercategories
289
+ cats = coco.loadCats(coco.getCatIds())
290
+ cat_id_to_cat = {cat["id"]: cat for cat in cats}
291
+ # print('COCO categories: \n{}\n'.format(' '.join(nms)))
292
+
293
+ # nms = set([cat['supercategory'] for cat in cats])
294
+ # print('COCO supercategories: \n{}'.format(' '.join(nms)))
295
+
296
+ if coco_category_names is not None:
297
+ catIds = coco.getCatIds(catNms=coco_category_names)
298
+ else:
299
+ catIds = coco.getCatIds()
300
+
301
+ if img_id is not None:
302
+ coco_img_ids = [img_id]
303
+ elif coco_category_names is None:
304
+ coco_img_ids = coco.getImgIds()
305
+ else:
306
+ coco_img_ids = coco.getImgIds(catIds=catIds)
307
+
308
+ return coco_img_ids, cat_id_to_cat, catIds, coco
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/eval_combo.py ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import math
7
+ import resource
8
+ import time
9
+
10
+ import fire
11
+ import torch
12
+ import tqdm
13
+ from data import build_data, setup_coco_img_ids
14
+ from metrics import calculate_miou, create_result_entry
15
+
16
+ import torchao
17
+ from torchao._models.utils import (
18
+ get_arch_name,
19
+ write_json_result_local,
20
+ write_json_result_ossci,
21
+ )
22
+ from torchao.dtypes import SemiSparseLayout
23
+ from torchao.prototype.quantization.autoquant_v2 import autoquant_v2
24
+ from torchao.quantization import (
25
+ autoquant,
26
+ int4_weight_only,
27
+ int8_dynamic_activation_int8_weight,
28
+ quantize_,
29
+ )
30
+ from torchao.sparsity import apply_fake_sparsity, semi_sparse_weight, sparsify_
31
+ from torchao.utils import TORCH_VERSION_AT_LEAST_2_5, unwrap_tensor_subclass
32
+
33
+ torch._dynamo.config.cache_size_limit = 50000
34
+
35
+
36
+ def unbind_jagged(device, data, sizes, offsets):
37
+ if data is None:
38
+ return None
39
+ data = data.to(device=device, non_blocking=True)
40
+ return [
41
+ data[offsets[batch_idx] : offsets[batch_idx + 1]].view(sizes[batch_idx])
42
+ for batch_idx in range(len(sizes))
43
+ ]
44
+
45
+
46
+ PADDED_TENSOR = None
47
+
48
+
49
+ # Preallocate a "landing" Tensor for incoming data and reuse it across launches.
50
+ def pad_to_batch_size(batch, batch_size, device):
51
+ assert batch.dim() == 4
52
+ # assert batch.is_pinned()
53
+ global PADDED_TENSOR
54
+ if PADDED_TENSOR is None:
55
+ batch = batch.to(device=device, non_blocking=True)
56
+ full_batch_size = (batch_size, batch.size(1), batch.size(2), batch.size(3))
57
+ first_entry = batch[0].unsqueeze(0)
58
+ repeat_first_entry = first_entry.expand(full_batch_size)
59
+ padded_batch = torch.cat(
60
+ [batch, repeat_first_entry[batch.size(0) : batch_size]], dim=0
61
+ )
62
+ assert padded_batch.size() == full_batch_size
63
+ PADDED_TENSOR = padded_batch
64
+ PADDED_TENSOR[: batch.size(0)].copy_(batch, non_blocking=True)
65
+ return PADDED_TENSOR
66
+
67
+
68
+ def get_features_batch(
69
+ encoder, input_image_batch, pad_input_image_batch, batch_size, device
70
+ ):
71
+ if pad_input_image_batch:
72
+ features_batch = encoder(
73
+ pad_to_batch_size(input_image_batch, batch_size, device)
74
+ )
75
+ return features_batch[: input_image_batch.size(0)]
76
+ return encoder(input_image_batch)
77
+
78
+
79
+ def build_results_batch(predictor, batch, batch_size, pad_input_image_batch):
80
+ encoder = predictor.model.image_encoder
81
+ device = predictor.device
82
+
83
+ input_image_batch = batch[0]
84
+ # The number of valid data points varies slightly per batch
85
+ orig_input_image_batch_size = input_image_batch.size(0)
86
+ if input_image_batch is None:
87
+ return (None, None, None)
88
+
89
+ with torch.autograd.profiler.record_function("data transfer"):
90
+ coords_lists = unbind_jagged(*([device] + batch[1:4]))
91
+ gt_masks_lists = unbind_jagged(*([device] + batch[4:7]))
92
+ if coords_lists is None:
93
+ return (None, None, None)
94
+ datapoints = list(zip(*(batch[7:] + [coords_lists, gt_masks_lists])))
95
+ if pad_input_image_batch:
96
+ # Pad to a static shape to avoid recompilation
97
+ input_image_batch = pad_to_batch_size(input_image_batch, batch_size, device)
98
+ else:
99
+ input_image_batch = input_image_batch.to(device=device, non_blocking=True)
100
+
101
+ # We explicitly exclude data transfers from the timing to focus
102
+ # only on the kernel performance.
103
+ # Next we synchronize and set two events to start timing.
104
+ if torch.cuda.is_available():
105
+ torch.cuda.synchronize()
106
+ start_event = torch.cuda.Event(enable_timing=True)
107
+ end_event = torch.cuda.Event(enable_timing=True)
108
+ start_event.record()
109
+ else:
110
+ t0 = time.time()
111
+
112
+ with torch.autograd.profiler.record_function("timed region"):
113
+ with torch.autograd.profiler.record_function("image encoder"):
114
+ features_batch = encoder(input_image_batch)
115
+ features_batch = features_batch[:orig_input_image_batch_size]
116
+
117
+ with torch.autograd.profiler.record_function("predict_torch"):
118
+ result_batch = []
119
+ for batch_idx, (
120
+ anns,
121
+ image,
122
+ input_size,
123
+ idx,
124
+ coords,
125
+ gt_masks,
126
+ ) in enumerate(datapoints):
127
+ features = features_batch.narrow(0, batch_idx, 1)
128
+ predictor.reset_image()
129
+ predictor.original_size = image.shape[:2]
130
+ predictor.input_size = input_size
131
+ predictor.features = features
132
+ predictor.is_image_set = True
133
+ coords = coords.unsqueeze(1)
134
+ fg_labels = torch.ones(
135
+ (coords.size(0), 1), dtype=torch.int, device=device
136
+ )
137
+ masks, scores, logits = predictor.predict_torch(
138
+ point_coords=coords,
139
+ point_labels=fg_labels,
140
+ multimask_output=True,
141
+ )
142
+ entry = create_result_entry(anns, gt_masks, masks, scores, idx)
143
+ result_batch += entry
144
+
145
+ # After all kernels have been launched we synchronize again and measure
146
+ # the amount of time spent on the GPU. This is a fairly tight measurement
147
+ # around the launched GPU kernels and excludes data movement from host
148
+ # to device.
149
+ if torch.cuda.is_available():
150
+ end_event.record()
151
+ torch.cuda.synchronize()
152
+ elapsed_time = start_event.elapsed_time(end_event)
153
+ else:
154
+ elapsed_time = time.time() - t0
155
+ return result_batch, orig_input_image_batch_size, elapsed_time
156
+
157
+
158
+ def build_results(
159
+ batched_data_iter,
160
+ predictor,
161
+ mask_debug_out_dir,
162
+ batch_size,
163
+ use_compile,
164
+ use_compile_decoder,
165
+ pad_input_image_batch,
166
+ compress,
167
+ use_fullgraph=False,
168
+ ):
169
+ # TODO: Re-enable this for datapoints
170
+ assert not use_compile_decoder
171
+
172
+ batch_runner = build_results_batch
173
+
174
+ results = []
175
+ batch_idx = 0
176
+ num_images = 0
177
+ num_batches = 0
178
+ elapsed_time = 0
179
+ partial_batch = False
180
+ for batch in tqdm.tqdm(batched_data_iter):
181
+ with torch.no_grad():
182
+ if batch_idx == 0:
183
+ with torch.autograd.profiler.record_function("compilation and warmup"):
184
+ if str(use_compile) != "False":
185
+ predictor.model.image_encoder = torch.compile(
186
+ predictor.model.image_encoder,
187
+ mode=use_compile,
188
+ fullgraph=use_fullgraph,
189
+ )
190
+ # Run first batch a few times for warmup and exclude it from the final timings
191
+ for _ in range(5):
192
+ _ = batch_runner(
193
+ predictor, batch, batch_size, pad_input_image_batch
194
+ )
195
+ result_batch, num_datapoints, kernel_time = batch_runner(
196
+ predictor, batch, batch_size, pad_input_image_batch
197
+ )
198
+ if result_batch is not None:
199
+ results += result_batch
200
+ # We expect a partial batch to only happens once at the end
201
+ assert not partial_batch
202
+ # Only measure timing on full batches
203
+ if num_datapoints == batch_size:
204
+ num_images += num_datapoints
205
+ num_batches += 1
206
+ # We consistently exclude the last (512 - filtered) images
207
+ # Since batch sizes must be powers of two and less than
208
+ # or equal 512 this ensures consistent timing across varying
209
+ # batch sizes.
210
+ if num_images <= 4488:
211
+ elapsed_time += kernel_time
212
+ else:
213
+ partial_batch = True
214
+ batch_idx += 1
215
+
216
+ avg_ms_per_img = None
217
+ if num_images > 0:
218
+ avg_ms_per_img = elapsed_time
219
+ avg_ms_per_img = avg_ms_per_img / num_images
220
+
221
+ return results, avg_ms_per_img, num_batches, num_images
222
+
223
+
224
+ def identity_runner(fn, *args, **kwargs):
225
+ return fn(*args, **kwargs)
226
+
227
+
228
+ def profiler_runner(path, fn, *args, **kwargs):
229
+ with torch.profiler.profile(
230
+ activities=[
231
+ torch.profiler.ProfilerActivity.CPU,
232
+ torch.profiler.ProfilerActivity.CUDA,
233
+ ],
234
+ record_shapes=True,
235
+ ) as prof:
236
+ result = fn(*args, **kwargs)
237
+ prof.export_chrome_trace(path)
238
+ return result
239
+
240
+
241
+ def profile_top_runner(fn, *args, **kwargs):
242
+ with torch.profiler.profile(
243
+ activities=[
244
+ torch.profiler.ProfilerActivity.CPU,
245
+ torch.profiler.ProfilerActivity.CUDA,
246
+ ],
247
+ record_shapes=True,
248
+ ) as prof:
249
+ result = fn(*args, **kwargs)
250
+ if torch.cuda.is_available():
251
+ print(prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=-1))
252
+ else:
253
+ print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=-1))
254
+ return result
255
+
256
+
257
+ def memory_runner(path, fn, *args, **kwargs):
258
+ print("Start memory recording")
259
+ torch.cuda.synchronize()
260
+ torch.cuda.memory._record_memory_history(
261
+ True, trace_alloc_max_entries=100000, trace_alloc_record_context=True
262
+ )
263
+ result = fn(*args, **kwargs)
264
+ torch.cuda.synchronize()
265
+ snapshot = torch.cuda.memory._snapshot()
266
+ print("Finish memory recording")
267
+ import pickle
268
+
269
+ with open(path, "wb") as f:
270
+ pickle.dump(snapshot, f)
271
+ # Use to convert pickle file into html
272
+ # python torch/cuda/_memory_viz.py trace_plot <snapshot>.pickle -o <snapshot>.html
273
+ return result
274
+
275
+
276
+ def run(
277
+ coco_root_dir,
278
+ coco_slice_name,
279
+ sam_checkpoint_base_path,
280
+ sam_model_type,
281
+ point_sampling_cache_dir,
282
+ mask_debug_out_dir,
283
+ batch_size=1,
284
+ print_header=False,
285
+ coco_category_names=None,
286
+ limit=None,
287
+ img_id=None,
288
+ use_half=None,
289
+ use_compile="False",
290
+ use_compile_decoder=False,
291
+ compress=None,
292
+ min_sqnr=None,
293
+ num_workers=0,
294
+ use_rel_pos=True,
295
+ pad_input_image_batch=True,
296
+ profile_path=None,
297
+ profile_top=False,
298
+ memory_path=None,
299
+ device="cuda",
300
+ output_json_path=None,
301
+ output_json_local=False,
302
+ ):
303
+ from torch._inductor import config as inductorconfig
304
+
305
+ inductorconfig.triton.unique_kernel_names = True
306
+ inductorconfig.epilogue_fusion = True
307
+ inductorconfig.coordinate_descent_tuning = True
308
+ inductorconfig.coordinate_descent_check_all_directions = True
309
+ inductorconfig.force_fuse_int_mm_with_mul = True
310
+ inductorconfig.use_mixed_mm = True
311
+ from torch.sparse import SparseSemiStructuredTensor
312
+
313
+ SparseSemiStructuredTensor._FORCE_CUTLASS = False
314
+
315
+ if use_half is not None:
316
+ if use_half == "float16":
317
+ use_half = torch.float16
318
+ elif use_half == "bfloat16":
319
+ use_half = torch.bfloat16
320
+ else:
321
+ raise ValueError(
322
+ "Expected one of float16 or bfloat for specified {use_half}"
323
+ )
324
+
325
+ # Batch size needs to be a multiple of two and at most 512.
326
+ assert math.log2(batch_size).is_integer()
327
+ assert batch_size <= 512
328
+
329
+ # https://github.com/facebookresearch/segment-anything/tree/main#model-checkpoints
330
+ # largest to smallest: vit_h, vit_l, vit_b
331
+ model_type_to_checkpoint = {
332
+ "vit_h": f"{sam_checkpoint_base_path}/sam_vit_h_4b8939.pth",
333
+ "vit_l": f"{sam_checkpoint_base_path}/sam_vit_l_0b3195.pth",
334
+ "vit_b": f"{sam_checkpoint_base_path}/sam_vit_b_01ec64.pth",
335
+ }
336
+
337
+ from segment_anything_fast import SamPredictor, sam_model_registry
338
+
339
+ checkpoint_path = model_type_to_checkpoint[sam_model_type]
340
+ sam = sam_model_registry[sam_model_type](checkpoint=checkpoint_path).to(
341
+ torch.device(device)
342
+ )
343
+ predictor = SamPredictor(sam)
344
+
345
+ from segment_anything_fast import tools
346
+
347
+ tools.apply_eval_dtype_predictor(predictor, use_half)
348
+
349
+ for block in predictor.model.image_encoder.blocks:
350
+ block.attn.use_rel_pos = use_rel_pos
351
+
352
+ # Helper filter functions
353
+ def attn_only(mod, name):
354
+ return isinstance(mod, torch.nn.Linear) and "attn" in name
355
+
356
+ def mlp_lin1_only(mod, name):
357
+ return isinstance(mod, torch.nn.Linear) and "lin1" in name
358
+
359
+ def mlp_lin2_only(mod, name):
360
+ return isinstance(mod, torch.nn.Linear) and "lin2" in name
361
+
362
+ def mlp_only(mod, name):
363
+ return isinstance(mod, torch.nn.Linear) and "mlp" in name
364
+
365
+ if compress == "int8_dynamic_quant":
366
+ quantize_(predictor.model.image_encoder, int8_dynamic_activation_int8_weight())
367
+ if not TORCH_VERSION_AT_LEAST_2_5:
368
+ predictor.model.image_encoder = unwrap_tensor_subclass(
369
+ predictor.model.image_encoder
370
+ )
371
+ elif compress == "sparse_mlp_only":
372
+
373
+ def mlp_only(mod, name):
374
+ return isinstance(mod, torch.nn.Linear) and "mlp" in name
375
+
376
+ apply_fake_sparsity(predictor.model.image_encoder, filter_fn=mlp_only)
377
+ sparsify_(
378
+ predictor.model.image_encoder, semi_sparse_weight(), filter_fn=mlp_only
379
+ )
380
+ elif compress == "sparse":
381
+ apply_fake_sparsity(predictor.model.image_encoder)
382
+ sparsify_(predictor.model.image_encoder, semi_sparse_weight())
383
+ elif compress == "int8_dynamic_quant_sparse":
384
+ # apply sparsify first to set qparams
385
+ apply_fake_sparsity(predictor.model.image_encoder, filter_fn=mlp_only)
386
+
387
+ quantize_(
388
+ predictor.model.image_encoder,
389
+ int8_dynamic_activation_int8_weight(),
390
+ attn_only,
391
+ )
392
+ quantize_(
393
+ predictor.model.image_encoder,
394
+ int8_dynamic_activation_int8_weight(layout=SemiSparseLayout()),
395
+ mlp_lin1_only,
396
+ )
397
+ sparsify_(predictor.model.image_encoder, semi_sparse_weight(), mlp_lin2_only)
398
+ if not TORCH_VERSION_AT_LEAST_2_5:
399
+ predictor.model.image_encoder = unwrap_tensor_subclass(
400
+ predictor.model.image_encoder
401
+ )
402
+ elif compress == "int4_weight_only_sparse":
403
+ # apply sparsify first to set qparams
404
+ apply_fake_sparsity(predictor.model.image_encoder, filter_fn=mlp_only)
405
+ from torchao.dtypes import MarlinSparseLayout
406
+
407
+ quantize_(
408
+ predictor.model.image_encoder,
409
+ int8_dynamic_activation_int8_weight(),
410
+ attn_only,
411
+ )
412
+ quantize_(
413
+ predictor.model.image_encoder,
414
+ int4_weight_only(layout=MarlinSparseLayout()),
415
+ mlp_lin1_only,
416
+ )
417
+ sparsify_(predictor.model.image_encoder, semi_sparse_weight(), mlp_lin2_only)
418
+ if not TORCH_VERSION_AT_LEAST_2_5:
419
+ predictor.model.image_encoder = unwrap_tensor_subclass(
420
+ predictor.model.image_encoder
421
+ )
422
+
423
+ elif compress is not None and "autoquant_v2" in compress:
424
+ example_input = torch.randn(
425
+ 1, 3, 1024, 1024, dtype=torch.bfloat16, device=device
426
+ )
427
+ if "autoquant_v2-int4" == compress:
428
+ autoquant_v2(
429
+ predictor.model.image_encoder,
430
+ example_input=example_input,
431
+ manual=True,
432
+ qtensor_class_list=torchao.prototype.quantization.autoquant_v2.DEFAULT_INT4_AUTOQUANT_CLASS_LIST,
433
+ )
434
+ elif "autoquant_v2-float8" == compress:
435
+ autoquant_v2(
436
+ predictor.model.image_encoder,
437
+ example_input=example_input,
438
+ manual=True,
439
+ qtensor_class_list=torchao.prototype.quantization.autoquant_v2.OTHER_AUTOQUANT_CLASS_LIST,
440
+ )
441
+ elif "autoquant_v2-all" == compress:
442
+ autoquant_v2(
443
+ predictor.model.image_encoder,
444
+ example_input=example_input,
445
+ manual=True,
446
+ qtensor_class_list=torchao.prototype.quantization.autoquant_v2.ALL_AUTOQUANT_CLASS_LIST,
447
+ )
448
+ else:
449
+ autoquant_v2(
450
+ predictor.model.image_encoder, example_input=example_input, manual=True
451
+ )
452
+
453
+ predictor.model.image_encoder(example_input)
454
+ predictor.model.image_encoder.finalize_autoquant()
455
+
456
+ elif compress is not None and "autoquant" in compress:
457
+ example_input = torch.randn(
458
+ 1, 3, 1024, 1024, dtype=torch.bfloat16, device=device
459
+ )
460
+ if "autoquant-int4" == compress:
461
+ autoquant(
462
+ predictor.model.image_encoder,
463
+ example_input=example_input,
464
+ manual=True,
465
+ qtensor_class_list=torchao.quantization.DEFAULT_INT4_AUTOQUANT_CLASS_LIST,
466
+ min_sqnr=min_sqnr,
467
+ )
468
+ elif "autoquant-float8" == compress:
469
+ autoquant(
470
+ predictor.model.image_encoder,
471
+ example_input=example_input,
472
+ manual=True,
473
+ qtensor_class_list=torchao.quantization.OTHER_AUTOQUANT_CLASS_LIST,
474
+ min_sqnr=min_sqnr,
475
+ )
476
+ elif "autoquant-sparse" == compress:
477
+ autoquant(
478
+ predictor.model.image_encoder,
479
+ example_input=example_input,
480
+ manual=True,
481
+ qtensor_class_list=torchao.quantization.DEFAULT_SPARSE_AUTOQUANT_CLASS_LIST,
482
+ min_sqnr=min_sqnr,
483
+ )
484
+ elif "autoquant-all" == compress:
485
+ autoquant(
486
+ predictor.model.image_encoder,
487
+ example_input=example_input,
488
+ manual=True,
489
+ qtensor_class_list=torchao.quantization.ALL_AUTOQUANT_CLASS_LIST,
490
+ min_sqnr=min_sqnr,
491
+ )
492
+ else:
493
+ autoquant(
494
+ predictor.model.image_encoder,
495
+ example_input=example_input,
496
+ manual=True,
497
+ min_sqnr=min_sqnr,
498
+ )
499
+ predictor.model.image_encoder(example_input)
500
+ predictor.model.image_encoder.finalize_autoquant()
501
+ else:
502
+ assert compress is None, f"Unsupported compress mode {compress}"
503
+
504
+ coco_img_ids_, cat_id_to_cat, catIds, coco = setup_coco_img_ids(
505
+ coco_root_dir, coco_slice_name, coco_category_names, img_id
506
+ )
507
+
508
+ coco_img_ids = []
509
+ for imgId in coco_img_ids_:
510
+ img = coco.loadImgs(imgId)[0]
511
+ annIds = coco.getAnnIds(imgIds=img["id"], catIds=catIds, iscrowd=None)
512
+ anns = coco.loadAnns(annIds)
513
+ if len(anns) != 0:
514
+ coco_img_ids.append(imgId)
515
+
516
+ build_batch = build_data(
517
+ coco_img_ids,
518
+ coco,
519
+ catIds,
520
+ coco_root_dir,
521
+ coco_slice_name,
522
+ point_sampling_cache_dir,
523
+ predictor,
524
+ use_half,
525
+ pad_input_image_batch,
526
+ )
527
+
528
+ limit = len(coco_img_ids) if limit is None else limit
529
+ batched_data_iter = torch.utils.data.DataLoader(
530
+ list(range(limit)),
531
+ batch_size=batch_size,
532
+ collate_fn=build_batch,
533
+ num_workers=num_workers,
534
+ pin_memory=False,
535
+ )
536
+ runner = identity_runner
537
+
538
+ if profile_path is not None:
539
+ import functools
540
+
541
+ runner = functools.partial(profiler_runner, profile_path)
542
+
543
+ if profile_top:
544
+ runner = profile_top_runner
545
+
546
+ if memory_path is not None:
547
+ assert use_compile != "max-autotune", (
548
+ f"Memory path does not support {use_compile}"
549
+ )
550
+ import functools
551
+
552
+ runner = functools.partial(memory_runner, memory_path)
553
+
554
+ results, avg_ms_per_img, num_batches, num_images = runner(
555
+ build_results,
556
+ batched_data_iter,
557
+ predictor,
558
+ mask_debug_out_dir,
559
+ batch_size,
560
+ use_compile,
561
+ use_compile_decoder,
562
+ pad_input_image_batch,
563
+ compress,
564
+ )
565
+
566
+ results = [[r[0], r[1], r[2], r[3].item()] for r in results]
567
+
568
+ img_s, batch_ms_batch_size = None, None
569
+ if avg_ms_per_img is not None:
570
+ img_s = 1000 / avg_ms_per_img
571
+ batch_ms_batch_size = (avg_ms_per_img * num_images) / num_batches / batch_size
572
+
573
+ mIoU = calculate_miou(results, mask_debug_out_dir, True, cat_id_to_cat)
574
+ if torch.cuda.is_available():
575
+ max_memory_allocated_bytes = torch.cuda.max_memory_allocated()
576
+ _, total_memory = torch.cuda.mem_get_info()
577
+ max_memory_allocated_percentage = int(
578
+ 100 * (max_memory_allocated_bytes / total_memory)
579
+ )
580
+ max_memory_allocated_bytes = max_memory_allocated_bytes >> 20
581
+ else:
582
+ import psutil
583
+
584
+ total_memory = psutil.virtual_memory().total
585
+ max_memory_allocated_bytes = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
586
+ max_memory_allocated_percentage = int(
587
+ 100 * (max_memory_allocated_bytes / (total_memory >> 10))
588
+ )
589
+ max_memory_allocated_bytes = max_memory_allocated_bytes >> 10
590
+
591
+ with open("results.csv", "a") as f:
592
+ if print_header:
593
+ header = ",".join(
594
+ [
595
+ "device",
596
+ "sam_model_type",
597
+ "batch_size",
598
+ "memory(MiB)",
599
+ "memory(%)",
600
+ "img_s(avg)",
601
+ "batch_ms(avg)/batch_size",
602
+ "mIoU",
603
+ "use_compile",
604
+ "use_half",
605
+ "compress",
606
+ "use_compile_decoder",
607
+ "use_rel_pos",
608
+ "pad_input_image_batch",
609
+ "num_workers",
610
+ "num_batches",
611
+ "num_images",
612
+ "profile_path",
613
+ "memory_path",
614
+ ]
615
+ )
616
+ f.write(header + "\n")
617
+ vals = ",".join(
618
+ map(
619
+ str,
620
+ [
621
+ device,
622
+ sam_model_type,
623
+ batch_size,
624
+ max_memory_allocated_bytes,
625
+ max_memory_allocated_percentage,
626
+ img_s,
627
+ batch_ms_batch_size,
628
+ mIoU,
629
+ use_compile,
630
+ use_half,
631
+ compress,
632
+ use_compile_decoder,
633
+ use_rel_pos,
634
+ pad_input_image_batch,
635
+ num_workers,
636
+ num_batches,
637
+ num_images,
638
+ profile_path,
639
+ memory_path,
640
+ ],
641
+ )
642
+ )
643
+ f.write(vals + "\n")
644
+
645
+ if output_json_path:
646
+ headers = [
647
+ "name",
648
+ "dtype",
649
+ "min_sqnr",
650
+ "compile",
651
+ "device",
652
+ "arch",
653
+ "metric",
654
+ "actual",
655
+ "target",
656
+ ]
657
+ name = sam_model_type
658
+ arch = get_arch_name()
659
+ dtype = compress or "noquant"
660
+ # boolean flag to indicate whether compile is used
661
+ compile = use_compile != "False"
662
+ memory_result = [
663
+ name,
664
+ dtype,
665
+ min_sqnr,
666
+ compile,
667
+ device,
668
+ arch,
669
+ "memory(MiB)",
670
+ max_memory_allocated_bytes,
671
+ None,
672
+ ]
673
+ performance_result = [
674
+ name,
675
+ dtype,
676
+ min_sqnr,
677
+ compile,
678
+ device,
679
+ arch,
680
+ "img_s(avg)",
681
+ img_s,
682
+ None,
683
+ ]
684
+ write_json_result = (
685
+ write_json_result_local if output_json_local else write_json_result_ossci
686
+ )
687
+ write_json_result(output_json_path, headers, memory_result)
688
+ write_json_result(output_json_path, headers, performance_result)
689
+
690
+
691
+ if __name__ == "__main__":
692
+ fire.Fire(run)
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/flash_4_configs.p ADDED
Binary file (219 Bytes). View file
 
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/metrics.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import pandas as pd
7
+ import torch
8
+
9
+
10
+ def create_result_entry(anns, gt_masks_list, masks, scores, img_idx):
11
+ argmax_scores = torch.argmax(scores, dim=1)
12
+ inference_masks = masks.gather(
13
+ 1,
14
+ argmax_scores.unsqueeze(-1)
15
+ .unsqueeze(-1)
16
+ .unsqueeze(-1)
17
+ .expand((masks.size(0), 1, masks.size(2), masks.size(3))),
18
+ ).squeeze(1)
19
+
20
+ def _iou(mask1, mask2):
21
+ assert mask1.dim() == 3
22
+ assert mask2.dim() == 3
23
+ intersection = torch.logical_and(mask1, mask2)
24
+ union = torch.logical_or(mask1, mask2)
25
+ return intersection.sum(dim=(-1, -2)) / union.sum(dim=(-1, -2))
26
+
27
+ top_score_ious = _iou(inference_masks, gt_masks_list)
28
+
29
+ entry = []
30
+ for idx in range(top_score_ious.size(0)):
31
+ entry.append(
32
+ [img_idx, anns[idx]["id"], anns[idx]["category_id"], top_score_ious[idx]]
33
+ )
34
+ return entry
35
+
36
+
37
+ def calculate_miou(results, mask_debug_out_dir, silent, cat_id_to_cat):
38
+ df = pd.DataFrame(results, columns=["img_id", "ann_id", "cat_id", "iou"])
39
+ df.to_csv(f"{mask_debug_out_dir}/df.csv")
40
+ df["supercategory"] = df["cat_id"].map(
41
+ lambda cat_id: cat_id_to_cat[cat_id]["supercategory"]
42
+ )
43
+ df["category"] = df["cat_id"].map(lambda cat_id: cat_id_to_cat[cat_id]["name"])
44
+
45
+ # TODO: cross reference the specifics of how we calculate mIoU with
46
+ # the SAM folks (should it be per dataset, per category, per image, etc)
47
+ # currently, just calculate them all
48
+
49
+ # TODO: QOL save the summaries to file
50
+
51
+ # per category
52
+ per_category = pd.pivot_table(
53
+ df,
54
+ values="iou",
55
+ index=["cat_id", "supercategory", "category"],
56
+ aggfunc=("mean", "count"),
57
+ )
58
+ if not silent:
59
+ print("\nmIoU averaged per category")
60
+ print(per_category)
61
+
62
+ # per super-category
63
+ per_supercategory = pd.pivot_table(
64
+ df, values="iou", index=["supercategory"], aggfunc=("mean", "count")
65
+ )
66
+ if not silent:
67
+ print("\nmIoU averaged per supercategory")
68
+ print(per_supercategory)
69
+
70
+ # per all selected masks
71
+ per_all_masks_agg = df["iou"].agg(["mean", "count"])
72
+ if not silent:
73
+ print("\nmIoU averaged per all selected masks")
74
+ print(per_all_masks_agg)
75
+
76
+ return df["iou"].agg(["mean", "count"])["mean"]
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/results.csv ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ device,sam_model_type,batch_size,memory(MiB),memory(%),img_s(avg),batch_ms(avg)/batch_size,mIoU,use_compile,use_half,compress,use_compile_decoder,use_rel_pos,pad_input_image_batch,num_workers,num_batches,num_images,profile_path,memory_path
2
+ cuda,vit_h,32,15172,18,22.533401716616083,44.37856354651513,0.5812715827356921,max-autotune,torch.bfloat16,None,False,True,True,32,154,4928,None,None
3
+ cuda,vit_h,32,15154,18,25.16516896830006,39.73746416166231,0.5818834536577897,max-autotune,torch.bfloat16,int8_dynamic_quant,False,True,True,32,154,4928,None,None
4
+ cuda,vit_h,32,15632,19,24.824717871078573,40.282431614863405,0.5675837487618974,max-autotune,torch.bfloat16,sparse_mlp_only,False,True,True,32,154,4928,None,None
5
+ cuda,vit_h,32,13429,16,24.589577947798148,40.66763578142439,0.5306639662569573,max-autotune,torch.bfloat16,sparse,False,True,True,32,154,4928,None,None
6
+ cuda,vit_h,32,14869,18,26.597207143088742,37.597932543073384,0.5669944616184625,max-autotune,torch.bfloat16,int8_dynamic_quant_sparse,False,True,True,32,154,4928,None,None
7
+ cuda,vit_h,32,17068,21,23.96093702681232,41.73459489004953,0.5485481164943489,max-autotune,torch.float16,int4_weight_only_sparse,False,True,True,32,154,4928,None,None
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/setup.sh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ SETUP_HOME=$(pwd)
8
+
9
+
10
+ mkdir -p checkpoints
11
+ mkdir -p datasets
12
+
13
+ mkdir -p tmp
14
+ mkdir -p tmp/sam_coco_mask_center_cache
15
+ mkdir -p tmp/sam_eval_masks_out
16
+
17
+ wget -nc -P checkpoints https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
18
+ wget -nc -P checkpoints https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth
19
+ wget -nc -P checkpoints https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth
20
+
21
+ mkdir -p datasets/coco2017
22
+ wget -nc -P datasets/coco2017 http://images.cocodataset.org/zips/val2017.zip
23
+ wget -nc -P datasets/coco2017 http://images.cocodataset.org/annotations/annotations_trainval2017.zip
24
+
25
+ cd datasets/coco2017 && unzip -n val2017.zip && cd $SETUP_HOME
26
+ cd datasets/coco2017 && unzip -n annotations_trainval2017.zip && cd $SETUP_HOME
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from hydra import initialize_config_module
8
+ from hydra.core.global_hydra import GlobalHydra
9
+
10
+ if not GlobalHydra.instance().is_initialized():
11
+ initialize_config_module("torchao._models.sam2", version_base="1.2")
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/automatic_mask_generator.py ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ # Adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/automatic_mask_generator.py
8
+ from typing import Any, Dict, List, Optional, Tuple, Union
9
+
10
+ import numpy as np
11
+ import torch
12
+ from torchvision.ops.boxes import batched_nms, box_area # type: ignore
13
+
14
+ from torchao._models.sam2.modeling.sam2_base import SAM2Base
15
+ from torchao._models.sam2.sam2_image_predictor import SAM2ImagePredictor
16
+ from torchao._models.sam2.utils.amg import (
17
+ MaskData,
18
+ _mask_to_rle_pytorch_2_0,
19
+ _mask_to_rle_pytorch_2_1,
20
+ area_from_rle,
21
+ batch_iterator,
22
+ batched_mask_to_box,
23
+ box_xyxy_to_xywh,
24
+ build_all_layer_point_grids,
25
+ calculate_stability_score,
26
+ coco_encode_rle,
27
+ generate_crop_boxes,
28
+ is_box_near_crop_edge_torch,
29
+ mask_to_rle_pytorch,
30
+ remove_small_regions,
31
+ rle_to_mask,
32
+ uncrop_boxes_xyxy,
33
+ uncrop_masks,
34
+ uncrop_points,
35
+ )
36
+ from torchao._models.sam2.utils.misc import (
37
+ crop_image,
38
+ get_image_size,
39
+ )
40
+
41
+
42
+ class SAM2AutomaticMaskGenerator(torch.nn.Module):
43
+ def __init__(
44
+ self,
45
+ model: SAM2Base,
46
+ points_per_side: Optional[int] = 32,
47
+ points_per_batch: int = 64,
48
+ pred_iou_thresh: float = 0.8,
49
+ stability_score_thresh: float = 0.95,
50
+ stability_score_offset: float = 1.0,
51
+ mask_threshold: float = 0.0,
52
+ box_nms_thresh: float = 0.7,
53
+ crop_n_layers: int = 0,
54
+ crop_nms_thresh: float = 0.7,
55
+ crop_overlap_ratio: float = 512 / 1500,
56
+ crop_n_points_downscale_factor: int = 1,
57
+ point_grids: Optional[List[np.ndarray]] = None,
58
+ min_mask_region_area: int = 0,
59
+ output_mode: str = "binary_mask",
60
+ use_m2m: bool = False,
61
+ multimask_output: bool = True,
62
+ **kwargs,
63
+ ) -> None:
64
+ """
65
+ Using a SAM 2 model, generates masks for the entire image.
66
+ Generates a grid of point prompts over the image, then filters
67
+ low quality and duplicate masks. The default settings are chosen
68
+ for SAM 2 with a HieraL backbone.
69
+
70
+ Arguments:
71
+ model (Sam): The SAM 2 model to use for mask prediction.
72
+ points_per_side (int or None): The number of points to be sampled
73
+ along one side of the image. The total number of points is
74
+ points_per_side**2. If None, 'point_grids' must provide explicit
75
+ point sampling.
76
+ points_per_batch (int): Sets the number of points run simultaneously
77
+ by the model. Higher numbers may be faster but use more GPU memory.
78
+ pred_iou_thresh (float): A filtering threshold in [0,1], using the
79
+ model's predicted mask quality.
80
+ stability_score_thresh (float): A filtering threshold in [0,1], using
81
+ the stability of the mask under changes to the cutoff used to binarize
82
+ the model's mask predictions.
83
+ stability_score_offset (float): The amount to shift the cutoff when
84
+ calculated the stability score.
85
+ mask_threshold (float): Threshold for binarizing the mask logits
86
+ box_nms_thresh (float): The box IoU cutoff used by non-maximal
87
+ suppression to filter duplicate masks.
88
+ crop_n_layers (int): If >0, mask prediction will be run again on
89
+ crops of the image. Sets the number of layers to run, where each
90
+ layer has 2**i_layer number of image crops.
91
+ crop_nms_thresh (float): The box IoU cutoff used by non-maximal
92
+ suppression to filter duplicate masks between different crops.
93
+ crop_overlap_ratio (float): Sets the degree to which crops overlap.
94
+ In the first crop layer, crops will overlap by this fraction of
95
+ the image length. Later layers with more crops scale down this overlap.
96
+ crop_n_points_downscale_factor (int): The number of points-per-side
97
+ sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
98
+ point_grids (list(np.ndarray) or None): A list over explicit grids
99
+ of points used for sampling, normalized to [0,1]. The nth grid in the
100
+ list is used in the nth crop layer. Exclusive with points_per_side.
101
+ min_mask_region_area (int): If >0, postprocessing will be applied
102
+ to remove disconnected regions and holes in masks with area smaller
103
+ than min_mask_region_area. Requires opencv.
104
+ output_mode (str): The form masks are returned in. Can be 'binary_mask',
105
+ 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.
106
+ For large resolutions, 'binary_mask' may consume large amounts of
107
+ memory.
108
+ use_m2m (bool): Whether to add a one step refinement using previous mask predictions.
109
+ multimask_output (bool): Whether to output multimask at each point of the grid.
110
+ """
111
+ super().__init__()
112
+ assert (points_per_side is None) != (point_grids is None), (
113
+ "Exactly one of points_per_side or point_grid must be provided."
114
+ )
115
+ if points_per_side is not None:
116
+ self.point_grids = build_all_layer_point_grids(
117
+ points_per_side,
118
+ crop_n_layers,
119
+ crop_n_points_downscale_factor,
120
+ )
121
+ elif point_grids is not None:
122
+ self.point_grids = point_grids
123
+ else:
124
+ raise ValueError("Can't have both points_per_side and point_grid be None.")
125
+
126
+ assert output_mode in [
127
+ "binary_mask",
128
+ "uncompressed_rle",
129
+ "coco_rle",
130
+ ], f"Unknown output_mode {output_mode}."
131
+ if output_mode == "coco_rle":
132
+ try:
133
+ from pycocotools import mask as mask_utils # type: ignore # noqa: F401
134
+ except ImportError as e:
135
+ print("Please install pycocotools")
136
+ raise e
137
+
138
+ self.predictor = SAM2ImagePredictor(
139
+ model,
140
+ max_hole_area=min_mask_region_area,
141
+ max_sprinkle_area=min_mask_region_area,
142
+ )
143
+ self.points_per_batch = points_per_batch
144
+ self.pred_iou_thresh = pred_iou_thresh
145
+ self.stability_score_thresh = stability_score_thresh
146
+ self.stability_score_offset = stability_score_offset
147
+ self.mask_threshold = mask_threshold
148
+ self.box_nms_thresh = box_nms_thresh
149
+ self.crop_n_layers = crop_n_layers
150
+ self.crop_nms_thresh = crop_nms_thresh
151
+ self.crop_overlap_ratio = crop_overlap_ratio
152
+ self.crop_n_points_downscale_factor = crop_n_points_downscale_factor
153
+ self.min_mask_region_area = min_mask_region_area
154
+ self.output_mode = output_mode
155
+ self.use_m2m = use_m2m
156
+ self.multimask_output = multimask_output
157
+
158
+ # Store a reference to these on the model so I can overwrite them
159
+ # with compile annotation if desired
160
+
161
+ self.calculate_stability_score = calculate_stability_score
162
+ self.batched_mask_to_box = batched_mask_to_box
163
+
164
+ @classmethod
165
+ def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2AutomaticMaskGenerator":
166
+ """
167
+ Load a pretrained model from the Hugging Face hub.
168
+
169
+ Arguments:
170
+ model_id (str): The Hugging Face repository ID.
171
+ **kwargs: Additional arguments to pass to the model constructor.
172
+
173
+ Returns:
174
+ (SAM2AutomaticMaskGenerator): The loaded model.
175
+ """
176
+ from sam2.build_sam import build_sam2_hf
177
+
178
+ sam_model = build_sam2_hf(model_id, **kwargs)
179
+ return cls(sam_model, **kwargs)
180
+
181
+ @torch.no_grad()
182
+ def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:
183
+ """
184
+ Generates masks for the given image.
185
+
186
+ Arguments:
187
+ image (np.ndarray): The image to generate masks for, in HWC uint8 format.
188
+
189
+ Returns:
190
+ list(dict(str, any)): A list over records for masks. Each record is
191
+ a dict containing the following keys:
192
+ segmentation (dict(str, any) or np.ndarray): The mask. If
193
+ output_mode='binary_mask', is an array of shape HW. Otherwise,
194
+ is a dictionary containing the RLE.
195
+ bbox (list(float)): The box around the mask, in XYWH format.
196
+ area (int): The area in pixels of the mask.
197
+ predicted_iou (float): The model's own prediction of the mask's
198
+ quality. This is filtered by the pred_iou_thresh parameter.
199
+ point_coords (list(list(float))): The point coordinates input
200
+ to the model to generate this mask.
201
+ stability_score (float): A measure of the mask's quality. This
202
+ is filtered on using the stability_score_thresh parameter.
203
+ crop_box (list(float)): The crop of the image used to generate
204
+ the mask, given in XYWH format.
205
+ """
206
+
207
+ # Generate masks
208
+ mask_data = self._generate_masks(image)
209
+
210
+ return self._encode_masks(mask_data)
211
+
212
+ def _encode_masks(self, mask_data):
213
+ mask_data["rles"] = _mask_to_rle_pytorch_2_1(mask_data["rles"])
214
+ # Encode masks
215
+ if self.output_mode == "coco_rle":
216
+ mask_data["segmentations"] = [
217
+ coco_encode_rle(rle) for rle in mask_data["rles"]
218
+ ]
219
+ elif self.output_mode == "binary_mask":
220
+ mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]]
221
+ else:
222
+ mask_data["segmentations"] = mask_data["rles"]
223
+
224
+ # Write mask records
225
+ curr_anns = []
226
+ for idx in range(len(mask_data["segmentations"])):
227
+ ann = {
228
+ "segmentation": mask_data["segmentations"][idx],
229
+ "area": area_from_rle(mask_data["rles"][idx]),
230
+ "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(),
231
+ "predicted_iou": mask_data["iou_preds"][idx].item(),
232
+ "point_coords": [mask_data["points"][idx].tolist()],
233
+ "stability_score": mask_data["stability_score"][idx].item(),
234
+ "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(),
235
+ }
236
+ curr_anns.append(ann)
237
+
238
+ return curr_anns
239
+
240
+ @torch.no_grad()
241
+ def generate_batch(self, images: List[np.ndarray]) -> List[List[Dict[str, Any]]]:
242
+ data = self._generate_masks_batch(images)
243
+ return [self._encode_masks(d) for d in data]
244
+
245
+ def _generate_masks(self, image: Union[np.ndarray, torch.Tensor]) -> MaskData:
246
+ orig_size = get_image_size(image)
247
+ crop_boxes, layer_idxs = generate_crop_boxes(
248
+ orig_size, self.crop_n_layers, self.crop_overlap_ratio
249
+ )
250
+
251
+ # Iterate over image crops
252
+ data = None
253
+ for crop_box, layer_idx in zip(crop_boxes, layer_idxs):
254
+ crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)
255
+ if data is None:
256
+ data = crop_data
257
+ else:
258
+ data.cat(crop_data)
259
+
260
+ return self._deduplicate_masks(crop_boxes, data)
261
+
262
+ def _deduplicate_masks(self, crop_boxes, data):
263
+ # Remove duplicate masks between crops
264
+ if len(crop_boxes) > 1:
265
+ # Prefer masks from smaller crops
266
+ scores = 1 / box_area(data["crop_boxes"])
267
+ scores = scores.to(data["boxes"].device)
268
+ keep_by_nms = batched_nms(
269
+ data["boxes"].float(),
270
+ scores,
271
+ torch.zeros_like(data["boxes"][:, 0]), # categories
272
+ iou_threshold=self.crop_nms_thresh,
273
+ )
274
+ data.filter(keep_by_nms)
275
+ data.to_numpy()
276
+ return data
277
+
278
+ def _generate_masks_batch(self, images: List[np.ndarray]) -> List[MaskData]:
279
+ all_orig_size = []
280
+ all_crop_boxes = []
281
+ all_layer_idxs = []
282
+ for image in images:
283
+ orig_size = get_image_size(image)
284
+ all_orig_size.append(orig_size)
285
+ crop_boxes, layer_idxs = generate_crop_boxes(
286
+ orig_size, self.crop_n_layers, self.crop_overlap_ratio
287
+ )
288
+ all_crop_boxes.append(crop_boxes)
289
+ all_layer_idxs.append(layer_idxs)
290
+
291
+ all_data = self._process_crop_batch(
292
+ images, all_crop_boxes, all_layer_idxs, all_orig_size
293
+ )
294
+
295
+ return [
296
+ self._deduplicate_masks(crop_boxes, data)
297
+ for (crop_boxes, data) in zip(all_crop_boxes, all_data)
298
+ ]
299
+
300
+ def _process_crop(
301
+ self,
302
+ image: np.ndarray,
303
+ crop_box: List[int],
304
+ crop_layer_idx: int,
305
+ orig_size: Tuple[int, ...],
306
+ ) -> MaskData:
307
+ # Crop the image and calculate embeddings
308
+ cropped_im = crop_image(image, crop_box)
309
+ cropped_im_size = get_image_size(cropped_im)
310
+ with torch.autograd.profiler.record_function("set_image"):
311
+ self.predictor.set_image(cropped_im)
312
+
313
+ return self._process_crop_points(
314
+ cropped_im_size, crop_layer_idx, crop_box, orig_size
315
+ )
316
+
317
+ def _process_crop_points(
318
+ self, cropped_im_size, crop_layer_idx, crop_box, orig_size
319
+ ):
320
+ # Get points for this crop
321
+ points_scale = np.array(cropped_im_size)[None, ::-1]
322
+ points_for_image = self.point_grids[crop_layer_idx] * points_scale
323
+
324
+ # Generate masks for this crop in batches
325
+ # data = MaskData()
326
+ data = None
327
+ points_per_batch = self.points_per_batch
328
+ if self.points_per_batch is None:
329
+ points_per_batch = len(points_for_image)
330
+ for (points,) in batch_iterator(points_per_batch, points_for_image):
331
+ batch_data = self._process_batch(
332
+ points, cropped_im_size, crop_box, orig_size, normalize=True
333
+ )
334
+ with torch.autograd.profiler.record_function("data.cat"):
335
+ if data is None:
336
+ data = batch_data
337
+ else:
338
+ data.cat(batch_data)
339
+ del batch_data
340
+ self.predictor.reset_predictor()
341
+ return self._process_crop_points_dedup(data, crop_box)
342
+
343
+ def _process_crop_points_dedup(self, data, crop_box):
344
+ with torch.autograd.profiler.record_function("batched_nms"):
345
+ # Remove duplicates within this crop.
346
+ keep_by_nms = batched_nms(
347
+ data["boxes"].float(),
348
+ data["iou_preds"],
349
+ torch.zeros_like(data["boxes"][:, 0]), # categories
350
+ iou_threshold=self.box_nms_thresh,
351
+ )
352
+
353
+ with torch.autograd.profiler.record_function("filter"):
354
+ data.filter(keep_by_nms)
355
+
356
+ with torch.autograd.profiler.record_function("uncrop_boxes_xyxy"):
357
+ # Return to the original image frame
358
+ data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box)
359
+ with torch.autograd.profiler.record_function("uncrop_points"):
360
+ data["points"] = uncrop_points(data["points"], crop_box)
361
+ with torch.autograd.profiler.record_function("crop_boxes"):
362
+ data["crop_boxes"] = torch.tensor(
363
+ [crop_box for _ in range(len(data["rles"]))]
364
+ )
365
+
366
+ return data
367
+
368
+ def _process_crop_batch(
369
+ self,
370
+ images: List[np.ndarray],
371
+ all_crop_boxes: List[List[int]],
372
+ all_layer_idxs: List[int],
373
+ all_orig_size_compact: List[Tuple[int, ...]],
374
+ ) -> List[MaskData]:
375
+ all_image = []
376
+ all_crop_box = []
377
+ all_layer_idx = []
378
+ all_orig_size = []
379
+ for image, orig_size, crop_boxes, layer_idxs in zip(
380
+ images, all_orig_size_compact, all_crop_boxes, all_layer_idxs
381
+ ):
382
+ # Iterate over image crops
383
+ for crop_box, layer_idx in zip(crop_boxes, layer_idxs):
384
+ all_image.append(image)
385
+ all_crop_box.append(crop_box)
386
+ all_layer_idx.append(layer_idx)
387
+ all_orig_size.append(orig_size)
388
+
389
+ # # TODO: NOTE: Calling process_crop in a loop like this might be an issue, because the predictor is stateful
390
+
391
+ all_cropped_im = [
392
+ crop_image(image, crop_box)
393
+ for image, crop_box in zip(all_image, all_crop_box)
394
+ ]
395
+
396
+ with torch.autograd.profiler.record_function("set_batch_image"):
397
+ self.predictor.set_image_batch(all_cropped_im)
398
+
399
+ i = 0
400
+ batch_features = self.predictor._features
401
+ all_crop_data = []
402
+ for cropped_im, crop_box, layer_idx, orig_size in zip(
403
+ all_cropped_im, all_crop_box, all_layer_idx, all_orig_size
404
+ ):
405
+ cropped_im_size = get_image_size(cropped_im)
406
+ self.predictor._orig_hw = [get_image_size(cropped_im)]
407
+ self.predictor._features = {
408
+ "image_embed": batch_features["image_embed"][i].unsqueeze(0),
409
+ "high_res_feats": [
410
+ b[i].unsqueeze(0) for b in batch_features["high_res_feats"]
411
+ ],
412
+ }
413
+ i += 1
414
+ self.predictor._is_image_set = True
415
+
416
+ # TODO: Batch mask_to_rle_pytorch_2 calls
417
+ # TODO: Specialize for rle-only return (specify which keys you want in data)
418
+
419
+ # all_crop_data.append(self._process_crop_points(cropped_im_size, layer_idx, crop_box, orig_size))
420
+
421
+ crop_layer_idx = layer_idx
422
+
423
+ # Get points for this crop
424
+ points_scale = np.array(cropped_im_size)[None, ::-1]
425
+ points_for_image = self.point_grids[crop_layer_idx] * points_scale
426
+
427
+ # Generate masks for this crop in batches
428
+ points_per_batch = self.points_per_batch
429
+ if self.points_per_batch is None:
430
+ points_per_batch = len(points_for_image)
431
+
432
+ all_batch_iterator_data = []
433
+ with torch.autograd.profiler.record_function("all _process_batch"):
434
+ for (points,) in batch_iterator(points_per_batch, points_for_image):
435
+ # batch_data = self._process_batch(
436
+ # points, cropped_im_size, crop_box, orig_size, normalize=True
437
+ # )
438
+
439
+ im_size = cropped_im_size
440
+ normalize = True
441
+
442
+ orig_h, orig_w = orig_size
443
+
444
+ orig_box = [0, 0, orig_w, orig_h]
445
+ orig_box_torch = torch.as_tensor(
446
+ orig_box, dtype=torch.float, device=self.predictor.device
447
+ )
448
+ crop_box_torch = torch.as_tensor(
449
+ crop_box, dtype=torch.float, device=self.predictor.device
450
+ )
451
+ data = self._process_batch_fullgraph(
452
+ points,
453
+ im_size,
454
+ crop_box,
455
+ crop_box_torch,
456
+ orig_size,
457
+ normalize,
458
+ orig_box_torch,
459
+ )
460
+ all_batch_iterator_data.append(data)
461
+ self.predictor.reset_predictor()
462
+
463
+ result_data = None
464
+ with torch.autograd.profiler.record_function("all mask_to_rle_pytorch_2"):
465
+ for data in all_batch_iterator_data:
466
+ # Compress to RLE
467
+ data["masks"] = uncrop_masks(
468
+ data["masks"], crop_box, orig_h, orig_w
469
+ )
470
+ # TODO: Capture all these masks in a single NT for mask_to_rle_pytorch_2
471
+ # or at a minimum create a mask_to_rle_pytorch_2_list and use loops
472
+ # to cause a single DtoH sync
473
+ data["rles"] = _mask_to_rle_pytorch_2_0(data["masks"])
474
+ del data["masks"]
475
+
476
+ batch_data = data
477
+ with torch.autograd.profiler.record_function("data.cat"):
478
+ if result_data is None:
479
+ result_data = batch_data
480
+ else:
481
+ result_data.cat(batch_data)
482
+ del batch_data
483
+ self.predictor.reset_predictor()
484
+
485
+ all_crop_data.append(self._process_crop_points_dedup(result_data, crop_box))
486
+
487
+ i = 0
488
+ all_data = []
489
+ for _, _, crop_boxes, layer_idxs in zip(
490
+ images, all_orig_size, all_crop_boxes, all_layer_idxs
491
+ ):
492
+ data = None
493
+ for _, _ in zip(crop_boxes, layer_idxs):
494
+ if data is None:
495
+ data = all_crop_data[i]
496
+ else:
497
+ data.cat(all_crop_data[i])
498
+ i += 1
499
+ all_data.append(data)
500
+ return all_data
501
+
502
+ def _process_batch_fullgraph(
503
+ self,
504
+ points: np.ndarray,
505
+ im_size: Tuple[int, ...],
506
+ crop_box: List[int],
507
+ crop_box_torch: torch.Tensor,
508
+ orig_size: Tuple[int, ...],
509
+ normalize: bool,
510
+ orig_box_torch: torch.Tensor,
511
+ ) -> MaskData:
512
+ orig_h, orig_w = orig_size
513
+
514
+ # Run model on this batch
515
+ points = torch.as_tensor(points, dtype=torch.float32).pin_memory()
516
+ points = points.to(device=self.predictor.device, non_blocking=True)
517
+ in_points = self.predictor._transforms.transform_coords(
518
+ points, normalize=normalize, orig_hw=im_size
519
+ )
520
+ in_labels = torch.ones(
521
+ in_points.shape[0], dtype=torch.int, device=in_points.device
522
+ )
523
+ with torch.autograd.profiler.record_function("_predict"):
524
+ # NOTE: Just leaving this for reference. predict was split to
525
+ # allow earlier filtering by predicted iou
526
+ # masks, iou_preds, low_res_masks = self.predictor._predict(
527
+ masks = None
528
+ high_res_feats = self.predictor._features["high_res_feats"]
529
+ image_embed = self.predictor._features["image_embed"]
530
+ image_pe = self.predictor.model.sam_prompt_encoder.get_dense_pe().clone()
531
+ assert self.multimask_output, (
532
+ "Currently require multimask_output set to True"
533
+ )
534
+ high_res_feats_input = [
535
+ feat_level[-1].unsqueeze(0).clone()
536
+ # for feat_level in self._features["high_res_feats"]
537
+ for feat_level in high_res_feats
538
+ ]
539
+ image_embed_input = image_embed[-1].unsqueeze(0).clone()
540
+ low_res_masks, iou_preds = self.predictor._predict_masks(
541
+ [t.contiguous() for t in high_res_feats_input],
542
+ image_embed_input.contiguous(),
543
+ image_pe.contiguous(),
544
+ in_points[:, None, :].contiguous(),
545
+ in_labels[:, None].contiguous(),
546
+ boxes=None,
547
+ mask_input=None,
548
+ multimask_output=self.multimask_output,
549
+ # img_idx=-1,
550
+ )
551
+
552
+ x0, y0, _, _ = crop_box
553
+ points = points.repeat_interleave(3 if masks is None else masks.shape[1], dim=0)
554
+
555
+ if not self.use_m2m:
556
+ with torch.autograd.profiler.record_function("thresh and filter"):
557
+ # Filter by predicted IoU
558
+ if self.pred_iou_thresh > 0.0:
559
+ keep_mask = iou_preds.flatten(0, 1) > self.pred_iou_thresh
560
+ keep_index = keep_mask.nonzero(as_tuple=True)[0]
561
+ low_res_masks = low_res_masks.flatten(0, 1).unsqueeze(1)
562
+ low_res_masks = low_res_masks[keep_index]
563
+ iou_preds = iou_preds.flatten(0, 1).unsqueeze(1)[keep_index]
564
+ points = points[keep_index]
565
+ if masks is None:
566
+ masks, low_res_mask = self.predictor._predict_masks_postprocess(
567
+ low_res_masks, -1, True, channel_1=low_res_masks.size(1) == 1
568
+ )
569
+
570
+ # Serialize predictions and store in MaskData
571
+ with torch.autograd.profiler.record_function("MaskData"):
572
+ data = MaskData(
573
+ masks=masks.flatten(0, 1),
574
+ iou_preds=iou_preds.flatten(0, 1),
575
+ points=points,
576
+ low_res_masks=low_res_masks.flatten(0, 1),
577
+ )
578
+ del masks
579
+
580
+ keep_mask = None
581
+
582
+ if not self.use_m2m:
583
+ # NOTE: This is left just for reference. We filter earlier for this case to save
584
+ # on compute within the expensive _predict_masks_postprocess
585
+ # with torch.autograd.profiler.record_function("thresh and filter"):
586
+ # # Filter by predicted IoU
587
+ # if self.pred_iou_thresh > 0.0:
588
+ # keep_mask = data["iou_preds"] > self.pred_iou_thresh
589
+ # # TODO: Might need this for correctness due to calculate_stability_score IoU?
590
+ # data.filter(keep_mask)
591
+
592
+ with torch.autograd.profiler.record_function("calculate_stability_score"):
593
+ # Calculate and filter by stability score
594
+ data["stability_score"] = self.calculate_stability_score(
595
+ data["masks"], self.mask_threshold, self.stability_score_offset
596
+ )
597
+ with torch.autograd.profiler.record_function("stability_score_thresh"):
598
+ if self.stability_score_thresh > 0.0:
599
+ keep_mask = data["stability_score"] >= self.stability_score_thresh
600
+ keep_index = keep_mask.nonzero(as_tuple=True)[0]
601
+ data.filter(keep_index)
602
+ else:
603
+ # One step refinement using previous mask predictions
604
+ in_points = self.predictor._transforms.transform_coords(
605
+ data["points"], normalize=normalize, orig_hw=im_size
606
+ )
607
+ labels = torch.ones(
608
+ in_points.shape[0], dtype=torch.int, device=in_points.device
609
+ )
610
+ masks, ious = self.refine_with_m2m(
611
+ in_points, labels, data["low_res_masks"], self.points_per_batch
612
+ )
613
+ data["masks"] = masks.squeeze(1)
614
+ data["iou_preds"] = ious.squeeze(1)
615
+
616
+ if self.pred_iou_thresh > 0.0:
617
+ keep_mask = data["iou_preds"] > self.pred_iou_thresh
618
+ data.filter(keep_mask)
619
+
620
+ data["stability_score"] = self.calculate_stability_score(
621
+ data["masks"], self.mask_threshold, self.stability_score_offset
622
+ )
623
+ if self.stability_score_thresh > 0.0:
624
+ keep_mask = data["stability_score"] >= self.stability_score_thresh
625
+ data.filter(keep_mask)
626
+
627
+ with torch.autograd.profiler.record_function(
628
+ "Threshold masks and calculate boxes"
629
+ ):
630
+ # Threshold masks and calculate boxes
631
+ data["masks"] = data["masks"] > self.mask_threshold
632
+ data["boxes"] = self.batched_mask_to_box(data["masks"])
633
+
634
+ with torch.autograd.profiler.record_function("is_box_near_crop_edge"):
635
+ # Filter boxes that touch crop boundaries
636
+ keep_mask = ~is_box_near_crop_edge_torch(
637
+ data["boxes"],
638
+ crop_box,
639
+ crop_box_torch,
640
+ orig_box_torch,
641
+ )
642
+
643
+ with torch.autograd.profiler.record_function("filter(keep_mask)"):
644
+ keep_index = keep_mask.nonzero(as_tuple=True)[0]
645
+ data.filter(keep_index)
646
+
647
+ return data
648
+
649
+ def _process_batch(
650
+ self,
651
+ points: np.ndarray,
652
+ im_size: Tuple[int, ...],
653
+ crop_box: List[int],
654
+ orig_size: Tuple[int, ...],
655
+ normalize=False,
656
+ ) -> MaskData:
657
+ orig_h, orig_w = orig_size
658
+
659
+ orig_box = [0, 0, orig_w, orig_h]
660
+ orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float)
661
+ orig_box_torch = orig_box_torch.pin_memory()
662
+ orig_box_torch = orig_box_torch.to(
663
+ device=self.predictor.device, non_blocking=True
664
+ )
665
+
666
+ crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float)
667
+ crop_box_torch = crop_box_torch.pin_memory()
668
+ crop_box_torch = crop_box_torch.to(
669
+ device=self.predictor.device, non_blocking=True
670
+ )
671
+
672
+ data = self._process_batch_fullgraph(
673
+ points,
674
+ im_size,
675
+ crop_box,
676
+ crop_box_torch,
677
+ orig_size,
678
+ normalize,
679
+ orig_box_torch,
680
+ )
681
+
682
+ with torch.autograd.profiler.record_function("uncrop_masks"):
683
+ # Compress to RLE
684
+ data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w)
685
+ data["rles"] = _mask_to_rle_pytorch_2_0(data["masks"])
686
+ del data["masks"]
687
+
688
+ return data
689
+
690
+ @staticmethod
691
+ def postprocess_small_regions(
692
+ mask_data: MaskData, min_area: int, nms_thresh: float
693
+ ) -> MaskData:
694
+ """
695
+ Removes small disconnected regions and holes in masks, then reruns
696
+ box NMS to remove any new duplicates.
697
+
698
+ Edits mask_data in place.
699
+
700
+ Requires open-cv as a dependency.
701
+ """
702
+ if len(mask_data["rles"]) == 0:
703
+ return mask_data
704
+
705
+ # Filter small disconnected regions and holes
706
+ new_masks = []
707
+ scores = []
708
+ for rle in mask_data["rles"]:
709
+ mask = rle_to_mask(rle)
710
+
711
+ mask, changed = remove_small_regions(mask, min_area, mode="holes")
712
+ unchanged = not changed
713
+ mask, changed = remove_small_regions(mask, min_area, mode="islands")
714
+ unchanged = unchanged and not changed
715
+
716
+ new_masks.append(torch.as_tensor(mask).unsqueeze(0))
717
+ # Give score=0 to changed masks and score=1 to unchanged masks
718
+ # so NMS will prefer ones that didn't need postprocessing
719
+ scores.append(float(unchanged))
720
+
721
+ # Recalculate boxes and remove any new duplicates
722
+ masks = torch.cat(new_masks, dim=0)
723
+ # TODO: This doesn't use the possibly compiled self.batched_mask_to_box
724
+ boxes = batched_mask_to_box(masks)
725
+ keep_by_nms = batched_nms(
726
+ boxes.float(),
727
+ torch.as_tensor(scores),
728
+ torch.zeros_like(boxes[:, 0]), # categories
729
+ iou_threshold=nms_thresh,
730
+ )
731
+
732
+ # Only recalculate RLEs for masks that have changed
733
+ for i_mask in keep_by_nms:
734
+ if scores[i_mask] == 0.0:
735
+ mask_torch = masks[i_mask].unsqueeze(0)
736
+ mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0]
737
+ mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly
738
+ mask_data.filter(keep_by_nms)
739
+
740
+ return mask_data
741
+
742
+ def refine_with_m2m(self, points, point_labels, low_res_masks, points_per_batch):
743
+ new_masks = []
744
+ new_iou_preds = []
745
+
746
+ for cur_points, cur_point_labels, low_res_mask in batch_iterator(
747
+ points_per_batch, points, point_labels, low_res_masks
748
+ ):
749
+ best_masks, best_iou_preds, _ = self.predictor._predict(
750
+ cur_points[:, None, :],
751
+ cur_point_labels[:, None],
752
+ mask_input=low_res_mask[:, None, :],
753
+ multimask_output=False,
754
+ return_logits=True,
755
+ )
756
+ new_masks.append(best_masks)
757
+ new_iou_preds.append(best_iou_preds)
758
+ masks = torch.cat(new_masks, dim=0)
759
+ return masks, torch.cat(new_iou_preds, dim=0)
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/build_sam.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+ import os
9
+
10
+ import torch
11
+ from hydra import compose
12
+ from hydra.utils import instantiate
13
+ from omegaconf import OmegaConf
14
+
15
+ from torchao._models import sam2
16
+
17
+ # Check if the user is running Python from the parent directory of the sam2 repo
18
+ # (i.e. the directory where this repo is cloned into) -- this is not supported since
19
+ # it could shadow the sam2 package and cause issues.
20
+ if os.path.isdir(os.path.join(sam2.__path__[0], "sam2")):
21
+ # If the user has "sam2/sam2" in their path, they are likey importing the repo itself
22
+ # as "sam2" rather than importing the "sam2" python package (i.e. "sam2/sam2" directory).
23
+ # This typically happens because the user is running Python from the parent directory
24
+ # that contains the sam2 repo they cloned.
25
+ raise RuntimeError(
26
+ "You're likely running Python from the parent directory of the sam2 repository "
27
+ "(i.e. the directory where https://github.com/facebookresearch/sam2 is cloned into). "
28
+ "This is not supported since the `sam2` Python package could be shadowed by the "
29
+ "repository name (the repository is also named `sam2` and contains the Python package "
30
+ "in `sam2/sam2`). Please run Python from another directory (e.g. from the repo dir "
31
+ "rather than its parent dir, or from your home directory) after installing SAM 2."
32
+ )
33
+
34
+
35
+ HF_MODEL_ID_TO_FILENAMES = {
36
+ "facebook/sam2-hiera-tiny": (
37
+ "configs/sam2/sam2_hiera_t.yaml",
38
+ "sam2_hiera_tiny.pt",
39
+ ),
40
+ "facebook/sam2-hiera-small": (
41
+ "configs/sam2/sam2_hiera_s.yaml",
42
+ "sam2_hiera_small.pt",
43
+ ),
44
+ "facebook/sam2-hiera-base-plus": (
45
+ "configs/sam2/sam2_hiera_b+.yaml",
46
+ "sam2_hiera_base_plus.pt",
47
+ ),
48
+ "facebook/sam2-hiera-large": (
49
+ "configs/sam2/sam2_hiera_l.yaml",
50
+ "sam2_hiera_large.pt",
51
+ ),
52
+ "facebook/sam2.1-hiera-tiny": (
53
+ "configs/sam2.1/sam2.1_hiera_t.yaml",
54
+ "sam2.1_hiera_tiny.pt",
55
+ ),
56
+ "facebook/sam2.1-hiera-small": (
57
+ "configs/sam2.1/sam2.1_hiera_s.yaml",
58
+ "sam2.1_hiera_small.pt",
59
+ ),
60
+ "facebook/sam2.1-hiera-base-plus": (
61
+ "configs/sam2.1/sam2.1_hiera_b+.yaml",
62
+ "sam2.1_hiera_base_plus.pt",
63
+ ),
64
+ "facebook/sam2.1-hiera-large": (
65
+ "configs/sam2.1/sam2.1_hiera_l.yaml",
66
+ "sam2.1_hiera_large.pt",
67
+ ),
68
+ }
69
+
70
+
71
+ def build_sam2(
72
+ config_file,
73
+ ckpt_path=None,
74
+ device="cuda",
75
+ mode="eval",
76
+ hydra_overrides_extra=[],
77
+ apply_postprocessing=True,
78
+ **kwargs,
79
+ ):
80
+ if apply_postprocessing:
81
+ hydra_overrides_extra = hydra_overrides_extra.copy()
82
+ hydra_overrides_extra += [
83
+ # dynamically fall back to multi-mask if the single mask is not stable
84
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
85
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
86
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
87
+ ]
88
+ # Read config and init model
89
+ cfg = compose(config_name=config_file, overrides=hydra_overrides_extra)
90
+ OmegaConf.resolve(cfg)
91
+ model = instantiate(cfg.model, _recursive_=True)
92
+ _load_checkpoint(model, ckpt_path)
93
+ model = model.to(device)
94
+ if mode == "eval":
95
+ model.eval()
96
+ return model
97
+
98
+
99
+ def build_sam2_video_predictor(
100
+ config_file,
101
+ ckpt_path=None,
102
+ device="cuda",
103
+ mode="eval",
104
+ hydra_overrides_extra=[],
105
+ apply_postprocessing=True,
106
+ **kwargs,
107
+ ):
108
+ hydra_overrides = [
109
+ "++model._target_=torchao._models.sam2.sam2_video_predictor.SAM2VideoPredictor",
110
+ ]
111
+ if apply_postprocessing:
112
+ hydra_overrides_extra = hydra_overrides_extra.copy()
113
+ hydra_overrides_extra += [
114
+ # dynamically fall back to multi-mask if the single mask is not stable
115
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true",
116
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05",
117
+ "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98",
118
+ # the sigmoid mask logits on interacted frames with clicks in the memory encoder so that the encoded masks are exactly as what users see from clicking
119
+ "++model.binarize_mask_from_pts_for_mem_enc=true",
120
+ # fill small holes in the low-res masks up to `fill_hole_area` (before resizing them to the original video resolution)
121
+ "++model.fill_hole_area=8",
122
+ ]
123
+ hydra_overrides.extend(hydra_overrides_extra)
124
+
125
+ # Read config and init model
126
+ cfg = compose(config_name=config_file, overrides=hydra_overrides)
127
+ OmegaConf.resolve(cfg)
128
+ model = instantiate(cfg.model, _recursive_=True)
129
+ _load_checkpoint(model, ckpt_path)
130
+ model = model.to(device)
131
+ if mode == "eval":
132
+ model.eval()
133
+ return model
134
+
135
+
136
+ def _hf_download(model_id):
137
+ from huggingface_hub import hf_hub_download
138
+
139
+ config_name, checkpoint_name = HF_MODEL_ID_TO_FILENAMES[model_id]
140
+ ckpt_path = hf_hub_download(repo_id=model_id, filename=checkpoint_name)
141
+ return config_name, ckpt_path
142
+
143
+
144
+ def build_sam2_hf(model_id, **kwargs):
145
+ config_name, ckpt_path = _hf_download(model_id)
146
+ return build_sam2(config_file=config_name, ckpt_path=ckpt_path, **kwargs)
147
+
148
+
149
+ def build_sam2_video_predictor_hf(model_id, **kwargs):
150
+ config_name, ckpt_path = _hf_download(model_id)
151
+ return build_sam2_video_predictor(
152
+ config_file=config_name, ckpt_path=ckpt_path, **kwargs
153
+ )
154
+
155
+
156
+ def _load_checkpoint(model, ckpt_path):
157
+ if ckpt_path is not None:
158
+ sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)["model"]
159
+ missing_keys, unexpected_keys = model.load_state_dict(sd)
160
+ if missing_keys:
161
+ logging.error(missing_keys)
162
+ raise RuntimeError()
163
+ if unexpected_keys:
164
+ logging.error(unexpected_keys)
165
+ raise RuntimeError()
166
+ logging.info("Loaded checkpoint sucessfully")
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1/sam2.1_hiera_l.yaml ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base
6
+ image_encoder:
7
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 1
9
+ trunk:
10
+ _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera
11
+ embed_dim: 144
12
+ num_heads: 2
13
+ stages: [2, 6, 36, 4]
14
+ global_att_blocks: [23, 33, 43]
15
+ window_pos_embed_bkg_spatial_size: [7, 7]
16
+ window_spec: [8, 4, 16, 8]
17
+ neck:
18
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck
19
+ position_encoding:
20
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
21
+ num_pos_feats: 256
22
+ normalize: true
23
+ scale: null
24
+ temperature: 10000
25
+ d_model: 256
26
+ backbone_channel_list: [1152, 576, 288, 144]
27
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
28
+ fpn_interp_model: nearest
29
+
30
+ memory_attention:
31
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention
32
+ d_model: 256
33
+ pos_enc_at_input: true
34
+ layer:
35
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer
36
+ activation: relu
37
+ dim_feedforward: 2048
38
+ dropout: 0.1
39
+ pos_enc_at_attn: false
40
+ self_attention:
41
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
42
+ rope_theta: 10000.0
43
+ feat_sizes: [32, 32]
44
+ embedding_dim: 256
45
+ num_heads: 1
46
+ downsample_rate: 1
47
+ dropout: 0.1
48
+ d_model: 256
49
+ pos_enc_at_cross_attn_keys: true
50
+ pos_enc_at_cross_attn_queries: false
51
+ cross_attention:
52
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
53
+ rope_theta: 10000.0
54
+ feat_sizes: [32, 32]
55
+ rope_k_repeat: True
56
+ embedding_dim: 256
57
+ num_heads: 1
58
+ downsample_rate: 1
59
+ dropout: 0.1
60
+ kv_in_dim: 64
61
+ num_layers: 4
62
+
63
+ memory_encoder:
64
+ _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder
65
+ out_dim: 64
66
+ position_encoding:
67
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
68
+ num_pos_feats: 64
69
+ normalize: true
70
+ scale: null
71
+ temperature: 10000
72
+ mask_downsampler:
73
+ _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler
74
+ kernel_size: 3
75
+ stride: 2
76
+ padding: 1
77
+ fuser:
78
+ _target_: torchao._models.sam2.modeling.memory_encoder.Fuser
79
+ layer:
80
+ _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock
81
+ dim: 256
82
+ kernel_size: 7
83
+ padding: 3
84
+ layer_scale_init_value: 1e-6
85
+ use_dwconv: True # depth-wise convs
86
+ num_layers: 2
87
+
88
+ num_maskmem: 7
89
+ image_size: 1024
90
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
91
+ sigmoid_scale_for_mem_enc: 20.0
92
+ sigmoid_bias_for_mem_enc: -10.0
93
+ use_mask_input_as_output_without_sam: true
94
+ # Memory
95
+ directly_add_no_mem_embed: true
96
+ no_obj_embed_spatial: true
97
+ # use high-resolution feature map in the SAM mask decoder
98
+ use_high_res_features_in_sam: true
99
+ # output 3 masks on the first click on initial conditioning frames
100
+ multimask_output_in_sam: true
101
+ # SAM heads
102
+ iou_prediction_use_sigmoid: True
103
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
104
+ use_obj_ptrs_in_encoder: true
105
+ add_tpos_enc_to_obj_ptrs: true
106
+ proj_tpos_enc_in_obj_ptrs: true
107
+ use_signed_tpos_enc_to_obj_ptrs: true
108
+ only_obj_ptrs_in_the_past_for_eval: true
109
+ # object occlusion prediction
110
+ pred_obj_scores: true
111
+ pred_obj_scores_mlp: true
112
+ fixed_no_obj_ptr: true
113
+ # multimask tracking settings
114
+ multimask_output_for_tracking: true
115
+ use_multimask_token_for_obj_ptr: true
116
+ multimask_min_pt_num: 0
117
+ multimask_max_pt_num: 1
118
+ use_mlp_for_obj_ptr_proj: true
119
+ # Compilation flag
120
+ compile_image_encoder: False
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1/sam2.1_hiera_t.yaml ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base
6
+ image_encoder:
7
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 1
9
+ trunk:
10
+ _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera
11
+ embed_dim: 96
12
+ num_heads: 1
13
+ stages: [1, 2, 7, 2]
14
+ global_att_blocks: [5, 7, 9]
15
+ window_pos_embed_bkg_spatial_size: [7, 7]
16
+ neck:
17
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck
18
+ position_encoding:
19
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
20
+ num_pos_feats: 256
21
+ normalize: true
22
+ scale: null
23
+ temperature: 10000
24
+ d_model: 256
25
+ backbone_channel_list: [768, 384, 192, 96]
26
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
27
+ fpn_interp_model: nearest
28
+
29
+ memory_attention:
30
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention
31
+ d_model: 256
32
+ pos_enc_at_input: true
33
+ layer:
34
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer
35
+ activation: relu
36
+ dim_feedforward: 2048
37
+ dropout: 0.1
38
+ pos_enc_at_attn: false
39
+ self_attention:
40
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
41
+ rope_theta: 10000.0
42
+ feat_sizes: [32, 32]
43
+ embedding_dim: 256
44
+ num_heads: 1
45
+ downsample_rate: 1
46
+ dropout: 0.1
47
+ d_model: 256
48
+ pos_enc_at_cross_attn_keys: true
49
+ pos_enc_at_cross_attn_queries: false
50
+ cross_attention:
51
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
52
+ rope_theta: 10000.0
53
+ feat_sizes: [32, 32]
54
+ rope_k_repeat: True
55
+ embedding_dim: 256
56
+ num_heads: 1
57
+ downsample_rate: 1
58
+ dropout: 0.1
59
+ kv_in_dim: 64
60
+ num_layers: 4
61
+
62
+ memory_encoder:
63
+ _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder
64
+ out_dim: 64
65
+ position_encoding:
66
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
67
+ num_pos_feats: 64
68
+ normalize: true
69
+ scale: null
70
+ temperature: 10000
71
+ mask_downsampler:
72
+ _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler
73
+ kernel_size: 3
74
+ stride: 2
75
+ padding: 1
76
+ fuser:
77
+ _target_: torchao._models.sam2.modeling.memory_encoder.Fuser
78
+ layer:
79
+ _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock
80
+ dim: 256
81
+ kernel_size: 7
82
+ padding: 3
83
+ layer_scale_init_value: 1e-6
84
+ use_dwconv: True # depth-wise convs
85
+ num_layers: 2
86
+
87
+ num_maskmem: 7
88
+ image_size: 1024
89
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
90
+ # SAM decoder
91
+ sigmoid_scale_for_mem_enc: 20.0
92
+ sigmoid_bias_for_mem_enc: -10.0
93
+ use_mask_input_as_output_without_sam: true
94
+ # Memory
95
+ directly_add_no_mem_embed: true
96
+ no_obj_embed_spatial: true
97
+ # use high-resolution feature map in the SAM mask decoder
98
+ use_high_res_features_in_sam: true
99
+ # output 3 masks on the first click on initial conditioning frames
100
+ multimask_output_in_sam: true
101
+ # SAM heads
102
+ iou_prediction_use_sigmoid: True
103
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
104
+ use_obj_ptrs_in_encoder: true
105
+ add_tpos_enc_to_obj_ptrs: true
106
+ proj_tpos_enc_in_obj_ptrs: true
107
+ use_signed_tpos_enc_to_obj_ptrs: true
108
+ only_obj_ptrs_in_the_past_for_eval: true
109
+ # object occlusion prediction
110
+ pred_obj_scores: true
111
+ pred_obj_scores_mlp: true
112
+ fixed_no_obj_ptr: true
113
+ # multimask tracking settings
114
+ multimask_output_for_tracking: true
115
+ use_multimask_token_for_obj_ptr: true
116
+ multimask_min_pt_num: 0
117
+ multimask_max_pt_num: 1
118
+ use_mlp_for_obj_ptr_proj: true
119
+ # Compilation flag
120
+ # HieraT does not currently support compilation, should always be set to False
121
+ compile_image_encoder: False
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1_training/sam2.1_hiera_b+_MOSE_finetune.yaml ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ scratch:
4
+ resolution: 1024
5
+ train_batch_size: 1
6
+ num_train_workers: 10
7
+ num_frames: 8
8
+ max_num_objects: 3
9
+ base_lr: 5.0e-6
10
+ vision_lr: 3.0e-06
11
+ phases_per_epoch: 1
12
+ num_epochs: 40
13
+
14
+ dataset:
15
+ # PATHS to Dataset
16
+ img_folder: null # PATH to MOSE JPEGImages folder
17
+ gt_folder: null # PATH to MOSE Annotations folder
18
+ file_list_txt: training/assets/MOSE_sample_train_list.txt # Optional PATH to filelist containing a subset of videos to be used for training
19
+ multiplier: 2
20
+
21
+ # Video transforms
22
+ vos:
23
+ train_transforms:
24
+ - _target_: training.dataset.transforms.ComposeAPI
25
+ transforms:
26
+ - _target_: training.dataset.transforms.RandomHorizontalFlip
27
+ consistent_transform: True
28
+ - _target_: training.dataset.transforms.RandomAffine
29
+ degrees: 25
30
+ shear: 20
31
+ image_interpolation: bilinear
32
+ consistent_transform: True
33
+ - _target_: training.dataset.transforms.RandomResizeAPI
34
+ sizes: ${scratch.resolution}
35
+ square: true
36
+ consistent_transform: True
37
+ - _target_: training.dataset.transforms.ColorJitter
38
+ consistent_transform: True
39
+ brightness: 0.1
40
+ contrast: 0.03
41
+ saturation: 0.03
42
+ hue: null
43
+ - _target_: training.dataset.transforms.RandomGrayscale
44
+ p: 0.05
45
+ consistent_transform: True
46
+ - _target_: training.dataset.transforms.ColorJitter
47
+ consistent_transform: False
48
+ brightness: 0.1
49
+ contrast: 0.05
50
+ saturation: 0.05
51
+ hue: null
52
+ - _target_: training.dataset.transforms.ToTensorAPI
53
+ - _target_: training.dataset.transforms.NormalizeAPI
54
+ mean: [0.485, 0.456, 0.406]
55
+ std: [0.229, 0.224, 0.225]
56
+
57
+ trainer:
58
+ _target_: training.trainer.Trainer
59
+ mode: train_only
60
+ max_epochs: ${times:${scratch.num_epochs},${scratch.phases_per_epoch}}
61
+ accelerator: cuda
62
+ seed_value: 123
63
+
64
+ model:
65
+ _target_: training.model.sam2.SAM2Train
66
+ image_encoder:
67
+ _target_: sam2.modeling.backbones.image_encoder.ImageEncoder
68
+ scalp: 1
69
+ trunk:
70
+ _target_: sam2.modeling.backbones.hieradet.Hiera
71
+ embed_dim: 112
72
+ num_heads: 2
73
+ drop_path_rate: 0.1
74
+ neck:
75
+ _target_: sam2.modeling.backbones.image_encoder.FpnNeck
76
+ position_encoding:
77
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
78
+ num_pos_feats: 256
79
+ normalize: true
80
+ scale: null
81
+ temperature: 10000
82
+ d_model: 256
83
+ backbone_channel_list: [896, 448, 224, 112]
84
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
85
+ fpn_interp_model: nearest
86
+
87
+ memory_attention:
88
+ _target_: sam2.modeling.memory_attention.MemoryAttention
89
+ d_model: 256
90
+ pos_enc_at_input: true
91
+ layer:
92
+ _target_: sam2.modeling.memory_attention.MemoryAttentionLayer
93
+ activation: relu
94
+ dim_feedforward: 2048
95
+ dropout: 0.1
96
+ pos_enc_at_attn: false
97
+ self_attention:
98
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
99
+ rope_theta: 10000.0
100
+ feat_sizes: [32, 32]
101
+ embedding_dim: 256
102
+ num_heads: 1
103
+ downsample_rate: 1
104
+ dropout: 0.1
105
+ d_model: 256
106
+ pos_enc_at_cross_attn_keys: true
107
+ pos_enc_at_cross_attn_queries: false
108
+ cross_attention:
109
+ _target_: sam2.modeling.sam.transformer.RoPEAttention
110
+ rope_theta: 10000.0
111
+ feat_sizes: [32, 32]
112
+ rope_k_repeat: True
113
+ embedding_dim: 256
114
+ num_heads: 1
115
+ downsample_rate: 1
116
+ dropout: 0.1
117
+ kv_in_dim: 64
118
+ num_layers: 4
119
+
120
+ memory_encoder:
121
+ _target_: sam2.modeling.memory_encoder.MemoryEncoder
122
+ out_dim: 64
123
+ position_encoding:
124
+ _target_: sam2.modeling.position_encoding.PositionEmbeddingSine
125
+ num_pos_feats: 64
126
+ normalize: true
127
+ scale: null
128
+ temperature: 10000
129
+ mask_downsampler:
130
+ _target_: sam2.modeling.memory_encoder.MaskDownSampler
131
+ kernel_size: 3
132
+ stride: 2
133
+ padding: 1
134
+ fuser:
135
+ _target_: sam2.modeling.memory_encoder.Fuser
136
+ layer:
137
+ _target_: sam2.modeling.memory_encoder.CXBlock
138
+ dim: 256
139
+ kernel_size: 7
140
+ padding: 3
141
+ layer_scale_init_value: 1e-6
142
+ use_dwconv: True # depth-wise convs
143
+ num_layers: 2
144
+
145
+ num_maskmem: 7
146
+ image_size: ${scratch.resolution}
147
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
148
+ sigmoid_scale_for_mem_enc: 20.0
149
+ sigmoid_bias_for_mem_enc: -10.0
150
+ use_mask_input_as_output_without_sam: true
151
+ # Memory
152
+ directly_add_no_mem_embed: true
153
+ no_obj_embed_spatial: true
154
+ # use high-resolution feature map in the SAM mask decoder
155
+ use_high_res_features_in_sam: true
156
+ # output 3 masks on the first click on initial conditioning frames
157
+ multimask_output_in_sam: true
158
+ # SAM heads
159
+ iou_prediction_use_sigmoid: True
160
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
161
+ use_obj_ptrs_in_encoder: true
162
+ add_tpos_enc_to_obj_ptrs: true
163
+ proj_tpos_enc_in_obj_ptrs: true
164
+ use_signed_tpos_enc_to_obj_ptrs: true
165
+ only_obj_ptrs_in_the_past_for_eval: true
166
+ # object occlusion prediction
167
+ pred_obj_scores: true
168
+ pred_obj_scores_mlp: true
169
+ fixed_no_obj_ptr: true
170
+ # multimask tracking settings
171
+ multimask_output_for_tracking: true
172
+ use_multimask_token_for_obj_ptr: true
173
+ multimask_min_pt_num: 0
174
+ multimask_max_pt_num: 1
175
+ use_mlp_for_obj_ptr_proj: true
176
+ # Compilation flag
177
+ # compile_image_encoder: False
178
+
179
+ ####### Training specific params #######
180
+ # box/point input and corrections
181
+ prob_to_use_pt_input_for_train: 0.5
182
+ prob_to_use_pt_input_for_eval: 0.0
183
+ prob_to_use_box_input_for_train: 0.5 # 0.5*0.5 = 0.25 prob to use box instead of points
184
+ prob_to_use_box_input_for_eval: 0.0
185
+ prob_to_sample_from_gt_for_train: 0.1 # with a small prob, sampling correction points from GT mask instead of prediction errors
186
+ num_frames_to_correct_for_train: 2 # iteratively sample on random 1~2 frames (always include the first frame)
187
+ num_frames_to_correct_for_eval: 1 # only iteratively sample on first frame
188
+ rand_frames_to_correct_for_train: True # random #init-cond-frame ~ 2
189
+ add_all_frames_to_correct_as_cond: True # when a frame receives a correction click, it becomes a conditioning frame (even if it's not initially a conditioning frame)
190
+ # maximum 2 initial conditioning frames
191
+ num_init_cond_frames_for_train: 2
192
+ rand_init_cond_frames_for_train: True # random 1~2
193
+ num_correction_pt_per_frame: 7
194
+ use_act_ckpt_iterative_pt_sampling: false
195
+
196
+
197
+
198
+ num_init_cond_frames_for_eval: 1 # only mask on the first frame
199
+ forward_backbone_per_frame_for_eval: True
200
+
201
+
202
+ data:
203
+ train:
204
+ _target_: training.dataset.sam2_datasets.TorchTrainMixedDataset
205
+ phases_per_epoch: ${scratch.phases_per_epoch}
206
+ batch_sizes:
207
+ - ${scratch.train_batch_size}
208
+
209
+ datasets:
210
+ - _target_: training.dataset.utils.RepeatFactorWrapper
211
+ dataset:
212
+ _target_: training.dataset.utils.ConcatDataset
213
+ datasets:
214
+ - _target_: training.dataset.vos_dataset.VOSDataset
215
+ transforms: ${vos.train_transforms}
216
+ training: true
217
+ video_dataset:
218
+ _target_: training.dataset.vos_raw_dataset.PNGRawDataset
219
+ img_folder: ${dataset.img_folder}
220
+ gt_folder: ${dataset.gt_folder}
221
+ file_list_txt: ${dataset.file_list_txt}
222
+ sampler:
223
+ _target_: training.dataset.vos_sampler.RandomUniformSampler
224
+ num_frames: ${scratch.num_frames}
225
+ max_num_objects: ${scratch.max_num_objects}
226
+ multiplier: ${dataset.multiplier}
227
+ shuffle: True
228
+ num_workers: ${scratch.num_train_workers}
229
+ pin_memory: True
230
+ drop_last: True
231
+ collate_fn:
232
+ _target_: training.utils.data_utils.collate_fn
233
+ _partial_: true
234
+ dict_key: all
235
+
236
+ optim:
237
+ amp:
238
+ enabled: True
239
+ amp_dtype: bfloat16
240
+
241
+ optimizer:
242
+ _target_: torch.optim.AdamW
243
+
244
+ gradient_clip:
245
+ _target_: training.optimizer.GradientClipper
246
+ max_norm: 0.1
247
+ norm_type: 2
248
+
249
+ param_group_modifiers:
250
+ - _target_: training.optimizer.layer_decay_param_modifier
251
+ _partial_: True
252
+ layer_decay_value: 0.9
253
+ apply_to: 'image_encoder.trunk'
254
+ overrides:
255
+ - pattern: '*pos_embed*'
256
+ value: 1.0
257
+
258
+ options:
259
+ lr:
260
+ - scheduler:
261
+ _target_: fvcore.common.param_scheduler.CosineParamScheduler
262
+ start_value: ${scratch.base_lr}
263
+ end_value: ${divide:${scratch.base_lr},10}
264
+ - scheduler:
265
+ _target_: fvcore.common.param_scheduler.CosineParamScheduler
266
+ start_value: ${scratch.vision_lr}
267
+ end_value: ${divide:${scratch.vision_lr},10}
268
+ param_names:
269
+ - 'image_encoder.*'
270
+ weight_decay:
271
+ - scheduler:
272
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
273
+ value: 0.1
274
+ - scheduler:
275
+ _target_: fvcore.common.param_scheduler.ConstantParamScheduler
276
+ value: 0.0
277
+ param_names:
278
+ - '*bias*'
279
+ module_cls_names: ['torch.nn.LayerNorm']
280
+
281
+ loss:
282
+ all:
283
+ _target_: training.loss_fns.MultiStepMultiMasksAndIous
284
+ weight_dict:
285
+ loss_mask: 20
286
+ loss_dice: 1
287
+ loss_iou: 1
288
+ loss_class: 1
289
+ supervise_all_iou: true
290
+ iou_use_l1_loss: true
291
+ pred_obj_scores: true
292
+ focal_gamma_obj_score: 0.0
293
+ focal_alpha_obj_score: -1.0
294
+
295
+ distributed:
296
+ backend: nccl
297
+ find_unused_parameters: True
298
+
299
+ logging:
300
+ tensorboard_writer:
301
+ _target_: training.utils.logger.make_tensorboard_logger
302
+ log_dir: ${launcher.experiment_log_dir}/tensorboard
303
+ flush_secs: 120
304
+ should_log: True
305
+ log_dir: ${launcher.experiment_log_dir}/logs
306
+ log_freq: 10
307
+
308
+ # initialize from a SAM 2 checkpoint
309
+ checkpoint:
310
+ save_dir: ${launcher.experiment_log_dir}/checkpoints
311
+ save_freq: 0 # 0 only last checkpoint is saved.
312
+ model_weight_initializer:
313
+ _partial_: True
314
+ _target_: training.utils.checkpoint_utils.load_state_dict_into_model
315
+ strict: True
316
+ ignore_unexpected_keys: null
317
+ ignore_missing_keys: null
318
+
319
+ state_dict:
320
+ _target_: training.utils.checkpoint_utils.load_checkpoint_and_apply_kernels
321
+ checkpoint_path: ./checkpoints/sam2.1_hiera_base_plus.pt # PATH to SAM 2.1 checkpoint
322
+ ckpt_state_dict_keys: ['model']
323
+
324
+ launcher:
325
+ num_nodes: 1
326
+ gpus_per_node: 8
327
+ experiment_log_dir: null # Path to log directory, defaults to ./sam2_logs/${config_name}
328
+
329
+ # SLURM args if running on a cluster
330
+ submitit:
331
+ partition: null
332
+ account: null
333
+ qos: null
334
+ cpus_per_task: 10
335
+ use_cluster: false
336
+ timeout_hour: 24
337
+ name: null
338
+ port_range: [10000, 65000]
339
+
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/csrc/connected_components.cu ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ // All rights reserved.
3
+
4
+ // This source code is licensed under the license found in the
5
+ // LICENSE file in the root directory of this source tree.
6
+
7
+ // adapted from https://github.com/zsef123/Connected_components_PyTorch
8
+ // with license found in the LICENSE_cctorch file in the root directory.
9
+ #include <ATen/cuda/CUDAContext.h>
10
+ #include <cuda.h>
11
+ #include <cuda_runtime.h>
12
+ #include <torch/extension.h>
13
+ #include <torch/script.h>
14
+ #include <vector>
15
+
16
+ // 2d
17
+ #define BLOCK_ROWS 16
18
+ #define BLOCK_COLS 16
19
+
20
+ namespace cc2d {
21
+
22
+ template <typename T>
23
+ __device__ __forceinline__ unsigned char hasBit(T bitmap, unsigned char pos) {
24
+ return (bitmap >> pos) & 1;
25
+ }
26
+
27
+ __device__ int32_t find(const int32_t* s_buf, int32_t n) {
28
+ while (s_buf[n] != n)
29
+ n = s_buf[n];
30
+ return n;
31
+ }
32
+
33
+ __device__ int32_t find_n_compress(int32_t* s_buf, int32_t n) {
34
+ const int32_t id = n;
35
+ while (s_buf[n] != n) {
36
+ n = s_buf[n];
37
+ s_buf[id] = n;
38
+ }
39
+ return n;
40
+ }
41
+
42
+ __device__ void union_(int32_t* s_buf, int32_t a, int32_t b) {
43
+ bool done;
44
+ do {
45
+ a = find(s_buf, a);
46
+ b = find(s_buf, b);
47
+
48
+ if (a < b) {
49
+ int32_t old = atomicMin(s_buf + b, a);
50
+ done = (old == b);
51
+ b = old;
52
+ } else if (b < a) {
53
+ int32_t old = atomicMin(s_buf + a, b);
54
+ done = (old == a);
55
+ a = old;
56
+ } else
57
+ done = true;
58
+
59
+ } while (!done);
60
+ }
61
+
62
+ __global__ void
63
+ init_labeling(int32_t* label, const uint32_t W, const uint32_t H) {
64
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
65
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
66
+ const uint32_t idx = row * W + col;
67
+
68
+ if (row < H && col < W)
69
+ label[idx] = idx;
70
+ }
71
+
72
+ __global__ void
73
+ merge(uint8_t* img, int32_t* label, const uint32_t W, const uint32_t H) {
74
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
75
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
76
+ const uint32_t idx = row * W + col;
77
+
78
+ if (row >= H || col >= W)
79
+ return;
80
+
81
+ uint32_t P = 0;
82
+
83
+ if (img[idx])
84
+ P |= 0x777;
85
+ if (row + 1 < H && img[idx + W])
86
+ P |= 0x777 << 4;
87
+ if (col + 1 < W && img[idx + 1])
88
+ P |= 0x777 << 1;
89
+
90
+ if (col == 0)
91
+ P &= 0xEEEE;
92
+ if (col + 1 >= W)
93
+ P &= 0x3333;
94
+ else if (col + 2 >= W)
95
+ P &= 0x7777;
96
+
97
+ if (row == 0)
98
+ P &= 0xFFF0;
99
+ if (row + 1 >= H)
100
+ P &= 0xFF;
101
+
102
+ if (P > 0) {
103
+ // If need check about top-left pixel(if flag the first bit) and hit the
104
+ // top-left pixel
105
+ if (hasBit(P, 0) && img[idx - W - 1]) {
106
+ union_(label, idx, idx - 2 * W - 2); // top left block
107
+ }
108
+
109
+ if ((hasBit(P, 1) && img[idx - W]) || (hasBit(P, 2) && img[idx - W + 1]))
110
+ union_(label, idx, idx - 2 * W); // top bottom block
111
+
112
+ if (hasBit(P, 3) && img[idx + 2 - W])
113
+ union_(label, idx, idx - 2 * W + 2); // top right block
114
+
115
+ if ((hasBit(P, 4) && img[idx - 1]) || (hasBit(P, 8) && img[idx + W - 1]))
116
+ union_(label, idx, idx - 2); // just left block
117
+ }
118
+ }
119
+
120
+ __global__ void compression(int32_t* label, const int32_t W, const int32_t H) {
121
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
122
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
123
+ const uint32_t idx = row * W + col;
124
+
125
+ if (row < H && col < W)
126
+ find_n_compress(label, idx);
127
+ }
128
+
129
+ __global__ void final_labeling(
130
+ const uint8_t* img,
131
+ int32_t* label,
132
+ const int32_t W,
133
+ const int32_t H) {
134
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2;
135
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2;
136
+ const uint32_t idx = row * W + col;
137
+
138
+ if (row >= H || col >= W)
139
+ return;
140
+
141
+ int32_t y = label[idx] + 1;
142
+
143
+ if (img[idx])
144
+ label[idx] = y;
145
+ else
146
+ label[idx] = 0;
147
+
148
+ if (col + 1 < W) {
149
+ if (img[idx + 1])
150
+ label[idx + 1] = y;
151
+ else
152
+ label[idx + 1] = 0;
153
+
154
+ if (row + 1 < H) {
155
+ if (img[idx + W + 1])
156
+ label[idx + W + 1] = y;
157
+ else
158
+ label[idx + W + 1] = 0;
159
+ }
160
+ }
161
+
162
+ if (row + 1 < H) {
163
+ if (img[idx + W])
164
+ label[idx + W] = y;
165
+ else
166
+ label[idx + W] = 0;
167
+ }
168
+ }
169
+
170
+ __global__ void init_counting(
171
+ const int32_t* label,
172
+ int32_t* count_init,
173
+ const int32_t W,
174
+ const int32_t H) {
175
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y);
176
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x);
177
+ const uint32_t idx = row * W + col;
178
+
179
+ if (row >= H || col >= W)
180
+ return;
181
+
182
+ int32_t y = label[idx];
183
+ if (y > 0) {
184
+ int32_t count_idx = y - 1;
185
+ atomicAdd(count_init + count_idx, 1);
186
+ }
187
+ }
188
+
189
+ __global__ void final_counting(
190
+ const int32_t* label,
191
+ const int32_t* count_init,
192
+ int32_t* count_final,
193
+ const int32_t W,
194
+ const int32_t H) {
195
+ const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y);
196
+ const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x);
197
+ const uint32_t idx = row * W + col;
198
+
199
+ if (row >= H || col >= W)
200
+ return;
201
+
202
+ int32_t y = label[idx];
203
+ if (y > 0) {
204
+ int32_t count_idx = y - 1;
205
+ count_final[idx] = count_init[count_idx];
206
+ } else {
207
+ count_final[idx] = 0;
208
+ }
209
+ }
210
+
211
+ } // namespace cc2d
212
+
213
+ std::vector<torch::Tensor> get_connected_componnets(
214
+ const torch::Tensor& inputs) {
215
+ AT_ASSERTM(inputs.is_cuda(), "inputs must be a CUDA tensor");
216
+ AT_ASSERTM(inputs.ndimension() == 4, "inputs must be [N, 1, H, W] shape");
217
+ AT_ASSERTM(
218
+ inputs.scalar_type() == torch::kUInt8, "inputs must be a uint8 type");
219
+
220
+ const uint32_t N = inputs.size(0);
221
+ const uint32_t C = inputs.size(1);
222
+ const uint32_t H = inputs.size(2);
223
+ const uint32_t W = inputs.size(3);
224
+
225
+ AT_ASSERTM(C == 1, "inputs must be [N, 1, H, W] shape");
226
+ AT_ASSERTM((H % 2) == 0, "height must be an even number");
227
+ AT_ASSERTM((W % 2) == 0, "width must be an even number");
228
+
229
+ // label must be uint32_t
230
+ auto label_options =
231
+ torch::TensorOptions().dtype(torch::kInt32).device(inputs.device());
232
+ torch::Tensor labels = torch::zeros({N, C, H, W}, label_options);
233
+ torch::Tensor counts_init = torch::zeros({N, C, H, W}, label_options);
234
+ torch::Tensor counts_final = torch::zeros({N, C, H, W}, label_options);
235
+
236
+ dim3 grid = dim3(
237
+ ((W + 1) / 2 + BLOCK_COLS - 1) / BLOCK_COLS,
238
+ ((H + 1) / 2 + BLOCK_ROWS - 1) / BLOCK_ROWS);
239
+ dim3 block = dim3(BLOCK_COLS, BLOCK_ROWS);
240
+ dim3 grid_count =
241
+ dim3((W + BLOCK_COLS) / BLOCK_COLS, (H + BLOCK_ROWS) / BLOCK_ROWS);
242
+ dim3 block_count = dim3(BLOCK_COLS, BLOCK_ROWS);
243
+ cudaStream_t stream = at::cuda::getCurrentCUDAStream();
244
+
245
+ for (int n = 0; n < N; n++) {
246
+ uint32_t offset = n * H * W;
247
+
248
+ cc2d::init_labeling<<<grid, block, 0, stream>>>(
249
+ labels.data_ptr<int32_t>() + offset, W, H);
250
+ cc2d::merge<<<grid, block, 0, stream>>>(
251
+ inputs.data_ptr<uint8_t>() + offset,
252
+ labels.data_ptr<int32_t>() + offset,
253
+ W,
254
+ H);
255
+ cc2d::compression<<<grid, block, 0, stream>>>(
256
+ labels.data_ptr<int32_t>() + offset, W, H);
257
+ cc2d::final_labeling<<<grid, block, 0, stream>>>(
258
+ inputs.data_ptr<uint8_t>() + offset,
259
+ labels.data_ptr<int32_t>() + offset,
260
+ W,
261
+ H);
262
+
263
+ // get the counting of each pixel
264
+ cc2d::init_counting<<<grid_count, block_count, 0, stream>>>(
265
+ labels.data_ptr<int32_t>() + offset,
266
+ counts_init.data_ptr<int32_t>() + offset,
267
+ W,
268
+ H);
269
+ cc2d::final_counting<<<grid_count, block_count, 0, stream>>>(
270
+ labels.data_ptr<int32_t>() + offset,
271
+ counts_init.data_ptr<int32_t>() + offset,
272
+ counts_final.data_ptr<int32_t>() + offset,
273
+ W,
274
+ H);
275
+ }
276
+
277
+ // returned values are [labels, counts]
278
+ std::vector<torch::Tensor> outputs;
279
+ outputs.push_back(labels);
280
+ outputs.push_back(counts_final);
281
+ return outputs;
282
+ }
283
+
284
+ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
285
+ m.def(
286
+ "get_connected_componnets",
287
+ &get_connected_componnets,
288
+ "get_connected_componnets");
289
+ }
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/map_tensor.py ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+ #
4
+ # This source code is licensed under the BSD 3-Clause license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+ import contextlib
7
+ import functools
8
+ from typing import Dict
9
+
10
+ import torch
11
+ from torch.nested._internal.nested_tensor import nested_view_from_values_offsets
12
+ from torch.utils._pytree import tree_map
13
+
14
+ MAP_TENSOR_ATEN_OP_TABLE = {}
15
+
16
+
17
+ def implements(aten_ops_or_torch_fns):
18
+ if not isinstance(aten_ops_or_torch_fns, (list, tuple)):
19
+ aten_ops_or_torch_fns = [aten_ops_or_torch_fns]
20
+
21
+ def decorator(func):
22
+ for op in aten_ops_or_torch_fns:
23
+
24
+ @functools.wraps(op)
25
+ def wrapper(f, types, args, kwargs):
26
+ return func(f, types, args, kwargs)
27
+
28
+ MAP_TENSOR_ATEN_OP_TABLE[op] = wrapper
29
+ return func
30
+
31
+ return decorator
32
+
33
+
34
+ @contextlib.contextmanager
35
+ def no_dispatch():
36
+ guard = torch._C._DisableTorchDispatch()
37
+ try:
38
+ yield
39
+ finally:
40
+ del guard
41
+
42
+
43
+ def wrap_dim(i, dim):
44
+ if i < 0:
45
+ return dim + i
46
+ return i
47
+
48
+
49
+ def unwrap(t):
50
+ if isinstance(t, MapTensor):
51
+ with no_dispatch():
52
+ return t.elems
53
+ else:
54
+ return t
55
+
56
+
57
+ def unwrap_i(t, i):
58
+ if isinstance(t, MapTensor):
59
+ with no_dispatch():
60
+ return t.elems[i]
61
+ else:
62
+ return t
63
+
64
+
65
+ def unwrap_fn(t, fn):
66
+ if isinstance(t, MapTensor):
67
+ with no_dispatch():
68
+ return fn(t.elems)
69
+ else:
70
+ return None
71
+
72
+
73
+ def wrap(t):
74
+ if isinstance(t, torch.Tensor):
75
+ return MapTensor(t)
76
+ else:
77
+ return t
78
+
79
+
80
+ @implements(torch.ops.aten.native_layer_norm.default)
81
+ def layer_norm_impl(func, types, args, kwargs=None):
82
+ unwrapped_args = tree_map(unwrap, args)
83
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
84
+ assert len(unwrapped_kwargs) == 0
85
+ assert len(unwrapped_args) == 5, f"args: {unwrapped_args}"
86
+ norm_res = func(*unwrapped_args)
87
+ assert len(norm_res) == 3
88
+ return tuple(wrap(a) for a in norm_res)
89
+
90
+
91
+ @implements(torch.ops.aten.add.Tensor)
92
+ def add_impl(func, types, args, kwargs):
93
+ unwrapped_args = tree_map(unwrap, args)
94
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
95
+ assert len(unwrapped_kwargs) == 0
96
+ assert len(unwrapped_args) == 2, f"args: {unwrapped_args}"
97
+ if not isinstance(args[0], MapTensor) and isinstance(args[1], MapTensor):
98
+ if args[0].dim() == (args[1].dim() + 1):
99
+ return NotImplemented
100
+ return NotImplemented
101
+ return wrap(func(*unwrapped_args, **unwrapped_kwargs))
102
+
103
+
104
+ @implements([torch.ops.aten.cat.default, torch.ops.aten.stack.default])
105
+ def cat_ops_impl(func, types, args, kwargs):
106
+ unwrapped_args = tree_map(unwrap, args)
107
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
108
+ assert len(unwrapped_kwargs) == 0
109
+ assert len(unwrapped_args) <= 2, f"args: {unwrapped_args}"
110
+ # TODO: Use MapTensor type for filter
111
+ # First argument's dim
112
+ dim = unwrapped_args[0][0].dim()
113
+ size = unwrapped_args[0][0].size()
114
+ for a in unwrapped_args[0]:
115
+ if a.dim() > dim:
116
+ dim = a.dim()
117
+ size = a.size()
118
+ new_args = []
119
+ for a in unwrapped_args[0]:
120
+ if a.dim() == dim:
121
+ new_args.append(a)
122
+ else:
123
+ assert a.dim() + 1 == dim
124
+ new_args.append(a.unsqueeze(0).expand((size[0],) + a.size()))
125
+ orig_dim = unwrapped_args[1] if len(unwrapped_args) == 2 else 0
126
+ return wrap(func(new_args, wrap_dim(orig_dim, dim - 1) + 1))
127
+
128
+
129
+ @implements(torch.ops.aten.select.int)
130
+ def select_impl(func, types, args, kwargs):
131
+ unwrapped_args = tree_map(unwrap, args)
132
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
133
+ assert len(unwrapped_kwargs) == 0
134
+ assert len(unwrapped_args) == 3, f"args: {unwrapped_args}"
135
+ return wrap(func(unwrapped_args[0], unwrapped_args[1] + 1, unwrapped_args[2]))
136
+
137
+
138
+ @implements(torch.ops.aten.slice.Tensor)
139
+ def slice_impl(func, types, args, kwargs):
140
+ unwrapped_args = tree_map(unwrap, args)
141
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
142
+ assert len(unwrapped_kwargs) == 0
143
+ assert len(unwrapped_args) == 4, f"args: {unwrapped_args}"
144
+ dim = unwrapped_args[0].dim()
145
+ return wrap(
146
+ func(
147
+ unwrapped_args[0],
148
+ wrap_dim(unwrapped_args[1], dim - 1) + 1,
149
+ unwrapped_args[2],
150
+ unwrapped_args[3],
151
+ )
152
+ )
153
+
154
+
155
+ @implements(
156
+ [
157
+ torch.ops.aten.mean.dim,
158
+ torch.ops.aten.max.dim,
159
+ torch.ops.aten.argmax.default,
160
+ torch.ops.aten.min.dim,
161
+ torch.ops.aten.any.dim,
162
+ torch.ops.aten.amax.default,
163
+ torch.ops.aten.amin.default,
164
+ torch.ops.aten.all.default,
165
+ torch.ops.aten.sum.dim_IntList,
166
+ ]
167
+ )
168
+ def reductions_impl(func, types, args, kwargs):
169
+ unwrapped_args = tree_map(unwrap, args)
170
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
171
+ # TODO: THIS MIGHT BE WRONG
172
+ if len(unwrapped_args) == 3 and len(unwrapped_kwargs) == 0:
173
+ assert len(unwrapped_args[1]) == 1
174
+ dim = unwrapped_args[0].dim()
175
+ return wrap(
176
+ func(
177
+ unwrapped_args[0],
178
+ [wrap_dim(u, dim - 1) + 1 for u in unwrapped_args[1]],
179
+ unwrapped_args[2],
180
+ )
181
+ )
182
+ if len(unwrapped_args) == 2 and len(unwrapped_kwargs) == 1:
183
+ assert len(unwrapped_args[1]) == 1
184
+ dim = unwrapped_args[0].dim()
185
+ return wrap(
186
+ func(
187
+ unwrapped_args[0],
188
+ [wrap_dim(u, dim - 1) + 1 for u in unwrapped_args[1]],
189
+ **unwrapped_kwargs,
190
+ )
191
+ )
192
+ if (
193
+ len(unwrapped_args) == 2
194
+ and len(unwrapped_kwargs) == 0
195
+ and type(unwrapped_args[1]) == list
196
+ ):
197
+ assert len(unwrapped_args[1]) == 1
198
+ dim = unwrapped_args[0].dim()
199
+ return wrap(
200
+ func(
201
+ unwrapped_args[0], [wrap_dim(u, dim - 1) + 1 for u in unwrapped_args[1]]
202
+ )
203
+ )
204
+ if (
205
+ len(unwrapped_args) == 2
206
+ and len(unwrapped_kwargs) == 0
207
+ and type(unwrapped_args[1]) == int
208
+ ):
209
+ dim = unwrapped_args[0].dim()
210
+ return wrap(func(unwrapped_args[0], wrap_dim(unwrapped_args[1], dim - 1) + 1))
211
+ if len(args) == 1 and len(kwargs) == 0:
212
+ return wrap(func(unwrapped_args[0]))
213
+ return NotImplemented
214
+
215
+
216
+ @implements([torch.ops.aten._unsafe_view.default, torch.ops.aten.expand.default])
217
+ def view_ops_impl(func, types, args, kwargs):
218
+ unwrapped_args = tree_map(unwrap, args)
219
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
220
+ assert len(unwrapped_kwargs) == 0
221
+ assert len(unwrapped_args) == 2, f"args: {unwrapped_args}"
222
+ input_size = unwrapped_args[0].size()
223
+ bigger_size = list(input_size[:1]) + unwrapped_args[1]
224
+ return wrap(func(unwrapped_args[0], bigger_size))
225
+
226
+
227
+ @implements(torch.ops.aten.view.default)
228
+ def view_impl(func, types, args, kwargs):
229
+ unwrapped_args = tree_map(unwrap, args)
230
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
231
+ assert len(unwrapped_kwargs) == 0
232
+ assert len(unwrapped_args) == 2, f"args: {unwrapped_args}"
233
+ input_size = unwrapped_args[0].size()
234
+ bigger_size = list(input_size[:1]) + unwrapped_args[1]
235
+ if unwrapped_args[0].size() == tuple(bigger_size):
236
+ return wrap(args[0].elems)
237
+ return wrap(unwrapped_args[0].reshape(bigger_size))
238
+
239
+
240
+ @implements([torch.ops.aten.mm.default, torch.ops.aten.bmm.default])
241
+ def mm_ops_impl(func, types, args, kwargs):
242
+ unwrapped_args = tree_map(unwrap, args)
243
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
244
+ assert len(unwrapped_kwargs) == 0
245
+ assert len(unwrapped_args) == 2, f"args: {unwrapped_args}"
246
+ return wrap(torch.matmul(*unwrapped_args))
247
+
248
+
249
+ @implements(torch.ops.aten.unsqueeze.default)
250
+ def unsqueeze_impl(func, types, args, kwargs):
251
+ unwrapped_args = tree_map(unwrap, args)
252
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
253
+ assert len(unwrapped_kwargs) == 0
254
+ assert len(unwrapped_args) == 2, f"args: {unwrapped_args}"
255
+ new_i = unwrapped_args[1]
256
+ if new_i >= 0:
257
+ new_i += 1
258
+ return wrap(func(unwrapped_args[0], new_i))
259
+
260
+
261
+ @implements(torch.ops.aten.squeeze.dim)
262
+ def squeeze_impl(func, types, args, kwargs):
263
+ unwrapped_args = tree_map(unwrap, args)
264
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
265
+ assert len(unwrapped_kwargs) == 0
266
+ assert len(unwrapped_args) == 2, f"args: {unwrapped_args}"
267
+ new_i = unwrapped_args[1]
268
+ if new_i >= 0:
269
+ new_i += 1
270
+ return wrap(func(unwrapped_args[0], new_i))
271
+
272
+
273
+ @implements(torch.ops.aten.addmm.default)
274
+ def addmm_impl(func, types, args, kwargs):
275
+ unwrapped_args = tree_map(unwrap, args)
276
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
277
+ assert len(unwrapped_kwargs) == 0
278
+ assert len(unwrapped_args) == 3, f"args: {unwrapped_args}"
279
+ return wrap(torch.matmul(unwrapped_args[1], unwrapped_args[2]) + unwrapped_args[0])
280
+
281
+
282
+ @implements(torch.ops.aten.convolution.default)
283
+ def convolution_impl(func, types, args, kwargs):
284
+ unwrapped_args = tree_map(unwrap, args)
285
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
286
+ assert len(unwrapped_kwargs) == 0
287
+ assert len(unwrapped_args) == 9, f"args: {unwrapped_args}"
288
+ a = unwrapped_args[0]
289
+ a = unwrapped_args[0].flatten(0, 1)
290
+ # TODO: It's scary that this .contiguous seems necessary, but I we're below composite conv
291
+ # which might expected contiguous output
292
+ resa = func(*((a,) + unwrapped_args[1:])).contiguous()
293
+ resb = resa.view(
294
+ (unwrapped_args[0].size(0), unwrapped_args[0].size(1)) + resa.size()[1:]
295
+ )
296
+ return wrap(resb)
297
+
298
+
299
+ @implements(torch.ops.aten.upsample_bilinear2d.default)
300
+ def upsample_bilinear2d_impl(func, types, args, kwargs):
301
+ unwrapped_args = tree_map(unwrap, args)
302
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
303
+ assert len(unwrapped_kwargs) == 0
304
+ assert len(unwrapped_args) == 3, f"args: {unwrapped_args}"
305
+ a = unwrapped_args[0]
306
+ a = unwrapped_args[0].flatten(0, 1)
307
+ # NOTE: It's scary that this .contiguous seems necessary, but we're below composite upsample
308
+ # which might expected contiguous output
309
+ resa = func(*((a,) + unwrapped_args[1:])).contiguous()
310
+ resb = resa.view(
311
+ (unwrapped_args[0].size(0), unwrapped_args[0].size(1)) + resa.size()[1:]
312
+ )
313
+ return wrap(resb)
314
+
315
+
316
+ @implements(torch.ops.aten.transpose.int)
317
+ def transpose_impl(func, types, args, kwargs):
318
+ unwrapped_args = tree_map(unwrap, args)
319
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
320
+ assert len(unwrapped_kwargs) == 0
321
+ assert len(unwrapped_args) == 3, f"args: {unwrapped_args}"
322
+ dim = unwrapped_args[0].dim()
323
+ return wrap(
324
+ func(
325
+ unwrapped_args[0],
326
+ wrap_dim(unwrapped_args[1], dim - 1) + 1,
327
+ wrap_dim(unwrapped_args[2], dim - 1) + 1,
328
+ )
329
+ )
330
+
331
+
332
+ @implements(torch.ops.aten.unbind.int)
333
+ def unbind_impl(func, types, args, kwargs):
334
+ unwrapped_args = tree_map(unwrap, args)
335
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
336
+ assert len(unwrapped_kwargs) == 0
337
+ assert len(unwrapped_args) == 2, f"args: {unwrapped_args}"
338
+ dim = unwrapped_args[0].dim()
339
+ return wrap(func(unwrapped_args[0], wrap_dim(unwrapped_args[1], dim - 1) + 1))
340
+
341
+
342
+ @implements(torch.ops.aten.permute.default)
343
+ def permute_impl(func, types, args, kwargs):
344
+ unwrapped_args = tree_map(unwrap, args)
345
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
346
+ assert len(unwrapped_kwargs) == 0
347
+ assert len(unwrapped_args) == 2, f"args: {unwrapped_args}"
348
+ dim = unwrapped_args[0].dim()
349
+ return wrap(
350
+ func(
351
+ unwrapped_args[0],
352
+ ([0] + [wrap_dim(u, dim - 1) + 1 for u in unwrapped_args[1]]),
353
+ )
354
+ )
355
+
356
+
357
+ @implements(torch.ops.aten._scaled_dot_product_efficient_attention.default)
358
+ def _scaled_dot_product_efficient_attention_impl(func, types, args, kwargs):
359
+ unwrapped_args = tree_map(unwrap, args)
360
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
361
+ assert len(args) == 5
362
+ if all(isinstance(a, MapTensor) for a in args[:3]):
363
+ # assert len(unwrapped_kwargs) == 0
364
+ assert len(unwrapped_args) == 5, f"args: {unwrapped_args}"
365
+ assert unwrapped_args[0].dim() == 5
366
+ assert unwrapped_args[1].dim() == 5
367
+ assert unwrapped_args[2].dim() == 5
368
+ sdpa_res = wrap(
369
+ func(
370
+ unwrapped_args[0].flatten(0, 1),
371
+ unwrapped_args[1].flatten(0, 1),
372
+ unwrapped_args[2].flatten(0, 1),
373
+ unwrapped_args[3],
374
+ unwrapped_args[4],
375
+ **unwrapped_kwargs,
376
+ )
377
+ )
378
+ return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:]
379
+ if isinstance(args[0], MapTensor) and not any(
380
+ isinstance(a, MapTensor) for a in args[1:]
381
+ ):
382
+ # assert len(unwrapped_kwargs) == 0
383
+ assert len(unwrapped_args) == 5, f"args: {unwrapped_args}"
384
+ assert unwrapped_args[0].dim() == 5
385
+ assert unwrapped_args[1].dim() == 4
386
+ assert unwrapped_args[2].dim() == 4
387
+ a0 = unwrapped_args[0]
388
+ a1_size = unwrapped_args[1].size()
389
+ a1 = unwrapped_args[1].unsqueeze(0).expand((a0.size(0),) + a1_size)
390
+ a2 = unwrapped_args[2].unsqueeze(0).expand((a0.size(0),) + a1_size)
391
+ sdpa_res = wrap(
392
+ func(
393
+ a0.flatten(0, 1),
394
+ a1.flatten(0, 1),
395
+ a2.flatten(0, 1),
396
+ unwrapped_args[3],
397
+ unwrapped_args[4],
398
+ **unwrapped_kwargs,
399
+ )
400
+ )
401
+ return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:]
402
+ if (
403
+ (not isinstance(args[0], MapTensor))
404
+ and isinstance(args[1], MapTensor)
405
+ and (not isinstance(args[2], MapTensor))
406
+ ):
407
+ assert len(unwrapped_kwargs) == 0
408
+ assert len(unwrapped_args) == 5, f"args: {unwrapped_args}"
409
+ assert unwrapped_args[0].dim() == 4
410
+ assert unwrapped_args[1].dim() == 5
411
+ assert unwrapped_args[2].dim() == 4
412
+ a1_size = unwrapped_args[1].size()
413
+ a0 = (
414
+ unwrapped_args[0]
415
+ .unsqueeze(0)
416
+ .expand((a1_size[0],) + unwrapped_args[0].size()[1:])
417
+ )
418
+ a2 = (
419
+ unwrapped_args[2]
420
+ .unsqueeze(0)
421
+ .expand((a1_size[0],) + unwrapped_args[2].size()[1:])
422
+ )
423
+ sdpa_res = wrap(
424
+ func(
425
+ a0.flatten(0, 1),
426
+ a1.flatten(0, 1),
427
+ a2.flatten(0, 1),
428
+ unwrapped_args[3],
429
+ unwrapped_args[4],
430
+ )
431
+ )
432
+ return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:]
433
+ if (
434
+ (not isinstance(args[0], MapTensor))
435
+ and isinstance(args[1], MapTensor)
436
+ and isinstance(args[2], MapTensor)
437
+ ):
438
+ # assert len(unwrapped_kwargs) == 0
439
+ assert len(unwrapped_args) == 5, f"args: {unwrapped_args}"
440
+ assert unwrapped_args[0].dim() == 4
441
+ assert unwrapped_args[1].dim() == 5
442
+ assert unwrapped_args[2].dim() == 5
443
+ a0_size = unwrapped_args[0].size()
444
+ a1_size = unwrapped_args[1].size()
445
+ a0 = unwrapped_args[0].unsqueeze(0).expand((a1_size[0],) + a0_size)
446
+ a1 = unwrapped_args[1]
447
+ a2 = unwrapped_args[2]
448
+ sdpa_res = wrap(
449
+ func(
450
+ a0.flatten(0, 1),
451
+ a1.flatten(0, 1),
452
+ a2.flatten(0, 1),
453
+ unwrapped_args[3],
454
+ unwrapped_args[4],
455
+ **unwrapped_kwargs,
456
+ )
457
+ )
458
+ return (wrap(sdpa_res[0].view((a1_size[0],) + a0_size)),) + sdpa_res[1:]
459
+ return NotImplemented
460
+
461
+
462
+ @implements(torch.ops.aten._scaled_dot_product_flash_attention.default)
463
+ def _scaled_dot_product_flash_attention_impl(func, types, args, kwargs):
464
+ unwrapped_args = tree_map(unwrap, args)
465
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
466
+ assert len(args) == 3
467
+ assert len(unwrapped_kwargs) == 1
468
+ assert len(unwrapped_args) == 3, f"args: {unwrapped_args}"
469
+ if all(isinstance(a, MapTensor) for a in args[:3]):
470
+ assert unwrapped_args[0].dim() == 5
471
+ assert unwrapped_args[1].dim() == 5
472
+ assert unwrapped_args[2].dim() == 5
473
+ sdpa_res = wrap(
474
+ func(
475
+ unwrapped_args[0].flatten(0, 1),
476
+ unwrapped_args[1].flatten(0, 1),
477
+ unwrapped_args[2].flatten(0, 1),
478
+ **unwrapped_kwargs,
479
+ )
480
+ )
481
+ return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:]
482
+ if isinstance(args[0], MapTensor) and not any(
483
+ isinstance(a, MapTensor) for a in args[1:]
484
+ ):
485
+ assert unwrapped_args[0].dim() == 5
486
+ assert unwrapped_args[1].dim() == 4
487
+ assert unwrapped_args[2].dim() == 4
488
+ a0 = unwrapped_args[0]
489
+ a1_size = unwrapped_args[1].size()
490
+ a1 = unwrapped_args[1].unsqueeze(0).expand((a0.size(0),) + a1_size)
491
+ a2 = unwrapped_args[2].unsqueeze(0).expand((a0.size(0),) + a1_size)
492
+ sdpa_res = wrap(
493
+ func(
494
+ a0.flatten(0, 1), a1.flatten(0, 1), a2.flatten(0, 1), **unwrapped_kwargs
495
+ )
496
+ )
497
+ return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:]
498
+ if (
499
+ (not isinstance(args[0], MapTensor))
500
+ and isinstance(args[1], MapTensor)
501
+ and (not isinstance(args[2], MapTensor))
502
+ ):
503
+ assert unwrapped_args[0].dim() == 4
504
+ assert unwrapped_args[1].dim() == 5
505
+ assert unwrapped_args[2].dim() == 4
506
+ a1_size = unwrapped_args[1].size()
507
+ a0 = (
508
+ unwrapped_args[0]
509
+ .unsqueeze(0)
510
+ .expand((a1_size[0],) + unwrapped_args[0].size()[1:])
511
+ )
512
+ a2 = (
513
+ unwrapped_args[2]
514
+ .unsqueeze(0)
515
+ .expand((a1_size[0],) + unwrapped_args[2].size()[1:])
516
+ )
517
+ sdpa_res = wrap(
518
+ func(
519
+ a0.flatten(0, 1), a1.flatten(0, 1), a2.flatten(0, 1), **unwrapped_kwargs
520
+ )
521
+ )
522
+ return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:]
523
+ if (
524
+ (not isinstance(args[0], MapTensor))
525
+ and isinstance(args[1], MapTensor)
526
+ and isinstance(args[2], MapTensor)
527
+ ):
528
+ assert unwrapped_args[0].dim() == 4
529
+ assert unwrapped_args[1].dim() == 5
530
+ assert unwrapped_args[2].dim() == 5
531
+ a0_size = unwrapped_args[0].size()
532
+ a1_size = unwrapped_args[1].size()
533
+ a0 = unwrapped_args[0].unsqueeze(0).expand((a1_size[0],) + a0_size)
534
+ a1 = unwrapped_args[1]
535
+ a2 = unwrapped_args[2]
536
+ sdpa_res = wrap(
537
+ func(
538
+ a0.flatten(0, 1), a1.flatten(0, 1), a2.flatten(0, 1), **unwrapped_kwargs
539
+ )
540
+ )
541
+ return (wrap(sdpa_res[0].view((a1_size[0],) + a0_size)),) + sdpa_res[1:]
542
+ return NotImplemented
543
+
544
+
545
+ # torch.ops.aten._unsafe_index.Tensor is only needed by inductor for compile
546
+ @implements([torch.ops.aten._unsafe_index.Tensor, torch.ops.aten.index.Tensor])
547
+ def index_ops_impl(func, types, args, kwargs):
548
+ unwrapped_args = tree_map(unwrap, args)
549
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
550
+ assert len(unwrapped_kwargs) == 0
551
+ assert len(unwrapped_args) == 2, f"args: {unwrapped_args}"
552
+ # if len(args[1]) == 1 and isinstance(args[1][0], MapTensor) and isinstance(args[0], MapTensor):
553
+ # return wrap(func(*unwrapped_args))
554
+ if (
555
+ len(args[1]) == 1
556
+ and isinstance(args[1][0], MapTensor)
557
+ and not isinstance(args[0], MapTensor)
558
+ ):
559
+ tensors = [
560
+ func(args[0], [args[1][0].elems[i]]) for i in range(len(args[1][0].elems))
561
+ ]
562
+ values = torch.cat(tensors)
563
+ lengths = torch.tensor([0] + [t.size(0) for t in tensors], pin_memory=True).to(
564
+ values.device, non_blocking=True
565
+ )
566
+ offsets = torch.cumsum(lengths, dim=0)
567
+ nt = nested_view_from_values_offsets(values, offsets)
568
+ assert nt.layout == torch.jagged
569
+ return wrap(nt)
570
+ if (
571
+ isinstance(args[0], MapTensor)
572
+ and not isinstance(args[1][0], MapTensor)
573
+ and len(args[1]) == 1
574
+ ):
575
+ return wrap(func(args[0].elems, [args[1][0].unsqueeze(0)]))
576
+ if (
577
+ isinstance(args[0], MapTensor)
578
+ and not isinstance(args[1][0], MapTensor)
579
+ and isinstance(args[1][1], MapTensor)
580
+ and len(args[1]) == 2
581
+ ):
582
+ res = []
583
+ for a0, a11 in zip(args[0].elems.unbind(), args[1][1].elems.unbind()):
584
+ res.append(func(a0, [args[1][0], a11]))
585
+ return wrap(torch.stack(res))
586
+ if (
587
+ isinstance(args[0], MapTensor)
588
+ and isinstance(args[1][0], MapTensor)
589
+ and len(args[1]) == 1
590
+ ):
591
+ tensors = [
592
+ func(args[0].elems[i], [args[1][0].elems[i]])
593
+ for i in range(len(args[0].elems))
594
+ ]
595
+ values = torch.cat(tensors)
596
+ lengths = torch.tensor([0] + [t.size(0) for t in tensors], pin_memory=True).to(
597
+ values.device, non_blocking=True
598
+ )
599
+ offsets = torch.cumsum(lengths, dim=0)
600
+ nt = nested_view_from_values_offsets(values, offsets)
601
+ assert nt.layout == torch.jagged
602
+ return wrap(nt)
603
+ a = unwrapped_args[0]
604
+ a = unwrapped_args[0].flatten(0, 1)
605
+ resa = func(a, args[1])
606
+ resb = resa.view(
607
+ (unwrapped_args[0].size(0), unwrapped_args[0].size(1)) + resa.size()[1:]
608
+ )
609
+ return wrap(resb)
610
+
611
+
612
+ # Prims
613
+ @implements(torch.ops.aten.dim.default)
614
+ def dim_impl(func, types, args, kwargs):
615
+ assert len(args) == 1
616
+ assert len(kwargs) == 0
617
+ ret_dim = func(args[0].elems) - 1
618
+ assert ret_dim >= 0
619
+ return ret_dim
620
+
621
+
622
+ @implements(torch.ops.aten.sym_size.default)
623
+ def sym_impl(func, types, args, kwargs):
624
+ assert len(args) == 1
625
+ assert len(kwargs) == 0
626
+ elems_size = func(args[0].elems)
627
+ assert len(elems_size) > 0
628
+ return elems_size[1:]
629
+
630
+
631
+ @implements(torch.ops.aten.is_contiguous.default)
632
+ def is_contiguous_impl(func, types, args, kwargs):
633
+ assert len(args) == 1
634
+ assert len(kwargs) == 0
635
+ return func(args[0].elems)
636
+
637
+
638
+ @implements(
639
+ [
640
+ torch.ops.aten.clamp.default,
641
+ torch.ops.aten.clone.default,
642
+ torch.ops.aten.cos.default,
643
+ torch.ops.aten.div.Tensor,
644
+ torch.ops.aten.eq.Scalar,
645
+ torch.ops.aten.gelu.default,
646
+ torch.ops.aten.mul.Tensor,
647
+ torch.ops.aten.pow.Tensor_Scalar,
648
+ torch.ops.aten.relu.default,
649
+ torch.ops.aten.sigmoid.default,
650
+ torch.ops.aten.sin.default,
651
+ torch.ops.aten.sqrt.default,
652
+ torch.ops.aten.sub.Tensor,
653
+ torch.ops.aten.unbind.int,
654
+ torch.ops.aten.where.self,
655
+ torch.ops.aten.zeros_like.default,
656
+ torch.ops.aten._to_copy.default,
657
+ torch.ops.aten.gt.Scalar,
658
+ torch.ops.aten.ge.Scalar,
659
+ torch.ops.aten.bitwise_not.default,
660
+ torch.ops.aten.lt.Tensor,
661
+ torch.ops.aten.bitwise_or.Tensor,
662
+ torch.ops.aten.eq.Tensor,
663
+ torch.ops.aten.abs.default,
664
+ torch.ops.aten.ne.Scalar,
665
+ torch.ops.aten.le.Tensor,
666
+ torch.ops.aten.view_as_complex.default,
667
+ torch.ops.aten.view_as_real.default,
668
+ torch.ops.aten.neg.default,
669
+ torch.ops.aten.le.Scalar,
670
+ torch.ops.aten.rsub.Scalar,
671
+ # Sketchy new in place ops
672
+ torch.ops.aten.bitwise_and_.Tensor,
673
+ torch.ops.aten.bitwise_or_.Tensor,
674
+ torch.ops.aten.le.Tensor,
675
+ torch.ops.aten.logical_and.default,
676
+ # in place ops
677
+ torch.ops.aten.add_.Tensor,
678
+ torch.ops.aten.copy_.default,
679
+ # Prims
680
+ torch.ops.prim.layout.default,
681
+ ]
682
+ )
683
+ def forwardables_impl(func, types, args, kwargs):
684
+ unwrapped_args = tree_map(unwrap, args)
685
+ unwrapped_kwargs = tree_map(unwrap, kwargs)
686
+ return wrap(func(*unwrapped_args, **unwrapped_kwargs))
687
+
688
+
689
+ def run_invariant_test(res, func, args, kwargs):
690
+ # Compares 0th element of list of results with
691
+ # func applied to 0th arg and kwarg.
692
+ # Rough test to maintain per-op accuracy.
693
+ if isinstance(res, torch.Tensor):
694
+ unwrapped_args_0 = tree_map(lambda x: unwrap_i(x, 0), args)
695
+ unwrapped_kwargs_0 = tree_map(lambda x: unwrap_i(x, 0), kwargs)
696
+ if func == torch.ops.aten.view.default:
697
+ res_0 = torch.ops.aten.reshape.default(
698
+ *unwrapped_args_0, **unwrapped_kwargs_0
699
+ )
700
+ else:
701
+ res_0 = func(*unwrapped_args_0, **unwrapped_kwargs_0)
702
+ # TODO: Extend this all elems not just elems[0]
703
+ if res.elems[0].size() != res_0.size():
704
+ import pdb
705
+
706
+ pdb.set_trace()
707
+ if not torch.allclose(res.elems[0], res_0, atol=1e-3, rtol=1e-3):
708
+ import pdb
709
+
710
+ pdb.set_trace()
711
+ else:
712
+ pass
713
+ # print("res got type: ", type(res))
714
+ # import pdb; pdb.set_trace()
715
+ return res
716
+
717
+
718
+ class MapTensor(torch.Tensor):
719
+ @staticmethod
720
+ def __new__(cls, elems):
721
+ # print("elems.layout: ", elems.layout)
722
+ return torch.Tensor._make_wrapper_subclass(
723
+ cls,
724
+ elems.shape[1:],
725
+ dtype=elems.dtype,
726
+ device=elems.device,
727
+ layout=elems.layout,
728
+ dispatch_layout=True,
729
+ dispatch_sizes_strides_policy=(
730
+ "sizes" if elems.layout == torch.jagged else None
731
+ ),
732
+ storage_size=(
733
+ elems._values.untyped_storage().size()
734
+ if elems.layout == torch.jagged
735
+ else None
736
+ ),
737
+ )
738
+
739
+ def __init__(self, elems):
740
+ self.elems = elems
741
+
742
+ @classmethod
743
+ def __torch_dispatch__(cls, func, types, args, kwargs=None):
744
+ if func in MAP_TENSOR_ATEN_OP_TABLE:
745
+ res = MAP_TENSOR_ATEN_OP_TABLE[func](func, types, args, kwargs)
746
+ # run_invariant_test(res, func, args, kwargs)
747
+ return res
748
+ return NotImplemented
749
+
750
+ @classmethod
751
+ def __torch_function__(cls, func, types, args=(), kwargs=None):
752
+ if kwargs is None:
753
+ kwargs = {}
754
+ with torch._C.DisableTorchFunctionSubclass():
755
+ return func(*args, **kwargs)
756
+
757
+ # flatten/unflatten is needed for compile
758
+ def __tensor_flatten__(self):
759
+ ctx = {}
760
+ inner_tensors = ["elems"]
761
+ return inner_tensors, ctx
762
+
763
+ @staticmethod
764
+ def __tensor_unflatten__(inner_tensors: Dict, meta, outer_size, outer_stride):
765
+ # inner tensors: _values, _offsets, [_lengths], [_min_seqlen], [_max_seqlen]
766
+ assert len(inner_tensors) == 1, f"{inner_tensors}"
767
+ elems = inner_tensors["elems"]
768
+
769
+ return MapTensor(elems)
770
+
771
+ def __repr__(self):
772
+ return f"MapTensor({self.elems.size()})"
773
+
774
+ def pin_memory(self):
775
+ elems = self.elems.pin_memory()
776
+ return wrap(elems)
777
+
778
+
779
+ # ts is a higher dim Tensor
780
+ def to_map_tensor(ts: torch.Tensor):
781
+ return MapTensor(ts)
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/hieradet.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+ from functools import partial
9
+ from typing import List, Tuple, Union
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+ from iopath.common.file_io import g_pathmgr
15
+
16
+ from torchao._models.sam2.modeling.backbones.utils import (
17
+ PatchEmbed,
18
+ window_partition,
19
+ window_unpartition,
20
+ )
21
+ from torchao._models.sam2.modeling.sam2_utils import MLP, DropPath
22
+
23
+
24
+ def do_pool(x: torch.Tensor, pool: nn.Module, norm: nn.Module = None) -> torch.Tensor:
25
+ if pool is None:
26
+ return x
27
+ # (B, H, W, C) -> (B, C, H, W)
28
+ x = x.permute(0, 3, 1, 2)
29
+ x = pool(x)
30
+ # (B, C, H', W') -> (B, H', W', C)
31
+ x = x.permute(0, 2, 3, 1)
32
+ if norm:
33
+ x = norm(x)
34
+
35
+ return x
36
+
37
+
38
+ class MultiScaleAttention(nn.Module):
39
+ def __init__(
40
+ self,
41
+ dim: int,
42
+ dim_out: int,
43
+ num_heads: int,
44
+ q_pool: nn.Module = None,
45
+ ):
46
+ super().__init__()
47
+
48
+ self.dim = dim
49
+ self.dim_out = dim_out
50
+ self.num_heads = num_heads
51
+ self.q_pool = q_pool
52
+ self.qkv = nn.Linear(dim, dim_out * 3)
53
+ self.proj = nn.Linear(dim_out, dim_out)
54
+
55
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
56
+ B, H, W, _ = x.shape
57
+ # qkv with shape (B, H * W, 3, nHead, C)
58
+ qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1)
59
+ # q, k, v with shape (B, H * W, nheads, C)
60
+ q, k, v = torch.unbind(qkv, 2)
61
+
62
+ # Q pooling (for downsample at stage changes)
63
+ if self.q_pool:
64
+ q = do_pool(q.reshape(B, H, W, -1), self.q_pool)
65
+ H, W = q.shape[1:3] # downsampled shape
66
+ q = q.reshape(B, H * W, self.num_heads, -1)
67
+
68
+ # TODO: This fails on batch sizes bigger than 2^16 - 1
69
+ # Torch's SDPA expects [B, nheads, H*W, C] so we transpose
70
+ if q.size(0) > 65535:
71
+ num_chunks = (q.size(0) + 65535) // 65535
72
+ q_chunks = q.chunk(num_chunks)
73
+ k_chunks = k.chunk(num_chunks)
74
+ v_chunks = v.chunk(num_chunks)
75
+ x_chunks = []
76
+ for qi, ki, vi in zip(q_chunks, k_chunks, v_chunks):
77
+ xi = F.scaled_dot_product_attention(
78
+ qi.transpose(1, 2),
79
+ ki.transpose(1, 2),
80
+ vi.transpose(1, 2),
81
+ )
82
+ x_chunks.append(xi)
83
+ x = torch.cat(x_chunks)
84
+ else:
85
+ x = F.scaled_dot_product_attention(
86
+ q.transpose(1, 2),
87
+ k.transpose(1, 2),
88
+ v.transpose(1, 2),
89
+ )
90
+ # Transpose back
91
+ x = x.transpose(1, 2)
92
+ x = x.reshape(B, H, W, -1)
93
+
94
+ x = self.proj(x)
95
+
96
+ return x
97
+
98
+
99
+ class MultiScaleBlock(nn.Module):
100
+ def __init__(
101
+ self,
102
+ dim: int,
103
+ dim_out: int,
104
+ num_heads: int,
105
+ mlp_ratio: float = 4.0,
106
+ drop_path: float = 0.0,
107
+ norm_layer: Union[nn.Module, str] = "LayerNorm",
108
+ q_stride: Tuple[int, int] = None,
109
+ act_layer: nn.Module = nn.GELU,
110
+ window_size: int = 0,
111
+ ):
112
+ super().__init__()
113
+
114
+ if isinstance(norm_layer, str):
115
+ norm_layer = partial(getattr(nn, norm_layer), eps=1e-6)
116
+
117
+ self.dim = dim
118
+ self.dim_out = dim_out
119
+ self.norm1 = norm_layer(dim)
120
+
121
+ self.window_size = window_size
122
+
123
+ self.pool, self.q_stride = None, q_stride
124
+ if self.q_stride:
125
+ self.pool = nn.MaxPool2d(
126
+ kernel_size=q_stride, stride=q_stride, ceil_mode=False
127
+ )
128
+
129
+ self.attn = MultiScaleAttention(
130
+ dim,
131
+ dim_out,
132
+ num_heads=num_heads,
133
+ q_pool=self.pool,
134
+ )
135
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
136
+
137
+ self.norm2 = norm_layer(dim_out)
138
+ self.mlp = MLP(
139
+ dim_out,
140
+ int(dim_out * mlp_ratio),
141
+ dim_out,
142
+ num_layers=2,
143
+ activation=act_layer,
144
+ )
145
+
146
+ if dim != dim_out:
147
+ self.proj = nn.Linear(dim, dim_out)
148
+
149
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
150
+ shortcut = x # B, H, W, C
151
+ x = self.norm1(x)
152
+
153
+ # Skip connection
154
+ if self.dim != self.dim_out:
155
+ shortcut = do_pool(self.proj(x), self.pool)
156
+
157
+ # Window partition
158
+ window_size = self.window_size
159
+ if window_size > 0:
160
+ H, W = x.shape[1], x.shape[2]
161
+ x, pad_hw = window_partition(x, window_size)
162
+
163
+ # Window Attention + Q Pooling (if stage change)
164
+ x = self.attn(x)
165
+ if self.q_stride:
166
+ # Shapes have changed due to Q pooling
167
+ window_size = self.window_size // self.q_stride[0]
168
+ H, W = shortcut.shape[1:3]
169
+
170
+ pad_h = (window_size - H % window_size) % window_size
171
+ pad_w = (window_size - W % window_size) % window_size
172
+ pad_hw = (H + pad_h, W + pad_w)
173
+
174
+ # Reverse window partition
175
+ if self.window_size > 0:
176
+ x = window_unpartition(x, window_size, pad_hw, (H, W))
177
+
178
+ x = shortcut + self.drop_path(x)
179
+ # MLP
180
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
181
+ return x
182
+
183
+
184
+ class Hiera(nn.Module):
185
+ """
186
+ Reference: https://arxiv.org/abs/2306.00989
187
+ """
188
+
189
+ def __init__(
190
+ self,
191
+ embed_dim: int = 96, # initial embed dim
192
+ num_heads: int = 1, # initial number of heads
193
+ drop_path_rate: float = 0.0, # stochastic depth
194
+ q_pool: int = 3, # number of q_pool stages
195
+ q_stride: Tuple[int, int] = (2, 2), # downsample stride bet. stages
196
+ stages: Tuple[int, ...] = (2, 3, 16, 3), # blocks per stage
197
+ dim_mul: float = 2.0, # dim_mul factor at stage shift
198
+ head_mul: float = 2.0, # head_mul factor at stage shift
199
+ window_pos_embed_bkg_spatial_size: Tuple[int, int] = (14, 14),
200
+ # window size per stage, when not using global att.
201
+ window_spec: Tuple[int, ...] = (
202
+ 8,
203
+ 4,
204
+ 14,
205
+ 7,
206
+ ),
207
+ # global attn in these blocks
208
+ global_att_blocks: Tuple[int, ...] = (
209
+ 12,
210
+ 16,
211
+ 20,
212
+ ),
213
+ weights_path=None,
214
+ return_interm_layers=True, # return feats from every stage
215
+ ):
216
+ super().__init__()
217
+
218
+ assert len(stages) == len(window_spec)
219
+ self.window_spec = window_spec
220
+
221
+ depth = sum(stages)
222
+ self.q_stride = q_stride
223
+ self.stage_ends = [sum(stages[:i]) - 1 for i in range(1, len(stages) + 1)]
224
+ assert 0 <= q_pool <= len(self.stage_ends[:-1])
225
+ self.q_pool_blocks = [x + 1 for x in self.stage_ends[:-1]][:q_pool]
226
+ self.return_interm_layers = return_interm_layers
227
+
228
+ self.patch_embed = PatchEmbed(
229
+ embed_dim=embed_dim,
230
+ )
231
+ # Which blocks have global att?
232
+ self.global_att_blocks = global_att_blocks
233
+
234
+ # Windowed positional embedding (https://arxiv.org/abs/2311.05613)
235
+ self.window_pos_embed_bkg_spatial_size = window_pos_embed_bkg_spatial_size
236
+ self.pos_embed = nn.Parameter(
237
+ torch.zeros(1, embed_dim, *self.window_pos_embed_bkg_spatial_size)
238
+ )
239
+ self.pos_embed_window = nn.Parameter(
240
+ torch.zeros(1, embed_dim, self.window_spec[0], self.window_spec[0])
241
+ )
242
+
243
+ dpr = [
244
+ x.item() for x in torch.linspace(0, drop_path_rate, depth)
245
+ ] # stochastic depth decay rule
246
+
247
+ cur_stage = 1
248
+ self.blocks = nn.ModuleList()
249
+
250
+ for i in range(depth):
251
+ dim_out = embed_dim
252
+ # lags by a block, so first block of
253
+ # next stage uses an initial window size
254
+ # of previous stage and final window size of current stage
255
+ window_size = self.window_spec[cur_stage - 1]
256
+
257
+ if self.global_att_blocks is not None:
258
+ window_size = 0 if i in self.global_att_blocks else window_size
259
+
260
+ if i - 1 in self.stage_ends:
261
+ dim_out = int(embed_dim * dim_mul)
262
+ num_heads = int(num_heads * head_mul)
263
+ cur_stage += 1
264
+
265
+ block = MultiScaleBlock(
266
+ dim=embed_dim,
267
+ dim_out=dim_out,
268
+ num_heads=num_heads,
269
+ drop_path=dpr[i],
270
+ q_stride=self.q_stride if i in self.q_pool_blocks else None,
271
+ window_size=window_size,
272
+ )
273
+
274
+ embed_dim = dim_out
275
+ self.blocks.append(block)
276
+
277
+ self.channel_list = (
278
+ [self.blocks[i].dim_out for i in self.stage_ends[::-1]]
279
+ if return_interm_layers
280
+ else [self.blocks[-1].dim_out]
281
+ )
282
+
283
+ if weights_path is not None:
284
+ with g_pathmgr.open(weights_path, "rb") as f:
285
+ chkpt = torch.load(f, map_location="cpu")
286
+ logging.info("loading Hiera", self.load_state_dict(chkpt, strict=False))
287
+
288
+ def _get_pos_embed(self, hw: Tuple[int, int]) -> torch.Tensor:
289
+ h, w = hw
290
+ window_embed = self.pos_embed_window
291
+ pos_embed = F.interpolate(self.pos_embed, size=(h, w), mode="bicubic")
292
+ pos_embed = pos_embed + window_embed.tile(
293
+ [x // y for x, y in zip(pos_embed.shape, window_embed.shape)]
294
+ )
295
+ pos_embed = pos_embed.permute(0, 2, 3, 1)
296
+ return pos_embed
297
+
298
+ def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
299
+ x = self.patch_embed(x)
300
+ # x: (B, H, W, C)
301
+
302
+ # Add pos embed
303
+ x = x + self._get_pos_embed(x.shape[1:3])
304
+
305
+ outputs = []
306
+ for i, blk in enumerate(self.blocks):
307
+ x = blk(x)
308
+ if (i == self.stage_ends[-1]) or (
309
+ i in self.stage_ends and self.return_interm_layers
310
+ ):
311
+ feats = x.permute(0, 3, 1, 2)
312
+ outputs.append(feats)
313
+
314
+ return outputs
315
+
316
+ def get_layer_id(self, layer_name):
317
+ # https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33
318
+ num_layers = self.get_num_layers()
319
+
320
+ if layer_name.find("rel_pos") != -1:
321
+ return num_layers + 1
322
+ elif layer_name.find("pos_embed") != -1:
323
+ return 0
324
+ elif layer_name.find("patch_embed") != -1:
325
+ return 0
326
+ elif layer_name.find("blocks") != -1:
327
+ return int(layer_name.split("blocks")[1].split(".")[1]) + 1
328
+ else:
329
+ return num_layers + 1
330
+
331
+ def get_num_layers(self) -> int:
332
+ return len(self.blocks)
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/image_encoder.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import List, Optional
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+
13
+
14
+ class ImageEncoder(nn.Module):
15
+ def __init__(
16
+ self,
17
+ trunk: nn.Module,
18
+ neck: nn.Module,
19
+ scalp: int = 0,
20
+ ):
21
+ super().__init__()
22
+ self.trunk = trunk
23
+ self.neck = neck
24
+ self.scalp = scalp
25
+ assert self.trunk.channel_list == self.neck.backbone_channel_list, (
26
+ f"Channel dims of trunk and neck do not match. Trunk: {self.trunk.channel_list}, neck: {self.neck.backbone_channel_list}"
27
+ )
28
+
29
+ def forward(self, sample: torch.Tensor):
30
+ # Forward through backbone
31
+ with torch.autograd.profiler.record_function("self.neck(self.trunk(sample))"):
32
+ from torchao._models.sam2.map_tensor import MapTensor, to_map_tensor
33
+
34
+ if isinstance(sample, MapTensor):
35
+ features, pos = self.neck(self.trunk(sample.elems.flatten(0, 1)))
36
+ features = [to_map_tensor(t.unsqueeze(1)) for t in features]
37
+ pos = [to_map_tensor(t.unsqueeze(1)) for t in pos]
38
+ else:
39
+ features, pos = self.neck(self.trunk(sample))
40
+ if self.scalp > 0:
41
+ # Discard the lowest resolution features
42
+ features, pos = features[: -self.scalp], pos[: -self.scalp]
43
+
44
+ src = features[-1]
45
+ output = {
46
+ "vision_features": src,
47
+ "vision_pos_enc": pos,
48
+ "backbone_fpn": features,
49
+ }
50
+ return output
51
+
52
+
53
+ class FpnNeck(nn.Module):
54
+ """
55
+ A modified variant of Feature Pyramid Network (FPN) neck
56
+ (we remove output conv and also do bicubic interpolation similar to ViT
57
+ pos embed interpolation)
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ position_encoding: nn.Module,
63
+ d_model: int,
64
+ backbone_channel_list: List[int],
65
+ kernel_size: int = 1,
66
+ stride: int = 1,
67
+ padding: int = 0,
68
+ fpn_interp_model: str = "bilinear",
69
+ fuse_type: str = "sum",
70
+ fpn_top_down_levels: Optional[List[int]] = None,
71
+ ):
72
+ """Initialize the neck
73
+ :param trunk: the backbone
74
+ :param position_encoding: the positional encoding to use
75
+ :param d_model: the dimension of the model
76
+ :param neck_norm: the normalization to use
77
+ """
78
+ super().__init__()
79
+ self.position_encoding = position_encoding
80
+ self.convs = nn.ModuleList()
81
+ self.backbone_channel_list = backbone_channel_list
82
+ self.d_model = d_model
83
+ for dim in backbone_channel_list:
84
+ current = nn.Sequential()
85
+ current.add_module(
86
+ "conv",
87
+ nn.Conv2d(
88
+ in_channels=dim,
89
+ out_channels=d_model,
90
+ kernel_size=kernel_size,
91
+ stride=stride,
92
+ padding=padding,
93
+ ),
94
+ )
95
+
96
+ self.convs.append(current)
97
+ self.fpn_interp_model = fpn_interp_model
98
+ assert fuse_type in ["sum", "avg"]
99
+ self.fuse_type = fuse_type
100
+
101
+ # levels to have top-down features in its outputs
102
+ # e.g. if fpn_top_down_levels is [2, 3], then only outputs of level 2 and 3
103
+ # have top-down propagation, while outputs of level 0 and level 1 have only
104
+ # lateral features from the same backbone level.
105
+ if fpn_top_down_levels is None:
106
+ # default is to have top-down features on all levels
107
+ fpn_top_down_levels = range(len(self.convs))
108
+ self.fpn_top_down_levels = list(fpn_top_down_levels)
109
+
110
+ def forward(self, xs: List[torch.Tensor]):
111
+ out = [None] * len(self.convs)
112
+ pos = [None] * len(self.convs)
113
+ assert len(xs) == len(self.convs)
114
+ # fpn forward pass
115
+ # see https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/fpn.py
116
+ prev_features = None
117
+ # forward in top-down order (from low to high resolution)
118
+ n = len(self.convs) - 1
119
+ for i in range(n, -1, -1):
120
+ x = xs[i]
121
+ lateral_features = self.convs[n - i](x)
122
+ if i in self.fpn_top_down_levels and prev_features is not None:
123
+ top_down_features = F.interpolate(
124
+ prev_features.to(dtype=torch.float32),
125
+ scale_factor=2.0,
126
+ mode=self.fpn_interp_model,
127
+ align_corners=(
128
+ None if self.fpn_interp_model == "nearest" else False
129
+ ),
130
+ antialias=False,
131
+ )
132
+ prev_features = lateral_features + top_down_features
133
+ if self.fuse_type == "avg":
134
+ prev_features /= 2
135
+ else:
136
+ prev_features = lateral_features
137
+ x_out = prev_features
138
+ out[i] = x_out
139
+ pos[i] = self.position_encoding(x_out).to(x_out.dtype)
140
+
141
+ return out, pos
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/utils.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ """Some utilities for backbones, in particular for windowing"""
8
+
9
+ from typing import Tuple
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+ import torch.nn.functional as F
14
+
15
+
16
+ def window_partition(x, window_size):
17
+ """
18
+ Partition into non-overlapping windows with padding if needed.
19
+ Args:
20
+ x (tensor): input tokens with [B, H, W, C].
21
+ window_size (int): window size.
22
+ Returns:
23
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
24
+ (Hp, Wp): padded height and width before partition
25
+ """
26
+ B, H, W, C = x.shape
27
+
28
+ pad_h = (window_size - H % window_size) % window_size
29
+ pad_w = (window_size - W % window_size) % window_size
30
+ if pad_h > 0 or pad_w > 0:
31
+ x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
32
+ Hp, Wp = H + pad_h, W + pad_w
33
+
34
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
35
+ windows = (
36
+ x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
37
+ )
38
+ return windows, (Hp, Wp)
39
+
40
+
41
+ def window_unpartition(windows, window_size, pad_hw, hw):
42
+ """
43
+ Window unpartition into original sequences and removing padding.
44
+ Args:
45
+ x (tensor): input tokens with [B * num_windows, window_size, window_size, C].
46
+ window_size (int): window size.
47
+ pad_hw (Tuple): padded height and width (Hp, Wp).
48
+ hw (Tuple): original height and width (H, W) before padding.
49
+ Returns:
50
+ x: unpartitioned sequences with [B, H, W, C].
51
+ """
52
+ Hp, Wp = pad_hw
53
+ H, W = hw
54
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
55
+ x = windows.view(
56
+ B, Hp // window_size, Wp // window_size, window_size, window_size, -1
57
+ )
58
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
59
+
60
+ if Hp > H or Wp > W:
61
+ x = x[:, :H, :W, :].contiguous()
62
+ return x
63
+
64
+
65
+ class PatchEmbed(nn.Module):
66
+ """
67
+ Image to Patch Embedding.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ kernel_size: Tuple[int, ...] = (7, 7),
73
+ stride: Tuple[int, ...] = (4, 4),
74
+ padding: Tuple[int, ...] = (3, 3),
75
+ in_chans: int = 3,
76
+ embed_dim: int = 768,
77
+ ):
78
+ """
79
+ Args:
80
+ kernel_size (Tuple): kernel size of the projection layer.
81
+ stride (Tuple): stride of the projection layer.
82
+ padding (Tuple): padding size of the projection layer.
83
+ in_chans (int): Number of input image channels.
84
+ embed_dim (int): embed_dim (int): Patch embedding dimension.
85
+ """
86
+ super().__init__()
87
+ self.proj = nn.Conv2d(
88
+ in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
89
+ )
90
+
91
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
92
+ x = self.proj(x)
93
+ # B C H W -> B H W C
94
+ x = x.permute(0, 2, 3, 1)
95
+ return x
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/memory_attention.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Optional
8
+
9
+ import torch
10
+ from torch import Tensor, nn
11
+
12
+ from torchao._models.sam2.modeling.sam.transformer import RoPEAttention
13
+ from torchao._models.sam2.modeling.sam2_utils import get_activation_fn, get_clones
14
+
15
+
16
+ class MemoryAttentionLayer(nn.Module):
17
+ def __init__(
18
+ self,
19
+ activation: str,
20
+ cross_attention: nn.Module,
21
+ d_model: int,
22
+ dim_feedforward: int,
23
+ dropout: float,
24
+ pos_enc_at_attn: bool,
25
+ pos_enc_at_cross_attn_keys: bool,
26
+ pos_enc_at_cross_attn_queries: bool,
27
+ self_attention: nn.Module,
28
+ ):
29
+ super().__init__()
30
+ self.d_model = d_model
31
+ self.dim_feedforward = dim_feedforward
32
+ self.dropout_value = dropout
33
+ self.self_attn = self_attention
34
+ self.cross_attn_image = cross_attention
35
+
36
+ # Implementation of Feedforward model
37
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
38
+ self.dropout = nn.Dropout(dropout)
39
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
40
+
41
+ self.norm1 = nn.LayerNorm(d_model)
42
+ self.norm2 = nn.LayerNorm(d_model)
43
+ self.norm3 = nn.LayerNorm(d_model)
44
+ self.dropout1 = nn.Dropout(dropout)
45
+ self.dropout2 = nn.Dropout(dropout)
46
+ self.dropout3 = nn.Dropout(dropout)
47
+
48
+ self.activation_str = activation
49
+ self.activation = get_activation_fn(activation)
50
+
51
+ # Where to add pos enc
52
+ self.pos_enc_at_attn = pos_enc_at_attn
53
+ self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries
54
+ self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys
55
+
56
+ def _forward_sa(self, tgt, query_pos):
57
+ # Self-Attention
58
+ tgt2 = self.norm1(tgt)
59
+ q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2
60
+ tgt2 = self.self_attn(q, k, v=tgt2)
61
+ tgt = tgt + self.dropout1(tgt2)
62
+ return tgt
63
+
64
+ def _forward_ca(self, tgt, memory, query_pos, pos, num_k_exclude_rope=0):
65
+ kwds = {}
66
+ if num_k_exclude_rope > 0:
67
+ assert isinstance(self.cross_attn_image, RoPEAttention)
68
+ kwds = {"num_k_exclude_rope": num_k_exclude_rope}
69
+
70
+ # Cross-Attention
71
+ tgt2 = self.norm2(tgt)
72
+ tgt2 = self.cross_attn_image(
73
+ q=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2,
74
+ k=memory + pos if self.pos_enc_at_cross_attn_keys else memory,
75
+ v=memory,
76
+ **kwds,
77
+ )
78
+ tgt = tgt + self.dropout2(tgt2)
79
+ return tgt
80
+
81
+ def forward(
82
+ self,
83
+ tgt,
84
+ memory,
85
+ pos: Optional[Tensor] = None,
86
+ query_pos: Optional[Tensor] = None,
87
+ num_k_exclude_rope: int = 0,
88
+ ) -> torch.Tensor:
89
+ # Self-Attn, Cross-Attn
90
+ tgt = self._forward_sa(tgt, query_pos)
91
+ tgt = self._forward_ca(tgt, memory, query_pos, pos, num_k_exclude_rope)
92
+ # MLP
93
+ tgt2 = self.norm3(tgt)
94
+ tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2))))
95
+ tgt = tgt + self.dropout3(tgt2)
96
+ return tgt
97
+
98
+
99
+ class MemoryAttention(nn.Module):
100
+ def __init__(
101
+ self,
102
+ d_model: int,
103
+ pos_enc_at_input: bool,
104
+ layer: nn.Module,
105
+ num_layers: int,
106
+ batch_first: bool = True, # Do layers expect batch first input?
107
+ ):
108
+ super().__init__()
109
+ self.d_model = d_model
110
+ self.layers = get_clones(layer, num_layers)
111
+ self.num_layers = num_layers
112
+ self.norm = nn.LayerNorm(d_model)
113
+ self.pos_enc_at_input = pos_enc_at_input
114
+ self.batch_first = batch_first
115
+
116
+ def forward(
117
+ self,
118
+ curr: torch.Tensor, # self-attention inputs
119
+ memory: torch.Tensor, # cross-attention inputs
120
+ curr_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs
121
+ memory_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs
122
+ num_obj_ptr_tokens: int = 0, # number of object pointer *tokens*
123
+ ):
124
+ if isinstance(curr, list):
125
+ assert isinstance(curr_pos, list)
126
+ assert len(curr) == len(curr_pos) == 1
127
+ curr, curr_pos = (
128
+ curr[0],
129
+ curr_pos[0],
130
+ )
131
+
132
+ assert curr.shape[1] == memory.shape[1], (
133
+ "Batch size must be the same for curr and memory"
134
+ )
135
+
136
+ output = curr
137
+ if self.pos_enc_at_input and curr_pos is not None:
138
+ output = output + 0.1 * curr_pos
139
+
140
+ if self.batch_first:
141
+ # Convert to batch first
142
+ output = output.transpose(0, 1)
143
+ curr_pos = curr_pos.transpose(0, 1)
144
+ memory = memory.transpose(0, 1)
145
+ memory_pos = memory_pos.transpose(0, 1)
146
+
147
+ for layer in self.layers:
148
+ kwds = {}
149
+ if isinstance(layer.cross_attn_image, RoPEAttention):
150
+ kwds = {"num_k_exclude_rope": num_obj_ptr_tokens}
151
+
152
+ output = layer(
153
+ tgt=output,
154
+ memory=memory,
155
+ pos=memory_pos,
156
+ query_pos=curr_pos,
157
+ **kwds,
158
+ )
159
+ normed_output = self.norm(output)
160
+
161
+ if self.batch_first:
162
+ # Convert back to seq first
163
+ normed_output = normed_output.transpose(0, 1)
164
+ curr_pos = curr_pos.transpose(0, 1)
165
+
166
+ return normed_output
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/memory_encoder.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from typing import Tuple
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+
14
+ from torchao._models.sam2.modeling.sam2_utils import DropPath, LayerNorm2d, get_clones
15
+
16
+
17
+ class MaskDownSampler(nn.Module):
18
+ """
19
+ Progressively downsample a mask by total_stride, each time by stride.
20
+ Note that LayerNorm is applied per *token*, like in ViT.
21
+
22
+ With each downsample (by a factor stride**2), channel capacity increases by the same factor.
23
+ In the end, we linearly project to embed_dim channels.
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ embed_dim=256,
29
+ kernel_size=4,
30
+ stride=4,
31
+ padding=0,
32
+ total_stride=16,
33
+ activation=nn.GELU,
34
+ ):
35
+ super().__init__()
36
+ num_layers = int(math.log2(total_stride) // math.log2(stride))
37
+ assert stride**num_layers == total_stride
38
+ self.encoder = nn.Sequential()
39
+ mask_in_chans, mask_out_chans = 1, 1
40
+ for _ in range(num_layers):
41
+ mask_out_chans = mask_in_chans * (stride**2)
42
+ self.encoder.append(
43
+ nn.Conv2d(
44
+ mask_in_chans,
45
+ mask_out_chans,
46
+ kernel_size=kernel_size,
47
+ stride=stride,
48
+ padding=padding,
49
+ )
50
+ )
51
+ self.encoder.append(LayerNorm2d(mask_out_chans))
52
+ self.encoder.append(activation())
53
+ mask_in_chans = mask_out_chans
54
+
55
+ self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1))
56
+
57
+ def forward(self, x):
58
+ return self.encoder(x)
59
+
60
+
61
+ # Lightly adapted from ConvNext (https://github.com/facebookresearch/ConvNeXt)
62
+ class CXBlock(nn.Module):
63
+ r"""ConvNeXt Block. There are two equivalent implementations:
64
+ (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W)
65
+ (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back
66
+ We use (2) as we find it slightly faster in PyTorch
67
+
68
+ Args:
69
+ dim (int): Number of input channels.
70
+ drop_path (float): Stochastic depth rate. Default: 0.0
71
+ layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6.
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ dim,
77
+ kernel_size=7,
78
+ padding=3,
79
+ drop_path=0.0,
80
+ layer_scale_init_value=1e-6,
81
+ use_dwconv=True,
82
+ ):
83
+ super().__init__()
84
+ self.dwconv = nn.Conv2d(
85
+ dim,
86
+ dim,
87
+ kernel_size=kernel_size,
88
+ padding=padding,
89
+ groups=dim if use_dwconv else 1,
90
+ ) # depthwise conv
91
+ self.norm = LayerNorm2d(dim, eps=1e-6)
92
+ self.pwconv1 = nn.Linear(
93
+ dim, 4 * dim
94
+ ) # pointwise/1x1 convs, implemented with linear layers
95
+ self.act = nn.GELU()
96
+ self.pwconv2 = nn.Linear(4 * dim, dim)
97
+ self.gamma = (
98
+ nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True)
99
+ if layer_scale_init_value > 0
100
+ else None
101
+ )
102
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
103
+
104
+ def forward(self, x):
105
+ input = x
106
+ x = self.dwconv(x)
107
+ x = self.norm(x)
108
+ x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C)
109
+ x = self.pwconv1(x)
110
+ x = self.act(x)
111
+ x = self.pwconv2(x)
112
+ if self.gamma is not None:
113
+ x = self.gamma * x
114
+ x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W)
115
+
116
+ x = input + self.drop_path(x)
117
+ return x
118
+
119
+
120
+ class Fuser(nn.Module):
121
+ def __init__(self, layer, num_layers, dim=None, input_projection=False):
122
+ super().__init__()
123
+ self.proj = nn.Identity()
124
+ self.layers = get_clones(layer, num_layers)
125
+
126
+ if input_projection:
127
+ assert dim is not None
128
+ self.proj = nn.Conv2d(dim, dim, kernel_size=1)
129
+
130
+ def forward(self, x):
131
+ # normally x: (N, C, H, W)
132
+ x = self.proj(x)
133
+ for layer in self.layers:
134
+ x = layer(x)
135
+ return x
136
+
137
+
138
+ class MemoryEncoder(nn.Module):
139
+ def __init__(
140
+ self,
141
+ out_dim,
142
+ mask_downsampler,
143
+ fuser,
144
+ position_encoding,
145
+ in_dim=256, # in_dim of pix_feats
146
+ ):
147
+ super().__init__()
148
+
149
+ self.mask_downsampler = mask_downsampler
150
+
151
+ self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1)
152
+ self.fuser = fuser
153
+ self.position_encoding = position_encoding
154
+ self.out_proj = nn.Identity()
155
+ if out_dim != in_dim:
156
+ self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1)
157
+
158
+ def forward(
159
+ self,
160
+ pix_feat: torch.Tensor,
161
+ masks: torch.Tensor,
162
+ skip_mask_sigmoid: bool = False,
163
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
164
+ ## Process masks
165
+ # sigmoid, so that less domain shift from gt masks which are bool
166
+ if not skip_mask_sigmoid:
167
+ masks = F.sigmoid(masks)
168
+ masks = self.mask_downsampler(masks)
169
+
170
+ ## Fuse pix_feats and downsampled masks
171
+ # in case the visual features are on CPU, cast them to CUDA
172
+ pix_feat = pix_feat.to(masks.device)
173
+
174
+ x = self.pix_feat_proj(pix_feat)
175
+ x = x + masks
176
+ x = self.fuser(x)
177
+ x = self.out_proj(x)
178
+
179
+ pos = self.position_encoding(x).to(x.dtype)
180
+
181
+ return {"vision_features": x, "vision_pos_enc": [pos]}
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/position_encoding.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from typing import Any, Optional, Tuple
9
+
10
+ import numpy as np
11
+ import torch
12
+ from torch import nn
13
+
14
+
15
+ class PositionEmbeddingSine(nn.Module):
16
+ """
17
+ This is a more standard version of the position embedding, very similar to the one
18
+ used by the Attention Is All You Need paper, generalized to work on images.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ num_pos_feats,
24
+ temperature: int = 10000,
25
+ normalize: bool = True,
26
+ scale: Optional[float] = None,
27
+ ):
28
+ super().__init__()
29
+ assert num_pos_feats % 2 == 0, "Expecting even model width"
30
+ self.num_pos_feats = num_pos_feats // 2
31
+ self.temperature = temperature
32
+ self.normalize = normalize
33
+ if scale is not None and normalize is False:
34
+ raise ValueError("normalize should be True if scale is passed")
35
+ if scale is None:
36
+ scale = 2 * math.pi
37
+ self.scale = scale
38
+
39
+ # self.cache = {}
40
+
41
+ def _encode_xy(self, x, y):
42
+ # The positions are expected to be normalized
43
+ assert len(x) == len(y) and x.ndim == y.ndim == 1
44
+ x_embed = x * self.scale
45
+ y_embed = y * self.scale
46
+
47
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
48
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
49
+
50
+ pos_x = x_embed[:, None] / dim_t
51
+ pos_y = y_embed[:, None] / dim_t
52
+ pos_x = torch.stack(
53
+ (pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2
54
+ ).flatten(1)
55
+ pos_y = torch.stack(
56
+ (pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2
57
+ ).flatten(1)
58
+ return pos_x, pos_y
59
+
60
+ @torch.no_grad()
61
+ def encode_boxes(self, x, y, w, h):
62
+ pos_x, pos_y = self._encode_xy(x, y)
63
+ pos = torch.cat((pos_y, pos_x, h[:, None], w[:, None]), dim=1)
64
+ return pos
65
+
66
+ encode = encode_boxes # Backwards compatibility
67
+
68
+ @torch.no_grad()
69
+ def encode_points(self, x, y, labels):
70
+ (bx, nx), (by, ny), (bl, nl) = x.shape, y.shape, labels.shape
71
+ assert bx == by and nx == ny and bx == bl and nx == nl
72
+ pos_x, pos_y = self._encode_xy(x.flatten(), y.flatten())
73
+ pos_x, pos_y = pos_x.reshape(bx, nx, -1), pos_y.reshape(by, ny, -1)
74
+ pos = torch.cat((pos_y, pos_x, labels[:, :, None]), dim=2)
75
+ return pos
76
+
77
+ @torch.no_grad()
78
+ def forward(self, x: torch.Tensor):
79
+ # cache_key = (x.shape[-2], x.shape[-1])
80
+ # if cache_key in self.cache:
81
+ # return self.cache[cache_key][None].repeat(x.shape[0], 1, 1, 1)
82
+ y_embed = (
83
+ torch.arange(1, x.shape[-2] + 1, dtype=torch.float32, device=x.device)
84
+ .view(1, -1, 1)
85
+ .repeat(x.shape[0], 1, x.shape[-1])
86
+ )
87
+ x_embed = (
88
+ torch.arange(1, x.shape[-1] + 1, dtype=torch.float32, device=x.device)
89
+ .view(1, 1, -1)
90
+ .repeat(x.shape[0], x.shape[-2], 1)
91
+ )
92
+
93
+ if self.normalize:
94
+ eps = 1e-6
95
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
96
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
97
+
98
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
99
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
100
+
101
+ pos_x = x_embed[:, :, :, None] / dim_t
102
+ pos_y = y_embed[:, :, :, None] / dim_t
103
+ pos_x = torch.stack(
104
+ (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4
105
+ ).flatten(3)
106
+ pos_y = torch.stack(
107
+ (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4
108
+ ).flatten(3)
109
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
110
+ # self.cache[cache_key] = pos[0]
111
+ return pos
112
+
113
+
114
+ class PositionEmbeddingRandom(nn.Module):
115
+ """
116
+ Positional encoding using random spatial frequencies.
117
+ """
118
+
119
+ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
120
+ super().__init__()
121
+ if scale is None or scale <= 0.0:
122
+ scale = 1.0
123
+ self.register_buffer(
124
+ "positional_encoding_gaussian_matrix",
125
+ scale * torch.randn((2, num_pos_feats)),
126
+ )
127
+
128
+ def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:
129
+ """Positionally encode points that are normalized to [0,1]."""
130
+ # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
131
+ coords = 2 * coords - 1
132
+ coords = coords @ self.positional_encoding_gaussian_matrix
133
+ coords = 2 * np.pi * coords
134
+ # outputs d_1 x ... x d_n x C shape
135
+ return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
136
+
137
+ def forward(self, size: Tuple[int, int]) -> torch.Tensor:
138
+ """Generate positional encoding for a grid of the specified size."""
139
+ h, w = size
140
+ device: Any = self.positional_encoding_gaussian_matrix.device
141
+ grid = torch.ones((h, w), device=device, dtype=torch.float32)
142
+ y_embed = grid.cumsum(dim=0) - 0.5
143
+ x_embed = grid.cumsum(dim=1) - 0.5
144
+ y_embed = y_embed / h
145
+ x_embed = x_embed / w
146
+
147
+ pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))
148
+ return pe.permute(2, 0, 1) # C x H x W
149
+
150
+ def forward_with_coords(
151
+ self, coords_input: torch.Tensor, image_size: Tuple[int, int]
152
+ ) -> torch.Tensor:
153
+ """Positionally encode points that are not normalized to [0,1]."""
154
+ coords = coords_input.clone()
155
+ coords[:, :, 0] = coords[:, :, 0] / image_size[1]
156
+ coords[:, :, 1] = coords[:, :, 1] / image_size[0]
157
+ return self._pe_encoding(coords.to(torch.float)) # B x N x C
158
+
159
+
160
+ # Rotary Positional Encoding, adapted from:
161
+ # 1. https://github.com/meta-llama/codellama/blob/main/llama/model.py
162
+ # 2. https://github.com/naver-ai/rope-vit
163
+ # 3. https://github.com/lucidrains/rotary-embedding-torch
164
+
165
+
166
+ def init_t_xy(end_x: int, end_y: int, device=None):
167
+ t = torch.arange(end_x * end_y, dtype=torch.float32, device=device)
168
+ t_x = (t % end_x).float()
169
+ t_y = torch.div(t, end_x, rounding_mode="floor").float()
170
+ return t_x, t_y
171
+
172
+
173
+ def compute_axial_cis(
174
+ dim: int, end_x: int, end_y: int, theta: float = 10000.0, device=None
175
+ ):
176
+ freqs_x = 1.0 / (
177
+ theta ** (torch.arange(0, dim, 4, device=device)[: (dim // 4)].float() / dim)
178
+ )
179
+ freqs_y = 1.0 / (
180
+ theta ** (torch.arange(0, dim, 4, device=device)[: (dim // 4)].float() / dim)
181
+ )
182
+
183
+ t_x, t_y = init_t_xy(end_x, end_y, device=device)
184
+ freqs_x = torch.outer(t_x, freqs_x)
185
+ freqs_y = torch.outer(t_y, freqs_y)
186
+ freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x)
187
+ freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y)
188
+ return torch.cat([freqs_cis_x, freqs_cis_y], dim=-1)
189
+
190
+
191
+ def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
192
+ ndim = x.ndim
193
+ assert 0 <= 1 < ndim
194
+ assert freqs_cis.shape == (x.shape[-2], x.shape[-1])
195
+ shape = [d if i >= ndim - 2 else 1 for i, d in enumerate(x.shape)]
196
+ return freqs_cis.view(*shape)
197
+
198
+
199
+ def apply_rotary_enc(
200
+ xq: torch.Tensor,
201
+ xk: torch.Tensor,
202
+ freqs_cis: torch.Tensor,
203
+ repeat_freqs_k: bool = False,
204
+ ):
205
+ xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
206
+ xk_ = (
207
+ torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
208
+ if xk.shape[-2] != 0
209
+ else None
210
+ )
211
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_)
212
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3)
213
+ if xk_ is None:
214
+ # no keys to rotate, due to dropout
215
+ return xq_out.type_as(xq).to(xq.device), xk
216
+ # repeat freqs along seq_len dim to match k seq_len
217
+ if repeat_freqs_k:
218
+ r = xk_.shape[-2] // xq_.shape[-2]
219
+ if freqs_cis.is_cuda:
220
+ freqs_cis = freqs_cis.repeat(*([1] * (freqs_cis.ndim - 2)), r, 1)
221
+ else:
222
+ # torch.repeat on complex numbers may not be supported on non-CUDA devices
223
+ # (freqs_cis has 4 dims and we repeat on dim 2) so we use expand + flatten
224
+ freqs_cis = freqs_cis.unsqueeze(2).expand(-1, -1, r, -1, -1).flatten(2, 3)
225
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3)
226
+ return xq_out.type_as(xq).to(xq.device), xk_out.type_as(xk).to(xk.device)
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/mask_decoder.py ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import List, Optional, Tuple, Type
8
+
9
+ import torch
10
+ from torch import nn
11
+
12
+ from torchao._models.sam2.modeling.sam2_utils import MLP, LayerNorm2d
13
+
14
+
15
+ class MaskDecoder(nn.Module):
16
+ def __init__(
17
+ self,
18
+ *,
19
+ transformer_dim: int,
20
+ transformer: nn.Module,
21
+ num_multimask_outputs: int = 3,
22
+ activation: Type[nn.Module] = nn.GELU,
23
+ iou_head_depth: int = 3,
24
+ iou_head_hidden_dim: int = 256,
25
+ use_high_res_features: bool = False,
26
+ iou_prediction_use_sigmoid=False,
27
+ dynamic_multimask_via_stability=False,
28
+ dynamic_multimask_stability_delta=0.05,
29
+ dynamic_multimask_stability_thresh=0.98,
30
+ pred_obj_scores: bool = False,
31
+ pred_obj_scores_mlp: bool = False,
32
+ use_multimask_token_for_obj_ptr: bool = False,
33
+ ) -> None:
34
+ """
35
+ Predicts masks given an image and prompt embeddings, using a
36
+ transformer architecture.
37
+
38
+ Arguments:
39
+ transformer_dim (int): the channel dimension of the transformer
40
+ transformer (nn.Module): the transformer used to predict masks
41
+ num_multimask_outputs (int): the number of masks to predict
42
+ when disambiguating masks
43
+ activation (nn.Module): the type of activation to use when
44
+ upscaling masks
45
+ iou_head_depth (int): the depth of the MLP used to predict
46
+ mask quality
47
+ iou_head_hidden_dim (int): the hidden dimension of the MLP
48
+ used to predict mask quality
49
+ """
50
+ super().__init__()
51
+ self.transformer_dim = transformer_dim
52
+ self.transformer = transformer
53
+
54
+ self.num_multimask_outputs = num_multimask_outputs
55
+
56
+ self.iou_token = nn.Embedding(1, transformer_dim)
57
+ self.num_mask_tokens = num_multimask_outputs + 1
58
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
59
+
60
+ self.pred_obj_scores = pred_obj_scores
61
+ if self.pred_obj_scores:
62
+ self.obj_score_token = nn.Embedding(1, transformer_dim)
63
+ self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
64
+
65
+ self.output_upscaling = nn.Sequential(
66
+ nn.ConvTranspose2d(
67
+ transformer_dim, transformer_dim // 4, kernel_size=2, stride=2
68
+ ),
69
+ LayerNorm2d(transformer_dim // 4),
70
+ activation(),
71
+ nn.ConvTranspose2d(
72
+ transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2
73
+ ),
74
+ activation(),
75
+ )
76
+ self.use_high_res_features = use_high_res_features
77
+ if use_high_res_features:
78
+ self.conv_s0 = nn.Conv2d(
79
+ transformer_dim, transformer_dim // 8, kernel_size=1, stride=1
80
+ )
81
+ self.conv_s1 = nn.Conv2d(
82
+ transformer_dim, transformer_dim // 4, kernel_size=1, stride=1
83
+ )
84
+
85
+ self.output_hypernetworks_mlps = nn.ModuleList(
86
+ [
87
+ MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
88
+ for i in range(self.num_mask_tokens)
89
+ ]
90
+ )
91
+
92
+ self.iou_prediction_head = MLP(
93
+ transformer_dim,
94
+ iou_head_hidden_dim,
95
+ self.num_mask_tokens,
96
+ iou_head_depth,
97
+ sigmoid_output=iou_prediction_use_sigmoid,
98
+ )
99
+ if self.pred_obj_scores:
100
+ self.pred_obj_score_head = nn.Linear(transformer_dim, 1)
101
+ if pred_obj_scores_mlp:
102
+ self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3)
103
+
104
+ # When outputting a single mask, optionally we can dynamically fall back to the best
105
+ # multimask output token if the single mask output token gives low stability scores.
106
+ self.dynamic_multimask_via_stability = dynamic_multimask_via_stability
107
+ self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta
108
+ self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh
109
+ self._src_dtype = torch.float32
110
+
111
+ def forward(
112
+ self,
113
+ image_embeddings: torch.Tensor,
114
+ image_pe: torch.Tensor,
115
+ sparse_prompt_embeddings: torch.Tensor,
116
+ dense_prompt_embeddings: torch.Tensor,
117
+ multimask_output: bool,
118
+ repeat_image: bool,
119
+ high_res_features: Optional[List[torch.Tensor]] = None,
120
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
121
+ """
122
+ Predict masks given image and prompt embeddings.
123
+
124
+ Arguments:
125
+ image_embeddings (torch.Tensor): the embeddings from the image encoder
126
+ image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
127
+ sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
128
+ dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
129
+ multimask_output (bool): Whether to return multiple masks or a single
130
+ mask.
131
+
132
+ Returns:
133
+ torch.Tensor: batched predicted masks
134
+ torch.Tensor: batched predictions of mask quality
135
+ torch.Tensor: batched SAM token for mask output
136
+ """
137
+ masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks(
138
+ image_embeddings=image_embeddings,
139
+ image_pe=image_pe,
140
+ sparse_prompt_embeddings=sparse_prompt_embeddings,
141
+ dense_prompt_embeddings=dense_prompt_embeddings,
142
+ repeat_image=repeat_image,
143
+ high_res_features=high_res_features,
144
+ )
145
+
146
+ # Select the correct mask or masks for output
147
+ if multimask_output:
148
+ masks = masks[:, 1:, :, :]
149
+ iou_pred = iou_pred[:, 1:]
150
+ elif self.dynamic_multimask_via_stability and not self.training:
151
+ masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred)
152
+ else:
153
+ masks = masks[:, 0:1, :, :]
154
+ iou_pred = iou_pred[:, 0:1]
155
+
156
+ if multimask_output and self.use_multimask_token_for_obj_ptr:
157
+ sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape
158
+ else:
159
+ # Take the mask output token. Here we *always* use the token for single mask output.
160
+ # At test time, even if we track after 1-click (and using multimask_output=True),
161
+ # we still take the single mask token here. The rationale is that we always track
162
+ # after multiple clicks during training, so the past tokens seen during training
163
+ # are always the single mask token (and we'll let it be the object-memory token).
164
+ sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape
165
+
166
+ # Prepare output
167
+ return masks, iou_pred, sam_tokens_out, object_score_logits
168
+
169
+ def predict_masks(
170
+ self,
171
+ image_embeddings: torch.Tensor,
172
+ image_pe: torch.Tensor,
173
+ sparse_prompt_embeddings: torch.Tensor,
174
+ dense_prompt_embeddings: torch.Tensor,
175
+ repeat_image: bool,
176
+ high_res_features: Optional[List[torch.Tensor]] = None,
177
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
178
+ """Predicts masks. See 'forward' for more details."""
179
+ # Concatenate output tokens
180
+ s = 0
181
+ if self.pred_obj_scores:
182
+ output_tokens = torch.cat(
183
+ [
184
+ self.obj_score_token.weight,
185
+ self.iou_token.weight,
186
+ self.mask_tokens.weight,
187
+ ],
188
+ dim=0,
189
+ )
190
+ s = 1
191
+ else:
192
+ output_tokens = torch.cat(
193
+ [self.iou_token.weight, self.mask_tokens.weight], dim=0
194
+ )
195
+ output_tokens = output_tokens.unsqueeze(0).expand(
196
+ sparse_prompt_embeddings.size(0), -1, -1
197
+ )
198
+ tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
199
+
200
+ # Expand per-image data in batch direction to be per-mask
201
+ if repeat_image:
202
+ src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
203
+ else:
204
+ assert image_embeddings.shape[0] == tokens.shape[0]
205
+ src = image_embeddings
206
+ src = src + dense_prompt_embeddings
207
+ assert image_pe.size(0) == 1, (
208
+ "image_pe should have size 1 in batch dim (from `get_dense_pe()`)"
209
+ )
210
+ pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
211
+ b, c, h, w = src.shape
212
+
213
+ with torch.autograd.profiler.record_function("self.transformer"):
214
+ # # Run the transformer
215
+ src = src.to(self._src_dtype)
216
+ pos_src = pos_src.to(self._src_dtype)
217
+ tokens = tokens.to(self._src_dtype)
218
+ hs, new_src = self.transformer(src, pos_src, tokens)
219
+ # TODO: Not specifying scale kwarg in SDPA will cause NaN here
220
+ # print("hs.isnan().any(): ", hs.isnan().any().item())
221
+
222
+ # TODO: These outputs are being immediately indexed.
223
+ # Is there something to remove?
224
+ # TODO: The fact that there's a crop box and we try to find stuff at the
225
+ # boundary later and there's generally cropping going on smells of padding.
226
+ iou_token_out = hs[:, s, :]
227
+ mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :]
228
+
229
+ # Upscale mask embeddings and predict masks using the mask tokens
230
+ src = new_src.transpose(1, 2).view(b, c, h, w)
231
+ if not self.use_high_res_features:
232
+ upscaled_embedding = self.output_upscaling(src)
233
+ else:
234
+ with torch.autograd.profiler.record_function("upscale mask embeddings"):
235
+ dc1, ln1, act1, dc2, act2 = self.output_upscaling
236
+ feat_s0, feat_s1 = high_res_features
237
+ upscaled_embedding = act1(ln1(dc1(src) + feat_s1))
238
+ upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0)
239
+ # upscaled_embedding = act2(torch.cat([dc2(upscaled_embedding[:512]), dc2(upscaled_embedding[-512:])]) + feat_s0)
240
+
241
+ hyper_in_list: List[torch.Tensor] = []
242
+ for i in range(self.num_mask_tokens):
243
+ hyper_in_list.append(
244
+ self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :])
245
+ )
246
+ hyper_in = torch.stack(hyper_in_list, dim=1)
247
+ b, c, h, w = upscaled_embedding.shape
248
+ # masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
249
+ masks = (
250
+ torch.matmul(
251
+ upscaled_embedding.view(b, c, h * w).transpose(-1, -2),
252
+ hyper_in.transpose(-1, -2),
253
+ )
254
+ .transpose(-1, -2)
255
+ .reshape(b, -1, h, w)
256
+ )
257
+
258
+ # Generate mask quality predictions
259
+ iou_pred = self.iou_prediction_head(iou_token_out)
260
+ if self.pred_obj_scores:
261
+ assert s == 1
262
+ object_score_logits = self.pred_obj_score_head(hs[:, 0, :])
263
+ else:
264
+ # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1
265
+ object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1)
266
+
267
+ return masks, iou_pred, mask_tokens_out, object_score_logits
268
+
269
+ def _get_stability_scores(self, mask_logits):
270
+ """
271
+ Compute stability scores of the mask logits based on the IoU between upper and
272
+ lower thresholds.
273
+ """
274
+ mask_logits = mask_logits.flatten(-2)
275
+ stability_delta = self.dynamic_multimask_stability_delta
276
+ area_i = torch.sum(mask_logits > stability_delta, dim=-1).float()
277
+ area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float()
278
+ stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0)
279
+ return stability_scores
280
+
281
+ def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores):
282
+ """
283
+ When outputting a single mask, if the stability score from the current single-mask
284
+ output (based on output token 0) falls below a threshold, we instead select from
285
+ multi-mask outputs (based on output token 1~3) the mask with the highest predicted
286
+ IoU score. This is intended to ensure a valid mask for both clicking and tracking.
287
+ """
288
+ # The best mask from multimask output tokens (1~3)
289
+ multimask_logits = all_mask_logits[:, 1:, :, :]
290
+ multimask_iou_scores = all_iou_scores[:, 1:]
291
+ best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1)
292
+ batch_inds = torch.arange(
293
+ multimask_iou_scores.size(0), device=all_iou_scores.device
294
+ )
295
+ best_multimask_logits = multimask_logits[batch_inds, best_scores_inds]
296
+ best_multimask_logits = best_multimask_logits.unsqueeze(1)
297
+ best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds]
298
+ best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1)
299
+
300
+ # The mask from singlemask output token 0 and its stability score
301
+ singlemask_logits = all_mask_logits[:, 0:1, :, :]
302
+ singlemask_iou_scores = all_iou_scores[:, 0:1]
303
+ stability_scores = self._get_stability_scores(singlemask_logits)
304
+ is_stable = stability_scores >= self.dynamic_multimask_stability_thresh
305
+
306
+ # Dynamically fall back to best multimask output upon low stability scores.
307
+ mask_logits_out = torch.where(
308
+ is_stable[..., None, None].expand_as(singlemask_logits),
309
+ singlemask_logits,
310
+ best_multimask_logits,
311
+ )
312
+ iou_scores_out = torch.where(
313
+ is_stable.expand_as(singlemask_iou_scores),
314
+ singlemask_iou_scores,
315
+ best_multimask_iou_scores,
316
+ )
317
+ return mask_logits_out, iou_scores_out
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/prompt_encoder.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ from typing import Optional, Tuple, Type
8
+
9
+ import torch
10
+ from torch import nn
11
+
12
+ from torchao._models.sam2.modeling.position_encoding import PositionEmbeddingRandom
13
+ from torchao._models.sam2.modeling.sam2_utils import LayerNorm2d
14
+
15
+
16
+ class PromptEncoder(nn.Module):
17
+ def __init__(
18
+ self,
19
+ embed_dim: int,
20
+ image_embedding_size: Tuple[int, int],
21
+ input_image_size: Tuple[int, int],
22
+ mask_in_chans: int,
23
+ activation: Type[nn.Module] = nn.GELU,
24
+ ) -> None:
25
+ """
26
+ Encodes prompts for input to SAM's mask decoder.
27
+
28
+ Arguments:
29
+ embed_dim (int): The prompts' embedding dimension
30
+ image_embedding_size (tuple(int, int)): The spatial size of the
31
+ image embedding, as (H, W).
32
+ input_image_size (int): The padded size of the image as input
33
+ to the image encoder, as (H, W).
34
+ mask_in_chans (int): The number of hidden channels used for
35
+ encoding input masks.
36
+ activation (nn.Module): The activation to use when encoding
37
+ input masks.
38
+ """
39
+ super().__init__()
40
+ self.embed_dim = embed_dim
41
+ self.input_image_size = input_image_size
42
+ self.image_embedding_size = image_embedding_size
43
+ self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)
44
+
45
+ self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners
46
+ point_embeddings = [
47
+ nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)
48
+ ]
49
+ self.point_embeddings = nn.ModuleList(point_embeddings)
50
+ self.not_a_point_embed = nn.Embedding(1, embed_dim)
51
+
52
+ self.mask_input_size = (
53
+ 4 * image_embedding_size[0],
54
+ 4 * image_embedding_size[1],
55
+ )
56
+ self.mask_downscaling = nn.Sequential(
57
+ nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),
58
+ LayerNorm2d(mask_in_chans // 4),
59
+ activation(),
60
+ nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),
61
+ LayerNorm2d(mask_in_chans),
62
+ activation(),
63
+ nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),
64
+ )
65
+ self.no_mask_embed = nn.Embedding(1, embed_dim)
66
+
67
+ def get_dense_pe(self) -> torch.Tensor:
68
+ """
69
+ Returns the positional encoding used to encode point prompts,
70
+ applied to a dense set of points the shape of the image encoding.
71
+
72
+ Returns:
73
+ torch.Tensor: Positional encoding with shape
74
+ 1x(embed_dim)x(embedding_h)x(embedding_w)
75
+ """
76
+ return self.pe_layer(self.image_embedding_size).unsqueeze(0)
77
+
78
+ def _embed_points(
79
+ self,
80
+ points: torch.Tensor,
81
+ labels: torch.Tensor,
82
+ pad: bool,
83
+ ) -> torch.Tensor:
84
+ """Embeds point prompts."""
85
+ points = points + 0.5 # Shift to center of pixel
86
+ if pad:
87
+ padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)
88
+ padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)
89
+ points = torch.cat([points, padding_point], dim=1)
90
+ labels = torch.cat([labels, padding_label], dim=1)
91
+ point_embedding = self.pe_layer.forward_with_coords(
92
+ points, self.input_image_size
93
+ )
94
+ # point_embedding[labels == -1] = 0.0
95
+ # point_embedding[labels == -1] += self.not_a_point_embed.weight
96
+ # point_embedding[labels == 0] += self.point_embeddings[0].weight
97
+ # point_embedding[labels == 1] += self.point_embeddings[1].weight
98
+ # point_embedding[labels == 2] += self.point_embeddings[2].weight
99
+ # point_embedding[labels == 3] += self.point_embeddings[3].weight
100
+
101
+ point_embedding = torch.where(
102
+ (labels == -1).unsqueeze(-1).expand_as(point_embedding),
103
+ torch.zeros_like(point_embedding) + self.not_a_point_embed.weight,
104
+ point_embedding,
105
+ )
106
+ point_embedding = torch.where(
107
+ (labels == 0).unsqueeze(-1).expand_as(point_embedding),
108
+ point_embedding + self.point_embeddings[0].weight,
109
+ point_embedding,
110
+ )
111
+ point_embedding = torch.where(
112
+ (labels == 1).unsqueeze(-1).expand_as(point_embedding),
113
+ point_embedding + self.point_embeddings[1].weight,
114
+ point_embedding,
115
+ )
116
+ point_embedding = torch.where(
117
+ (labels == 2).unsqueeze(-1).expand_as(point_embedding),
118
+ point_embedding + self.point_embeddings[2].weight,
119
+ point_embedding,
120
+ )
121
+ point_embedding = torch.where(
122
+ (labels == 3).unsqueeze(-1).expand_as(point_embedding),
123
+ point_embedding + self.point_embeddings[3].weight,
124
+ point_embedding,
125
+ )
126
+
127
+ return point_embedding
128
+
129
+ def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
130
+ """Embeds box prompts."""
131
+ boxes = boxes + 0.5 # Shift to center of pixel
132
+ coords = boxes.reshape(-1, 2, 2)
133
+ corner_embedding = self.pe_layer.forward_with_coords(
134
+ coords, self.input_image_size
135
+ )
136
+ corner_embedding[:, 0, :] += self.point_embeddings[2].weight
137
+ corner_embedding[:, 1, :] += self.point_embeddings[3].weight
138
+ return corner_embedding
139
+
140
+ def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:
141
+ """Embeds mask inputs."""
142
+ mask_embedding = self.mask_downscaling(masks)
143
+ return mask_embedding
144
+
145
+ def _get_batch_size(
146
+ self,
147
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
148
+ boxes: Optional[torch.Tensor],
149
+ masks: Optional[torch.Tensor],
150
+ ) -> int:
151
+ """
152
+ Gets the batch size of the output given the batch size of the input prompts.
153
+ """
154
+ if points is not None:
155
+ return points[0].shape[0]
156
+ elif boxes is not None:
157
+ return boxes.shape[0]
158
+ elif masks is not None:
159
+ return masks.shape[0]
160
+ else:
161
+ return 1
162
+
163
+ def _get_device(self) -> torch.device:
164
+ return self.point_embeddings[0].weight.device
165
+
166
+ def forward(
167
+ self,
168
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
169
+ boxes: Optional[torch.Tensor],
170
+ masks: Optional[torch.Tensor],
171
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
172
+ """
173
+ Embeds different types of prompts, returning both sparse and dense
174
+ embeddings.
175
+
176
+ Arguments:
177
+ points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates
178
+ and labels to embed.
179
+ boxes (torch.Tensor or none): boxes to embed
180
+ masks (torch.Tensor or none): masks to embed
181
+
182
+ Returns:
183
+ torch.Tensor: sparse embeddings for the points and boxes, with shape
184
+ BxNx(embed_dim), where N is determined by the number of input points
185
+ and boxes.
186
+ torch.Tensor: dense embeddings for the masks, in the shape
187
+ Bx(embed_dim)x(embed_H)x(embed_W)
188
+ """
189
+ # if boxes is not None:
190
+ # raise ValueError("Currently do not support boxes. "
191
+ # "Please create an issue on pytorch/ao.")
192
+ # if masks is not None:
193
+ # raise ValueError("Currently do not support masks. "
194
+ # "Please create an issue on pytorch/ao.")
195
+ bs = self._get_batch_size(points, boxes, masks)
196
+ sparse_embeddings = torch.empty(
197
+ (bs, 0, self.embed_dim), device=self._get_device()
198
+ )
199
+ if points is not None:
200
+ coords, labels = points
201
+ point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))
202
+ sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)
203
+ if boxes is not None:
204
+ box_embeddings = self._embed_boxes(boxes)
205
+ sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)
206
+
207
+ if masks is not None:
208
+ dense_embeddings = self._embed_masks(masks)
209
+ else:
210
+ dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
211
+ bs, -1, self.image_embedding_size[0], self.image_embedding_size[1]
212
+ )
213
+
214
+ return sparse_embeddings, dense_embeddings
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/transformer.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import contextlib
8
+ import math
9
+ import warnings
10
+ from functools import partial
11
+ from typing import Tuple, Type
12
+
13
+ import torch
14
+ import torch.nn.functional as F
15
+ from torch import Tensor, nn
16
+
17
+ from torchao._models.sam2.modeling.position_encoding import (
18
+ apply_rotary_enc,
19
+ compute_axial_cis,
20
+ )
21
+ from torchao._models.sam2.modeling.sam2_utils import MLP
22
+ from torchao._models.sam2.utils.misc import get_sdpa_settings
23
+
24
+ warnings.simplefilter(action="ignore", category=FutureWarning)
25
+ # Check whether Flash Attention is available (and use it by default)
26
+ OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = get_sdpa_settings()
27
+ # A fallback setting to allow all available kernels if Flash Attention fails
28
+ ALLOW_ALL_KERNELS = False
29
+
30
+
31
+ def sdp_kernel_context(dropout_p):
32
+ """
33
+ Get the context for the attention scaled dot-product kernel. We use Flash Attention
34
+ by default, but fall back to all available kernels if Flash Attention fails.
35
+ """
36
+ if ALLOW_ALL_KERNELS:
37
+ return contextlib.nullcontext()
38
+
39
+ return torch.backends.cuda.sdp_kernel(
40
+ enable_flash=USE_FLASH_ATTN,
41
+ # if Flash attention kernel is off, then math kernel needs to be enabled
42
+ enable_math=(OLD_GPU and dropout_p > 0.0) or MATH_KERNEL_ON,
43
+ enable_mem_efficient=OLD_GPU,
44
+ )
45
+
46
+
47
+ class TwoWayTransformer(nn.Module):
48
+ def __init__(
49
+ self,
50
+ depth: int,
51
+ embedding_dim: int,
52
+ num_heads: int,
53
+ mlp_dim: int,
54
+ activation: Type[nn.Module] = nn.ReLU,
55
+ attention_downsample_rate: int = 2,
56
+ ) -> None:
57
+ """
58
+ A transformer decoder that attends to an input image using
59
+ queries whose positional embedding is supplied.
60
+
61
+ Args:
62
+ depth (int): number of layers in the transformer
63
+ embedding_dim (int): the channel dimension for the input embeddings
64
+ num_heads (int): the number of heads for multihead attention. Must
65
+ divide embedding_dim
66
+ mlp_dim (int): the channel dimension internal to the MLP block
67
+ activation (nn.Module): the activation to use in the MLP block
68
+ """
69
+ super().__init__()
70
+ self.depth = depth
71
+ self.embedding_dim = embedding_dim
72
+ self.num_heads = num_heads
73
+ self.mlp_dim = mlp_dim
74
+ self.layers = nn.ModuleList()
75
+
76
+ for i in range(depth):
77
+ self.layers.append(
78
+ TwoWayAttentionBlock(
79
+ embedding_dim=embedding_dim,
80
+ num_heads=num_heads,
81
+ mlp_dim=mlp_dim,
82
+ activation=activation,
83
+ attention_downsample_rate=attention_downsample_rate,
84
+ skip_first_layer_pe=(i == 0),
85
+ )
86
+ )
87
+
88
+ self.final_attn_token_to_image = Attention(
89
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
90
+ )
91
+ self.norm_final_attn = nn.LayerNorm(embedding_dim)
92
+
93
+ def forward(
94
+ self,
95
+ image_embedding: Tensor,
96
+ image_pe: Tensor,
97
+ point_embedding: Tensor,
98
+ ) -> Tuple[Tensor, Tensor]:
99
+ """
100
+ Args:
101
+ image_embedding (torch.Tensor): image to attend to. Should be shape
102
+ B x embedding_dim x h x w for any h and w.
103
+ image_pe (torch.Tensor): the positional encoding to add to the image. Must
104
+ have the same shape as image_embedding.
105
+ point_embedding (torch.Tensor): the embedding to add to the query points.
106
+ Must have shape B x N_points x embedding_dim for any N_points.
107
+
108
+ Returns:
109
+ torch.Tensor: the processed point_embedding
110
+ torch.Tensor: the processed image_embedding
111
+ """
112
+ # BxCxHxW -> BxHWxC == B x N_image_tokens x C
113
+ bs, c, h, w = image_embedding.shape
114
+ image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
115
+ image_pe = image_pe.flatten(2).permute(0, 2, 1)
116
+
117
+ # Prepare queries
118
+ queries = point_embedding
119
+ keys = image_embedding
120
+
121
+ # Apply transformer blocks and final layernorm
122
+ for layer in self.layers:
123
+ queries, keys = layer(
124
+ queries=queries,
125
+ keys=keys,
126
+ query_pe=point_embedding,
127
+ key_pe=image_pe,
128
+ )
129
+
130
+ # Apply the final attention layer from the points to the image
131
+ q = queries + point_embedding
132
+ k = keys + image_pe
133
+ attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
134
+ queries = queries + attn_out
135
+ queries = self.norm_final_attn(queries)
136
+
137
+ return queries, keys
138
+
139
+
140
+ class TwoWayAttentionBlock(nn.Module):
141
+ def __init__(
142
+ self,
143
+ embedding_dim: int,
144
+ num_heads: int,
145
+ mlp_dim: int = 2048,
146
+ activation: Type[nn.Module] = nn.ReLU,
147
+ attention_downsample_rate: int = 2,
148
+ skip_first_layer_pe: bool = False,
149
+ ) -> None:
150
+ """
151
+ A transformer block with four layers: (1) self-attention of sparse
152
+ inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp
153
+ block on sparse inputs, and (4) cross attention of dense inputs to sparse
154
+ inputs.
155
+
156
+ Arguments:
157
+ embedding_dim (int): the channel dimension of the embeddings
158
+ num_heads (int): the number of heads in the attention layers
159
+ mlp_dim (int): the hidden dimension of the mlp block
160
+ activation (nn.Module): the activation of the mlp block
161
+ skip_first_layer_pe (bool): skip the PE on the first layer
162
+ """
163
+ super().__init__()
164
+ self.self_attn = Attention(embedding_dim, num_heads)
165
+ self.norm1 = nn.LayerNorm(embedding_dim)
166
+
167
+ self.cross_attn_token_to_image = Attention(
168
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
169
+ )
170
+ self.norm2 = nn.LayerNorm(embedding_dim)
171
+
172
+ self.mlp = MLP(
173
+ embedding_dim, mlp_dim, embedding_dim, num_layers=2, activation=activation
174
+ )
175
+ self.norm3 = nn.LayerNorm(embedding_dim)
176
+
177
+ self.norm4 = nn.LayerNorm(embedding_dim)
178
+ self.cross_attn_image_to_token = Attention(
179
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
180
+ )
181
+
182
+ self.skip_first_layer_pe = skip_first_layer_pe
183
+
184
+ def forward(
185
+ self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor
186
+ ) -> Tuple[Tensor, Tensor]:
187
+ # Self attention block
188
+ if self.skip_first_layer_pe:
189
+ queries = self.self_attn(q=queries, k=queries, v=queries)
190
+ else:
191
+ q = queries + query_pe
192
+ attn_out = self.self_attn(q=q, k=q, v=queries)
193
+ queries = queries + attn_out
194
+ queries = self.norm1(queries)
195
+
196
+ # Cross attention block, tokens attending to image embedding
197
+ q = queries + query_pe
198
+ k = keys + key_pe
199
+ attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
200
+ queries = queries + attn_out
201
+ queries = self.norm2(queries)
202
+
203
+ # MLP block
204
+ mlp_out = self.mlp(queries)
205
+ queries = queries + mlp_out
206
+ queries = self.norm3(queries)
207
+
208
+ # Cross attention block, image embedding attending to tokens
209
+ q = queries + query_pe
210
+ k = keys + key_pe
211
+ attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
212
+ keys = keys + attn_out
213
+ keys = self.norm4(keys)
214
+
215
+ return queries, keys
216
+
217
+
218
+ class Attention(nn.Module):
219
+ """
220
+ An attention layer that allows for downscaling the size of the embedding
221
+ after projection to queries, keys, and values.
222
+ """
223
+
224
+ def __init__(
225
+ self,
226
+ embedding_dim: int,
227
+ num_heads: int,
228
+ downsample_rate: int = 1,
229
+ dropout: float = 0.0,
230
+ kv_in_dim: int = None,
231
+ ) -> None:
232
+ super().__init__()
233
+ self.embedding_dim = embedding_dim
234
+ self.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dim
235
+ self.internal_dim = embedding_dim // downsample_rate
236
+ self.num_heads = num_heads
237
+ assert self.internal_dim % num_heads == 0, (
238
+ "num_heads must divide embedding_dim."
239
+ )
240
+
241
+ self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
242
+ self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
243
+ self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim)
244
+ self.out_proj = nn.Linear(self.internal_dim, embedding_dim)
245
+
246
+ self.dropout_p = dropout
247
+
248
+ def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:
249
+ b, n, c = x.shape
250
+ x = x.reshape(b, n, num_heads, c // num_heads)
251
+ return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
252
+
253
+ def _recombine_heads(self, x: Tensor) -> Tensor:
254
+ b, n_heads, n_tokens, c_per_head = x.shape
255
+ x = x.transpose(1, 2)
256
+ return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
257
+
258
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
259
+ # Input projections
260
+ q = self.q_proj(q)
261
+ k = self.k_proj(k)
262
+ v = self.v_proj(v)
263
+
264
+ # Separate into heads
265
+ q = self._separate_heads(q, self.num_heads)
266
+ k = self._separate_heads(k, self.num_heads)
267
+ v = self._separate_heads(v, self.num_heads)
268
+
269
+ dropout_p = self.dropout_p if self.training else 0.0
270
+ # # Attention
271
+ # try:
272
+ # with sdp_kernel_context(dropout_p):
273
+ # out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
274
+ # except Exception as e:
275
+ # # Fall back to all kernels if the Flash attention kernel fails
276
+ # warnings.warn(
277
+ # f"Flash Attention kernel failed due to: {e}\nFalling back to all available "
278
+ # f"kernels for scaled_dot_product_attention (which may have a slower speed).",
279
+ # category=UserWarning,
280
+ # stacklevel=2,
281
+ # )
282
+ # global ALLOW_ALL_KERNELS
283
+ # ALLOW_ALL_KERNELS = True
284
+ # out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
285
+ # TODO: This scale should not be needed. But without it compile causes a NaN.
286
+ out = F.scaled_dot_product_attention(
287
+ q, k, v, dropout_p=dropout_p, scale=(1.0 / math.sqrt(q.size(-1)))
288
+ )
289
+
290
+ out = self._recombine_heads(out)
291
+ out = self.out_proj(out)
292
+
293
+ return out
294
+
295
+
296
+ class RoPEAttention(Attention):
297
+ """Attention with rotary position encoding."""
298
+
299
+ def __init__(
300
+ self,
301
+ *args,
302
+ rope_theta=10000.0,
303
+ # whether to repeat q rope to match k length
304
+ # this is needed for cross-attention to memories
305
+ rope_k_repeat=False,
306
+ feat_sizes=(32, 32), # [w, h] for stride 16 feats at 512 resolution
307
+ **kwargs,
308
+ ):
309
+ super().__init__(*args, **kwargs)
310
+
311
+ self.compute_cis = partial(
312
+ compute_axial_cis, dim=self.internal_dim // self.num_heads, theta=rope_theta
313
+ )
314
+ freqs_cis = self.compute_cis(end_x=feat_sizes[0], end_y=feat_sizes[1])
315
+ self.freqs_cis = freqs_cis
316
+ self.rope_k_repeat = rope_k_repeat
317
+
318
+ def forward(
319
+ self, q: Tensor, k: Tensor, v: Tensor, num_k_exclude_rope: int = 0
320
+ ) -> Tensor:
321
+ # Input projections
322
+ q = self.q_proj(q)
323
+ k = self.k_proj(k)
324
+ v = self.v_proj(v)
325
+
326
+ # Separate into heads
327
+ q = self._separate_heads(q, self.num_heads)
328
+ k = self._separate_heads(k, self.num_heads)
329
+ v = self._separate_heads(v, self.num_heads)
330
+
331
+ # Apply rotary position encoding
332
+ w = h = math.sqrt(q.shape[-2])
333
+ # NOTE: Disabling this.
334
+ # self.freqs_cis = self.freqs_cis.to(q.device)
335
+ if self.freqs_cis.shape[0] != q.shape[-2]:
336
+ self.freqs_cis = self.compute_cis(
337
+ end_x=w, end_y=h, device=q.device
338
+ ) # .to(q.device)
339
+ if q.shape[-2] != k.shape[-2]:
340
+ assert self.rope_k_repeat
341
+
342
+ num_k_rope = k.size(-2) - num_k_exclude_rope
343
+ q, k[:, :, :num_k_rope] = apply_rotary_enc(
344
+ q,
345
+ k[:, :, :num_k_rope],
346
+ freqs_cis=self.freqs_cis,
347
+ repeat_freqs_k=self.rope_k_repeat,
348
+ )
349
+
350
+ dropout_p = self.dropout_p if self.training else 0.0
351
+ # # Attention
352
+ # try:
353
+ # with sdp_kernel_context(dropout_p):
354
+ # out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p)
355
+ # except Exception as e:
356
+ # # Fall back to all kernels if the Flash attention kernel fails
357
+ # warnings.warn(
358
+ # f"Flash Attention kernel failed due to: {e}\nFalling back to all available "
359
+ # f"kernels for scaled_dot_product_attention (which may have a slower speed).",
360
+ # category=UserWarning,
361
+ # stacklevel=2,
362
+ # )
363
+ # global ALLOW_ALL_KERNELS
364
+ # ALLOW_ALL_KERNELS = True
365
+ # TODO: This scale should not be needed. But without it compile causes a NaN.
366
+ out = F.scaled_dot_product_attention(
367
+ q, k, v, dropout_p=dropout_p, scale=(1.0 / math.sqrt(q.size(-1)))
368
+ )
369
+
370
+ out = self._recombine_heads(out)
371
+ out = self.out_proj(out)
372
+
373
+ return out
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam2_base.py ADDED
@@ -0,0 +1,929 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import torch
8
+ import torch.distributed
9
+ import torch.nn.functional as F
10
+ from torch.nn.init import trunc_normal_
11
+
12
+ from torchao._models.sam2.modeling.sam.mask_decoder import MaskDecoder
13
+ from torchao._models.sam2.modeling.sam.prompt_encoder import PromptEncoder
14
+ from torchao._models.sam2.modeling.sam.transformer import TwoWayTransformer
15
+ from torchao._models.sam2.modeling.sam2_utils import (
16
+ MLP,
17
+ get_1d_sine_pe,
18
+ select_closest_cond_frames,
19
+ )
20
+
21
+ # a large negative value as a placeholder score for missing objects
22
+ NO_OBJ_SCORE = -1024.0
23
+
24
+
25
+ class SAM2Base(torch.nn.Module):
26
+ def __init__(
27
+ self,
28
+ image_encoder,
29
+ memory_attention,
30
+ memory_encoder,
31
+ num_maskmem=7, # default 1 input frame + 6 previous frames
32
+ image_size=512,
33
+ backbone_stride=16, # stride of the image backbone output
34
+ sigmoid_scale_for_mem_enc=1.0, # scale factor for mask sigmoid prob
35
+ sigmoid_bias_for_mem_enc=0.0, # bias factor for mask sigmoid prob
36
+ # During evaluation, whether to binarize the sigmoid mask logits on interacted frames with clicks
37
+ binarize_mask_from_pts_for_mem_enc=False,
38
+ use_mask_input_as_output_without_sam=False, # on frames with mask input, whether to directly output the input mask without using a SAM prompt encoder + mask decoder
39
+ # The maximum number of conditioning frames to participate in the memory attention (-1 means no limit; if there are more conditioning frames than this limit,
40
+ # we only cross-attend to the temporally closest `max_cond_frames_in_attn` conditioning frames in the encoder when tracking each frame). This gives the model
41
+ # a temporal locality when handling a large number of annotated frames (since closer frames should be more important) and also avoids GPU OOM.
42
+ max_cond_frames_in_attn=-1,
43
+ # on the first frame, whether to directly add the no-memory embedding to the image feature
44
+ # (instead of using the transformer encoder)
45
+ directly_add_no_mem_embed=False,
46
+ # whether to use high-resolution feature maps in the SAM mask decoder
47
+ use_high_res_features_in_sam=False,
48
+ # whether to output multiple (3) masks for the first click on initial conditioning frames
49
+ multimask_output_in_sam=False,
50
+ # the minimum and maximum number of clicks to use multimask_output_in_sam (only relevant when `multimask_output_in_sam=True`;
51
+ # default is 1 for both, meaning that only the first click gives multimask output; also note that a box counts as two points)
52
+ multimask_min_pt_num=1,
53
+ multimask_max_pt_num=1,
54
+ # whether to also use multimask output for tracking (not just for the first click on initial conditioning frames; only relevant when `multimask_output_in_sam=True`)
55
+ multimask_output_for_tracking=False,
56
+ # Whether to use multimask tokens for obj ptr; Only relevant when both
57
+ # use_obj_ptrs_in_encoder=True and multimask_output_for_tracking=True
58
+ use_multimask_token_for_obj_ptr: bool = False,
59
+ # whether to use sigmoid to restrict ious prediction to [0-1]
60
+ iou_prediction_use_sigmoid=False,
61
+ # The memory bank's temporal stride during evaluation (i.e. the `r` parameter in XMem and Cutie; XMem and Cutie use r=5).
62
+ # For r>1, the (self.num_maskmem - 1) non-conditioning memory frames consist of
63
+ # (self.num_maskmem - 2) nearest frames from every r-th frames, plus the last frame.
64
+ memory_temporal_stride_for_eval=1,
65
+ # whether to apply non-overlapping constraints on the object masks in the memory encoder during evaluation (to avoid/alleviate superposing masks)
66
+ non_overlap_masks_for_mem_enc=False,
67
+ # whether to cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
68
+ use_obj_ptrs_in_encoder=False,
69
+ # the maximum number of object pointers from other frames in encoder cross attention (only relevant when `use_obj_ptrs_in_encoder=True`)
70
+ max_obj_ptrs_in_encoder=16,
71
+ # whether to add temporal positional encoding to the object pointers in the encoder (only relevant when `use_obj_ptrs_in_encoder=True`)
72
+ add_tpos_enc_to_obj_ptrs=True,
73
+ # whether to add an extra linear projection layer for the temporal positional encoding in the object pointers to avoid potential interference
74
+ # with spatial positional encoding (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`)
75
+ proj_tpos_enc_in_obj_ptrs=False,
76
+ # whether to use signed distance (instead of unsigned absolute distance) in the temporal positional encoding in the object pointers
77
+ # (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`)
78
+ use_signed_tpos_enc_to_obj_ptrs=False,
79
+ # whether to only attend to object pointers in the past (before the current frame) in the encoder during evaluation
80
+ # (only relevant when `use_obj_ptrs_in_encoder=True`; this might avoid pointer information too far in the future to distract the initial tracking)
81
+ only_obj_ptrs_in_the_past_for_eval=False,
82
+ # Whether to predict if there is an object in the frame
83
+ pred_obj_scores: bool = False,
84
+ # Whether to use an MLP to predict object scores
85
+ pred_obj_scores_mlp: bool = False,
86
+ # Only relevant if pred_obj_scores=True and use_obj_ptrs_in_encoder=True;
87
+ # Whether to have a fixed no obj pointer when there is no object present
88
+ # or to use it as an additive embedding with obj_ptr produced by decoder
89
+ fixed_no_obj_ptr: bool = False,
90
+ # Soft no object, i.e. mix in no_obj_ptr softly,
91
+ # hope to make recovery easier if there is a mistake and mitigate accumulation of errors
92
+ soft_no_obj_ptr: bool = False,
93
+ use_mlp_for_obj_ptr_proj: bool = False,
94
+ # add no obj embedding to spatial frames
95
+ no_obj_embed_spatial: bool = False,
96
+ # extra arguments used to construct the SAM mask decoder; if not None, it should be a dict of kwargs to be passed into `MaskDecoder` class.
97
+ sam_mask_decoder_extra_args=None,
98
+ compile_image_encoder: bool = False,
99
+ ):
100
+ super().__init__()
101
+
102
+ # Part 1: the image backbone
103
+ self.image_encoder = image_encoder
104
+ # Use level 0, 1, 2 for high-res setting, or just level 2 for the default setting
105
+ self.use_high_res_features_in_sam = use_high_res_features_in_sam
106
+ self.num_feature_levels = 3 if use_high_res_features_in_sam else 1
107
+ self.use_obj_ptrs_in_encoder = use_obj_ptrs_in_encoder
108
+ self.max_obj_ptrs_in_encoder = max_obj_ptrs_in_encoder
109
+ if use_obj_ptrs_in_encoder:
110
+ # A conv layer to downsample the mask prompt to stride 4 (the same stride as
111
+ # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale,
112
+ # so that it can be fed into the SAM mask decoder to generate a pointer.
113
+ self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4)
114
+ self.add_tpos_enc_to_obj_ptrs = add_tpos_enc_to_obj_ptrs
115
+ if proj_tpos_enc_in_obj_ptrs:
116
+ assert add_tpos_enc_to_obj_ptrs # these options need to be used together
117
+ self.proj_tpos_enc_in_obj_ptrs = proj_tpos_enc_in_obj_ptrs
118
+ self.use_signed_tpos_enc_to_obj_ptrs = use_signed_tpos_enc_to_obj_ptrs
119
+ self.only_obj_ptrs_in_the_past_for_eval = only_obj_ptrs_in_the_past_for_eval
120
+
121
+ # Part 2: memory attention to condition current frame's visual features
122
+ # with memories (and obj ptrs) from past frames
123
+ self.memory_attention = memory_attention
124
+ self.hidden_dim = image_encoder.neck.d_model
125
+
126
+ # Part 3: memory encoder for the previous frame's outputs
127
+ self.memory_encoder = memory_encoder
128
+ self.mem_dim = self.hidden_dim
129
+ if hasattr(self.memory_encoder, "out_proj") and hasattr(
130
+ self.memory_encoder.out_proj, "weight"
131
+ ):
132
+ # if there is compression of memories along channel dim
133
+ self.mem_dim = self.memory_encoder.out_proj.weight.shape[0]
134
+ self.num_maskmem = num_maskmem # Number of memories accessible
135
+ # Temporal encoding of the memories
136
+ self.maskmem_tpos_enc = torch.nn.Parameter(
137
+ torch.zeros(num_maskmem, 1, 1, self.mem_dim)
138
+ )
139
+ trunc_normal_(self.maskmem_tpos_enc, std=0.02)
140
+ # a single token to indicate no memory embedding from previous frames
141
+ self.no_mem_embed = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
142
+ self.no_mem_pos_enc = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim))
143
+ trunc_normal_(self.no_mem_embed, std=0.02)
144
+ trunc_normal_(self.no_mem_pos_enc, std=0.02)
145
+ self.directly_add_no_mem_embed = directly_add_no_mem_embed
146
+ # Apply sigmoid to the output raw mask logits (to turn them from
147
+ # range (-inf, +inf) to range (0, 1)) before feeding them into the memory encoder
148
+ self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc
149
+ self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc
150
+ self.binarize_mask_from_pts_for_mem_enc = binarize_mask_from_pts_for_mem_enc
151
+ self.non_overlap_masks_for_mem_enc = non_overlap_masks_for_mem_enc
152
+ self.memory_temporal_stride_for_eval = memory_temporal_stride_for_eval
153
+ # On frames with mask input, whether to directly output the input mask without
154
+ # using a SAM prompt encoder + mask decoder
155
+ self.use_mask_input_as_output_without_sam = use_mask_input_as_output_without_sam
156
+ self.multimask_output_in_sam = multimask_output_in_sam
157
+ self.multimask_min_pt_num = multimask_min_pt_num
158
+ self.multimask_max_pt_num = multimask_max_pt_num
159
+ self.multimask_output_for_tracking = multimask_output_for_tracking
160
+ self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr
161
+ self.iou_prediction_use_sigmoid = iou_prediction_use_sigmoid
162
+
163
+ # Part 4: SAM-style prompt encoder (for both mask and point inputs)
164
+ # and SAM-style mask decoder for the final mask output
165
+ self.image_size = image_size
166
+ self.backbone_stride = backbone_stride
167
+ self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args
168
+ self.pred_obj_scores = pred_obj_scores
169
+ self.pred_obj_scores_mlp = pred_obj_scores_mlp
170
+ self.fixed_no_obj_ptr = fixed_no_obj_ptr
171
+ self.soft_no_obj_ptr = soft_no_obj_ptr
172
+ if self.fixed_no_obj_ptr:
173
+ assert self.pred_obj_scores
174
+ assert self.use_obj_ptrs_in_encoder
175
+ if self.pred_obj_scores and self.use_obj_ptrs_in_encoder:
176
+ self.no_obj_ptr = torch.nn.Parameter(torch.zeros(1, self.hidden_dim))
177
+ trunc_normal_(self.no_obj_ptr, std=0.02)
178
+ self.use_mlp_for_obj_ptr_proj = use_mlp_for_obj_ptr_proj
179
+ self.no_obj_embed_spatial = None
180
+ if no_obj_embed_spatial:
181
+ self.no_obj_embed_spatial = torch.nn.Parameter(torch.zeros(1, self.mem_dim))
182
+ trunc_normal_(self.no_obj_embed_spatial, std=0.02)
183
+
184
+ self._build_sam_heads()
185
+ self.max_cond_frames_in_attn = max_cond_frames_in_attn
186
+
187
+ # Model compilation
188
+ if compile_image_encoder:
189
+ # Compile the forward function (not the full module) to allow loading checkpoints.
190
+ print(
191
+ "Image encoder compilation is enabled. First forward pass will be slow."
192
+ )
193
+ self.image_encoder.forward = torch.compile(
194
+ self.image_encoder.forward,
195
+ mode="max-autotune",
196
+ fullgraph=True,
197
+ dynamic=False,
198
+ )
199
+
200
+ @property
201
+ def device(self):
202
+ return next(self.parameters()).device
203
+
204
+ def forward(self, *args, **kwargs):
205
+ raise NotImplementedError(
206
+ "Please use the corresponding methods in SAM2VideoPredictor for inference or SAM2Train for training/fine-tuning"
207
+ "See notebooks/video_predictor_example.ipynb for an inference example."
208
+ )
209
+
210
+ def _build_sam_heads(self):
211
+ """Build SAM-style prompt encoder and mask decoder."""
212
+ self.sam_prompt_embed_dim = self.hidden_dim
213
+ self.sam_image_embedding_size = self.image_size // self.backbone_stride
214
+
215
+ # build PromptEncoder and MaskDecoder from SAM
216
+ # (their hyperparameters like `mask_in_chans=16` are from SAM code)
217
+ self.sam_prompt_encoder = PromptEncoder(
218
+ embed_dim=self.sam_prompt_embed_dim,
219
+ image_embedding_size=(
220
+ self.sam_image_embedding_size,
221
+ self.sam_image_embedding_size,
222
+ ),
223
+ input_image_size=(self.image_size, self.image_size),
224
+ mask_in_chans=16,
225
+ )
226
+ self.sam_mask_decoder = MaskDecoder(
227
+ num_multimask_outputs=3,
228
+ transformer=TwoWayTransformer(
229
+ depth=2,
230
+ embedding_dim=self.sam_prompt_embed_dim,
231
+ mlp_dim=2048,
232
+ num_heads=8,
233
+ ),
234
+ transformer_dim=self.sam_prompt_embed_dim,
235
+ iou_head_depth=3,
236
+ iou_head_hidden_dim=256,
237
+ use_high_res_features=self.use_high_res_features_in_sam,
238
+ iou_prediction_use_sigmoid=self.iou_prediction_use_sigmoid,
239
+ pred_obj_scores=self.pred_obj_scores,
240
+ pred_obj_scores_mlp=self.pred_obj_scores_mlp,
241
+ use_multimask_token_for_obj_ptr=self.use_multimask_token_for_obj_ptr,
242
+ **(self.sam_mask_decoder_extra_args or {}),
243
+ )
244
+ if self.use_obj_ptrs_in_encoder:
245
+ # a linear projection on SAM output tokens to turn them into object pointers
246
+ self.obj_ptr_proj = torch.nn.Linear(self.hidden_dim, self.hidden_dim)
247
+ if self.use_mlp_for_obj_ptr_proj:
248
+ self.obj_ptr_proj = MLP(
249
+ self.hidden_dim, self.hidden_dim, self.hidden_dim, 3
250
+ )
251
+ else:
252
+ self.obj_ptr_proj = torch.nn.Identity()
253
+ if self.proj_tpos_enc_in_obj_ptrs:
254
+ # a linear projection on temporal positional encoding in object pointers to
255
+ # avoid potential interference with spatial positional encoding
256
+ self.obj_ptr_tpos_proj = torch.nn.Linear(self.hidden_dim, self.mem_dim)
257
+ else:
258
+ self.obj_ptr_tpos_proj = torch.nn.Identity()
259
+
260
+ def _forward_sam_heads(
261
+ self,
262
+ backbone_features,
263
+ point_inputs=None,
264
+ mask_inputs=None,
265
+ high_res_features=None,
266
+ multimask_output=False,
267
+ ):
268
+ """
269
+ Forward SAM prompt encoders and mask heads.
270
+
271
+ Inputs:
272
+ - backbone_features: image features of [B, C, H, W] shape
273
+ - point_inputs: a dictionary with "point_coords" and "point_labels", where
274
+ 1) "point_coords" has [B, P, 2] shape and float32 dtype and contains the
275
+ absolute pixel-unit coordinate in (x, y) format of the P input points
276
+ 2) "point_labels" has shape [B, P] and int32 dtype, where 1 means
277
+ positive clicks, 0 means negative clicks, and -1 means padding
278
+ - mask_inputs: a mask of [B, 1, H*16, W*16] shape, float or bool, with the
279
+ same spatial size as the image.
280
+ - high_res_features: either 1) None or 2) or a list of length 2 containing
281
+ two feature maps of [B, C, 4*H, 4*W] and [B, C, 2*H, 2*W] shapes respectively,
282
+ which will be used as high-resolution feature maps for SAM decoder.
283
+ - multimask_output: if it's True, we output 3 candidate masks and their 3
284
+ corresponding IoU estimates, and if it's False, we output only 1 mask and
285
+ its corresponding IoU estimate.
286
+
287
+ Outputs:
288
+ - low_res_multimasks: [B, M, H*4, W*4] shape (where M = 3 if
289
+ `multimask_output=True` and M = 1 if `multimask_output=False`), the SAM
290
+ output mask logits (before sigmoid) for the low-resolution masks, with 4x
291
+ the resolution (1/4 stride) of the input backbone_features.
292
+ - high_res_multimasks: [B, M, H*16, W*16] shape (where M = 3
293
+ if `multimask_output=True` and M = 1 if `multimask_output=False`),
294
+ upsampled from the low-resolution masks, with shape size as the image
295
+ (stride is 1 pixel).
296
+ - ious, [B, M] shape, where (where M = 3 if `multimask_output=True` and M = 1
297
+ if `multimask_output=False`), the estimated IoU of each output mask.
298
+ - low_res_masks: [B, 1, H*4, W*4] shape, the best mask in `low_res_multimasks`.
299
+ If `multimask_output=True`, it's the mask with the highest IoU estimate.
300
+ If `multimask_output=False`, it's the same as `low_res_multimasks`.
301
+ - high_res_masks: [B, 1, H*16, W*16] shape, the best mask in `high_res_multimasks`.
302
+ If `multimask_output=True`, it's the mask with the highest IoU estimate.
303
+ If `multimask_output=False`, it's the same as `high_res_multimasks`.
304
+ - obj_ptr: [B, C] shape, the object pointer vector for the output mask, extracted
305
+ based on the output token from the SAM mask decoder.
306
+ """
307
+ B = backbone_features.size(0)
308
+ device = backbone_features.device
309
+ assert backbone_features.size(1) == self.sam_prompt_embed_dim
310
+ assert backbone_features.size(2) == self.sam_image_embedding_size
311
+ assert backbone_features.size(3) == self.sam_image_embedding_size
312
+
313
+ # a) Handle point prompts
314
+ if point_inputs is not None:
315
+ sam_point_coords = point_inputs["point_coords"]
316
+ sam_point_labels = point_inputs["point_labels"]
317
+ assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B
318
+ else:
319
+ # If no points are provide, pad with an empty point (with label -1)
320
+ sam_point_coords = torch.zeros(B, 1, 2, device=device)
321
+ sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device)
322
+
323
+ # b) Handle mask prompts
324
+ if mask_inputs is not None:
325
+ # If mask_inputs is provided, downsize it into low-res mask input if needed
326
+ # and feed it as a dense mask prompt into the SAM mask encoder
327
+ assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1)
328
+ if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size:
329
+ sam_mask_prompt = F.interpolate(
330
+ mask_inputs.float(),
331
+ size=self.sam_prompt_encoder.mask_input_size,
332
+ align_corners=False,
333
+ mode="bilinear",
334
+ antialias=True, # use antialias for downsampling
335
+ )
336
+ else:
337
+ sam_mask_prompt = mask_inputs
338
+ else:
339
+ # Otherwise, simply feed None (and SAM's prompt encoder will add
340
+ # a learned `no_mask_embed` to indicate no mask input in this case).
341
+ sam_mask_prompt = None
342
+
343
+ sparse_embeddings, dense_embeddings = self.sam_prompt_encoder(
344
+ points=(sam_point_coords, sam_point_labels),
345
+ boxes=None,
346
+ masks=sam_mask_prompt,
347
+ )
348
+ (
349
+ low_res_multimasks,
350
+ ious,
351
+ sam_output_tokens,
352
+ object_score_logits,
353
+ ) = self.sam_mask_decoder(
354
+ image_embeddings=backbone_features,
355
+ image_pe=self.sam_prompt_encoder.get_dense_pe(),
356
+ sparse_prompt_embeddings=sparse_embeddings,
357
+ dense_prompt_embeddings=dense_embeddings,
358
+ multimask_output=multimask_output,
359
+ repeat_image=False, # the image is already batched
360
+ high_res_features=high_res_features,
361
+ )
362
+ if self.pred_obj_scores:
363
+ is_obj_appearing = object_score_logits > 0
364
+
365
+ # Mask used for spatial memories is always a *hard* choice between obj and no obj,
366
+ # consistent with the actual mask prediction
367
+ low_res_multimasks = torch.where(
368
+ is_obj_appearing[:, None, None],
369
+ low_res_multimasks,
370
+ NO_OBJ_SCORE,
371
+ )
372
+
373
+ # convert masks from possibly bfloat16 (or float16) to float32
374
+ # (older PyTorch versions before 2.1 don't support `interpolate` on bf16)
375
+ low_res_multimasks = low_res_multimasks.float()
376
+ high_res_multimasks = F.interpolate(
377
+ low_res_multimasks,
378
+ size=(self.image_size, self.image_size),
379
+ mode="bilinear",
380
+ align_corners=False,
381
+ )
382
+
383
+ sam_output_token = sam_output_tokens[:, 0]
384
+ if multimask_output:
385
+ # take the best mask prediction (with the highest IoU estimation)
386
+ best_iou_inds = torch.argmax(ious, dim=-1)
387
+ batch_inds = torch.arange(B, device=device)
388
+ low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
389
+ high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1)
390
+ if sam_output_tokens.size(1) > 1:
391
+ sam_output_token = sam_output_tokens[batch_inds, best_iou_inds]
392
+ else:
393
+ low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks
394
+
395
+ # Extract object pointer from the SAM output token (with occlusion handling)
396
+ obj_ptr = self.obj_ptr_proj(sam_output_token)
397
+ if self.pred_obj_scores:
398
+ # Allow *soft* no obj ptr, unlike for masks
399
+ if self.soft_no_obj_ptr:
400
+ lambda_is_obj_appearing = object_score_logits.sigmoid()
401
+ else:
402
+ lambda_is_obj_appearing = is_obj_appearing.float()
403
+
404
+ if self.fixed_no_obj_ptr:
405
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
406
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
407
+
408
+ return (
409
+ low_res_multimasks,
410
+ high_res_multimasks,
411
+ ious,
412
+ low_res_masks,
413
+ high_res_masks,
414
+ obj_ptr,
415
+ object_score_logits,
416
+ )
417
+
418
+ def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs):
419
+ """
420
+ Directly turn binary `mask_inputs` into a output mask logits without using SAM.
421
+ (same input and output shapes as in _forward_sam_heads above).
422
+ """
423
+ # Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid).
424
+ out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05
425
+ mask_inputs_float = mask_inputs.float()
426
+ high_res_masks = mask_inputs_float * out_scale + out_bias
427
+ low_res_masks = F.interpolate(
428
+ high_res_masks,
429
+ size=(high_res_masks.size(-2) // 4, high_res_masks.size(-1) // 4),
430
+ align_corners=False,
431
+ mode="bilinear",
432
+ antialias=True, # use antialias for downsampling
433
+ )
434
+ # a dummy IoU prediction of all 1's under mask input
435
+ ious = mask_inputs.new_ones(mask_inputs.size(0), 1).float()
436
+ if not self.use_obj_ptrs_in_encoder:
437
+ # all zeros as a dummy object pointer (of shape [B, C])
438
+ obj_ptr = torch.zeros(
439
+ mask_inputs.size(0), self.hidden_dim, device=mask_inputs.device
440
+ )
441
+ else:
442
+ # produce an object pointer using the SAM decoder from the mask input
443
+ _, _, _, _, _, obj_ptr, _ = self._forward_sam_heads(
444
+ backbone_features=backbone_features,
445
+ mask_inputs=self.mask_downsample(mask_inputs_float),
446
+ high_res_features=high_res_features,
447
+ )
448
+ # In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem;
449
+ # Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying
450
+ # on the object_scores from the SAM decoder.
451
+ is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1)
452
+ is_obj_appearing = is_obj_appearing[..., None]
453
+ lambda_is_obj_appearing = is_obj_appearing.float()
454
+ object_score_logits = out_scale * lambda_is_obj_appearing + out_bias
455
+ if self.pred_obj_scores:
456
+ if self.fixed_no_obj_ptr:
457
+ obj_ptr = lambda_is_obj_appearing * obj_ptr
458
+ obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr
459
+
460
+ return (
461
+ low_res_masks,
462
+ high_res_masks,
463
+ ious,
464
+ low_res_masks,
465
+ high_res_masks,
466
+ obj_ptr,
467
+ object_score_logits,
468
+ )
469
+
470
+ def forward_image(self, img_batch: torch.Tensor):
471
+ """Get the image feature on the input batch."""
472
+ backbone_out = self.image_encoder(img_batch)
473
+ if self.use_high_res_features_in_sam:
474
+ # precompute projected level 0 and level 1 features in SAM decoder
475
+ # to avoid running it again on every SAM click
476
+ # NOTE: These are 1x1 convolutions
477
+ backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0(
478
+ backbone_out["backbone_fpn"][0]
479
+ )
480
+ backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1(
481
+ backbone_out["backbone_fpn"][1]
482
+ )
483
+ return backbone_out
484
+
485
+ def _prepare_backbone_features(self, backbone_out):
486
+ """Prepare and flatten visual features."""
487
+ backbone_out = backbone_out.copy()
488
+ assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"])
489
+ assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levels
490
+
491
+ feature_maps = backbone_out["backbone_fpn"][-self.num_feature_levels :]
492
+ vision_pos_embeds = backbone_out["vision_pos_enc"][-self.num_feature_levels :]
493
+
494
+ feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds]
495
+ # flatten NxCxHxW to HWxNxC
496
+ vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps]
497
+ vision_pos_embeds = [x.flatten(2).permute(2, 0, 1) for x in vision_pos_embeds]
498
+
499
+ return backbone_out, vision_feats, vision_pos_embeds, feat_sizes
500
+
501
+ def _prepare_memory_conditioned_features(
502
+ self,
503
+ frame_idx,
504
+ is_init_cond_frame,
505
+ current_vision_feats,
506
+ current_vision_pos_embeds,
507
+ feat_sizes,
508
+ output_dict,
509
+ num_frames,
510
+ track_in_reverse=False, # tracking in reverse time order (for demo usage)
511
+ ):
512
+ """Fuse the current frame's visual feature map with previous memory."""
513
+ B = current_vision_feats[-1].size(1) # batch size on this frame
514
+ C = self.hidden_dim
515
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
516
+ device = current_vision_feats[-1].device
517
+ # The case of `self.num_maskmem == 0` below is primarily used for reproducing SAM on images.
518
+ # In this case, we skip the fusion with any memory.
519
+ if self.num_maskmem == 0: # Disable memory and skip fusion
520
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
521
+ return pix_feat
522
+
523
+ num_obj_ptr_tokens = 0
524
+ tpos_sign_mul = -1 if track_in_reverse else 1
525
+ # Step 1: condition the visual features of the current frame on previous memories
526
+ if not is_init_cond_frame:
527
+ # Retrieve the memories encoded with the maskmem backbone
528
+ to_cat_memory, to_cat_memory_pos_embed = [], []
529
+ # Add conditioning frames's output first (all cond frames have t_pos=0 for
530
+ # when getting temporal positional embedding below)
531
+ assert len(output_dict["cond_frame_outputs"]) > 0
532
+ # Select a maximum number of temporally closest cond frames for cross attention
533
+ cond_outputs = output_dict["cond_frame_outputs"]
534
+ selected_cond_outputs, unselected_cond_outputs = select_closest_cond_frames(
535
+ frame_idx, cond_outputs, self.max_cond_frames_in_attn
536
+ )
537
+ t_pos_and_prevs = [(0, out) for out in selected_cond_outputs.values()]
538
+ # Add last (self.num_maskmem - 1) frames before current frame for non-conditioning memory
539
+ # the earliest one has t_pos=1 and the latest one has t_pos=self.num_maskmem-1
540
+ # We also allow taking the memory frame non-consecutively (with stride>1), in which case
541
+ # we take (self.num_maskmem - 2) frames among every stride-th frames plus the last frame.
542
+ stride = 1 if self.training else self.memory_temporal_stride_for_eval
543
+ for t_pos in range(1, self.num_maskmem):
544
+ t_rel = self.num_maskmem - t_pos # how many frames before current frame
545
+ if t_rel == 1:
546
+ # for t_rel == 1, we take the last frame (regardless of r)
547
+ if not track_in_reverse:
548
+ # the frame immediately before this frame (i.e. frame_idx - 1)
549
+ prev_frame_idx = frame_idx - t_rel
550
+ else:
551
+ # the frame immediately after this frame (i.e. frame_idx + 1)
552
+ prev_frame_idx = frame_idx + t_rel
553
+ else:
554
+ # for t_rel >= 2, we take the memory frame from every r-th frames
555
+ if not track_in_reverse:
556
+ # first find the nearest frame among every r-th frames before this frame
557
+ # for r=1, this would be (frame_idx - 2)
558
+ prev_frame_idx = ((frame_idx - 2) // stride) * stride
559
+ # then seek further among every r-th frames
560
+ prev_frame_idx = prev_frame_idx - (t_rel - 2) * stride
561
+ else:
562
+ # first find the nearest frame among every r-th frames after this frame
563
+ # for r=1, this would be (frame_idx + 2)
564
+ prev_frame_idx = -(-(frame_idx + 2) // stride) * stride
565
+ # then seek further among every r-th frames
566
+ prev_frame_idx = prev_frame_idx + (t_rel - 2) * stride
567
+ out = output_dict["non_cond_frame_outputs"].get(prev_frame_idx, None)
568
+ if out is None:
569
+ # If an unselected conditioning frame is among the last (self.num_maskmem - 1)
570
+ # frames, we still attend to it as if it's a non-conditioning frame.
571
+ out = unselected_cond_outputs.get(prev_frame_idx, None)
572
+ t_pos_and_prevs.append((t_pos, out))
573
+
574
+ for t_pos, prev in t_pos_and_prevs:
575
+ if prev is None:
576
+ continue # skip padding frames
577
+ # "maskmem_features" might have been offloaded to CPU in demo use cases,
578
+ # so we load it back to GPU (it's a no-op if it's already on GPU).
579
+ feats = prev["maskmem_features"].to(device, non_blocking=True)
580
+ to_cat_memory.append(feats.flatten(2).permute(2, 0, 1))
581
+ # Spatial positional encoding (it might have been offloaded to CPU in eval)
582
+ maskmem_enc = prev["maskmem_pos_enc"][-1].to(device)
583
+ maskmem_enc = maskmem_enc.flatten(2).permute(2, 0, 1)
584
+ # Temporal positional encoding
585
+ maskmem_enc = (
586
+ maskmem_enc + self.maskmem_tpos_enc[self.num_maskmem - t_pos - 1]
587
+ )
588
+ to_cat_memory_pos_embed.append(maskmem_enc)
589
+
590
+ # Construct the list of past object pointers
591
+ if self.use_obj_ptrs_in_encoder:
592
+ max_obj_ptrs_in_encoder = min(num_frames, self.max_obj_ptrs_in_encoder)
593
+ # First add those object pointers from selected conditioning frames
594
+ # (optionally, only include object pointers in the past during evaluation)
595
+ if not self.training and self.only_obj_ptrs_in_the_past_for_eval:
596
+ ptr_cond_outputs = {
597
+ t: out
598
+ for t, out in selected_cond_outputs.items()
599
+ if (t >= frame_idx if track_in_reverse else t <= frame_idx)
600
+ }
601
+ else:
602
+ ptr_cond_outputs = selected_cond_outputs
603
+ pos_and_ptrs = [
604
+ # Temporal pos encoding contains how far away each pointer is from current frame
605
+ (
606
+ (
607
+ (frame_idx - t) * tpos_sign_mul
608
+ if self.use_signed_tpos_enc_to_obj_ptrs
609
+ else abs(frame_idx - t)
610
+ ),
611
+ out["obj_ptr"],
612
+ )
613
+ for t, out in ptr_cond_outputs.items()
614
+ ]
615
+ # Add up to (max_obj_ptrs_in_encoder - 1) non-conditioning frames before current frame
616
+ for t_diff in range(1, max_obj_ptrs_in_encoder):
617
+ t = frame_idx + t_diff if track_in_reverse else frame_idx - t_diff
618
+ if t < 0 or (num_frames is not None and t >= num_frames):
619
+ break
620
+ out = output_dict["non_cond_frame_outputs"].get(
621
+ t, unselected_cond_outputs.get(t, None)
622
+ )
623
+ if out is not None:
624
+ pos_and_ptrs.append((t_diff, out["obj_ptr"]))
625
+ # If we have at least one object pointer, add them to the across attention
626
+ if len(pos_and_ptrs) > 0:
627
+ pos_list, ptrs_list = zip(*pos_and_ptrs)
628
+ # stack object pointers along dim=0 into [ptr_seq_len, B, C] shape
629
+ obj_ptrs = torch.stack(ptrs_list, dim=0)
630
+ # a temporal positional embedding based on how far each object pointer is from
631
+ # the current frame (sine embedding normalized by the max pointer num).
632
+ if self.add_tpos_enc_to_obj_ptrs:
633
+ t_diff_max = max_obj_ptrs_in_encoder - 1
634
+ tpos_dim = C if self.proj_tpos_enc_in_obj_ptrs else self.mem_dim
635
+ obj_pos = (
636
+ torch.tensor(pos_list)
637
+ .pin_memory()
638
+ .to(device=device, non_blocking=True)
639
+ )
640
+ obj_pos = get_1d_sine_pe(obj_pos / t_diff_max, dim=tpos_dim)
641
+ obj_pos = self.obj_ptr_tpos_proj(obj_pos)
642
+ obj_pos = obj_pos.unsqueeze(1).expand(-1, B, self.mem_dim)
643
+ else:
644
+ obj_pos = obj_ptrs.new_zeros(len(pos_list), B, self.mem_dim)
645
+ if self.mem_dim < C:
646
+ # split a pointer into (C // self.mem_dim) tokens for self.mem_dim < C
647
+ obj_ptrs = obj_ptrs.reshape(
648
+ -1, B, C // self.mem_dim, self.mem_dim
649
+ )
650
+ obj_ptrs = obj_ptrs.permute(0, 2, 1, 3).flatten(0, 1)
651
+ obj_pos = obj_pos.repeat_interleave(C // self.mem_dim, dim=0)
652
+ to_cat_memory.append(obj_ptrs)
653
+ to_cat_memory_pos_embed.append(obj_pos)
654
+ num_obj_ptr_tokens = obj_ptrs.shape[0]
655
+ else:
656
+ num_obj_ptr_tokens = 0
657
+ else:
658
+ # for initial conditioning frames, encode them without using any previous memory
659
+ if self.directly_add_no_mem_embed:
660
+ # directly add no-mem embedding (instead of using the transformer encoder)
661
+ pix_feat_with_mem = current_vision_feats[-1] + self.no_mem_embed
662
+ pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
663
+ return pix_feat_with_mem
664
+
665
+ # Use a dummy token on the first frame (to avoid empty memory input to tranformer encoder)
666
+ to_cat_memory = [self.no_mem_embed.expand(1, B, self.mem_dim)]
667
+ to_cat_memory_pos_embed = [self.no_mem_pos_enc.expand(1, B, self.mem_dim)]
668
+
669
+ # Step 2: Concatenate the memories and forward through the transformer encoder
670
+ memory = torch.cat(to_cat_memory, dim=0)
671
+ memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0)
672
+
673
+ current_vision_feats = [c.clone() for c in current_vision_feats]
674
+ current_vision_pos_embeds = [c.clone() for c in current_vision_pos_embeds]
675
+ memory = memory.clone()
676
+ memory_pos_embed = memory_pos_embed.clone()
677
+ pix_feat_with_mem = self.memory_attention(
678
+ curr=current_vision_feats,
679
+ curr_pos=current_vision_pos_embeds,
680
+ memory=memory,
681
+ memory_pos=memory_pos_embed,
682
+ num_obj_ptr_tokens=num_obj_ptr_tokens,
683
+ )
684
+ pix_feat_with_mem = pix_feat_with_mem.clone()
685
+ # reshape the output (HW)BC => BCHW
686
+ pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W)
687
+ return pix_feat_with_mem
688
+
689
+ def _encode_new_memory(
690
+ self,
691
+ current_vision_feats,
692
+ feat_sizes,
693
+ pred_masks_high_res,
694
+ object_score_logits,
695
+ is_mask_from_pts,
696
+ ):
697
+ """Encode the current image and its prediction into a memory feature."""
698
+ B = current_vision_feats[-1].size(1) # batch size on this frame
699
+ C = self.hidden_dim
700
+ H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size
701
+ # top-level feature, (HW)BC => BCHW
702
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W)
703
+ if self.non_overlap_masks_for_mem_enc and not self.training:
704
+ # optionally, apply non-overlapping constraints to the masks (it's applied
705
+ # in the batch dimension and should only be used during eval, where all
706
+ # the objects come from the same video under batch size 1).
707
+ pred_masks_high_res = self._apply_non_overlapping_constraints(
708
+ pred_masks_high_res
709
+ )
710
+ # scale the raw mask logits with a temperature before applying sigmoid
711
+ binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts
712
+ if binarize and not self.training:
713
+ mask_for_mem = (pred_masks_high_res > 0).float()
714
+ else:
715
+ # apply sigmoid on the raw mask logits to turn them into range (0, 1)
716
+ mask_for_mem = torch.sigmoid(pred_masks_high_res)
717
+ # apply scale and bias terms to the sigmoid probabilities
718
+ if self.sigmoid_scale_for_mem_enc != 1.0:
719
+ mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc
720
+ if self.sigmoid_bias_for_mem_enc != 0.0:
721
+ mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc
722
+ maskmem_out = self.memory_encoder(
723
+ pix_feat,
724
+ mask_for_mem,
725
+ skip_mask_sigmoid=True, # sigmoid already applied
726
+ )
727
+ maskmem_features = maskmem_out["vision_features"].clone()
728
+ maskmem_pos_enc = [m.clone() for m in maskmem_out["vision_pos_enc"]]
729
+ # add a no-object embedding to the spatial memory to indicate that the frame
730
+ # is predicted to be occluded (i.e. no object is appearing in the frame)
731
+ if self.no_obj_embed_spatial is not None:
732
+ is_obj_appearing = (object_score_logits > 0).float()
733
+ maskmem_features += (
734
+ 1 - is_obj_appearing[..., None, None]
735
+ ) * self.no_obj_embed_spatial[..., None, None].expand(
736
+ *maskmem_features.shape
737
+ )
738
+
739
+ return maskmem_features, maskmem_pos_enc
740
+
741
+ def _track_step(
742
+ self,
743
+ frame_idx,
744
+ is_init_cond_frame,
745
+ current_vision_feats,
746
+ current_vision_pos_embeds,
747
+ feat_sizes,
748
+ point_inputs,
749
+ mask_inputs,
750
+ output_dict,
751
+ num_frames,
752
+ track_in_reverse,
753
+ prev_sam_mask_logits,
754
+ ):
755
+ current_out = {"point_inputs": point_inputs, "mask_inputs": mask_inputs}
756
+ # High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW
757
+ if len(current_vision_feats) > 1:
758
+ high_res_features = [
759
+ x.permute(1, 2, 0).view(x.size(1), x.size(2), *s)
760
+ for x, s in zip(current_vision_feats[:-1], feat_sizes[:-1])
761
+ ]
762
+ else:
763
+ high_res_features = None
764
+ if mask_inputs is not None and self.use_mask_input_as_output_without_sam:
765
+ # When use_mask_input_as_output_without_sam=True, we directly output the mask input
766
+ # (see it as a GT mask) without using a SAM prompt encoder + mask decoder.
767
+ pix_feat = current_vision_feats[-1].permute(1, 2, 0)
768
+ pix_feat = pix_feat.view(-1, self.hidden_dim, *feat_sizes[-1])
769
+ sam_outputs = self._use_mask_as_output(
770
+ pix_feat, high_res_features, mask_inputs
771
+ )
772
+ else:
773
+ # fused the visual feature with previous memory features in the memory bank
774
+ pix_feat = self._prepare_memory_conditioned_features(
775
+ frame_idx=frame_idx,
776
+ is_init_cond_frame=is_init_cond_frame,
777
+ current_vision_feats=current_vision_feats[-1:],
778
+ current_vision_pos_embeds=current_vision_pos_embeds[-1:],
779
+ feat_sizes=feat_sizes[-1:],
780
+ output_dict=output_dict,
781
+ num_frames=num_frames,
782
+ track_in_reverse=track_in_reverse,
783
+ )
784
+ # apply SAM-style segmentation head
785
+ # here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder,
786
+ # e.g. in demo where such logits come from earlier interaction instead of correction sampling
787
+ # (in this case, any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead)
788
+ if prev_sam_mask_logits is not None:
789
+ assert point_inputs is not None and mask_inputs is None
790
+ mask_inputs = prev_sam_mask_logits
791
+ else:
792
+ assert mask_inputs is None
793
+ multimask_output = self._use_multimask(is_init_cond_frame, point_inputs)
794
+
795
+ assert multimask_output
796
+ if point_inputs is not None:
797
+ point_inputs = {k: point_inputs[k].contiguous() for k in point_inputs}
798
+ sam_outputs = self._forward_sam_heads(
799
+ backbone_features=pix_feat.contiguous(),
800
+ point_inputs=point_inputs,
801
+ mask_inputs=mask_inputs,
802
+ high_res_features=[h.contiguous() for h in high_res_features],
803
+ multimask_output=multimask_output,
804
+ )
805
+
806
+ return current_out, sam_outputs, high_res_features, pix_feat
807
+
808
+ def _encode_memory_in_output(
809
+ self,
810
+ current_vision_feats,
811
+ feat_sizes,
812
+ point_inputs,
813
+ run_mem_encoder,
814
+ high_res_masks,
815
+ object_score_logits,
816
+ current_out,
817
+ ):
818
+ if run_mem_encoder and self.num_maskmem > 0:
819
+ high_res_masks_for_mem_enc = high_res_masks
820
+ maskmem_features, maskmem_pos_enc = self._encode_new_memory(
821
+ current_vision_feats=current_vision_feats,
822
+ feat_sizes=feat_sizes,
823
+ pred_masks_high_res=high_res_masks_for_mem_enc,
824
+ object_score_logits=object_score_logits,
825
+ is_mask_from_pts=(point_inputs is not None),
826
+ )
827
+ current_out["maskmem_features"] = maskmem_features
828
+ current_out["maskmem_pos_enc"] = maskmem_pos_enc
829
+ else:
830
+ current_out["maskmem_features"] = None
831
+ current_out["maskmem_pos_enc"] = None
832
+
833
+ @torch.autograd.profiler.record_function("track_step")
834
+ def track_step(
835
+ self,
836
+ frame_idx,
837
+ is_init_cond_frame,
838
+ current_vision_feats,
839
+ current_vision_pos_embeds,
840
+ feat_sizes,
841
+ point_inputs,
842
+ mask_inputs,
843
+ output_dict,
844
+ num_frames,
845
+ track_in_reverse=False, # tracking in reverse time order (for demo usage)
846
+ # Whether to run the memory encoder on the predicted masks. Sometimes we might want
847
+ # to skip the memory encoder with `run_mem_encoder=False`. For example,
848
+ # in demo we might call `track_step` multiple times for each user click,
849
+ # and only encode the memory when the user finalizes their clicks. And in ablation
850
+ # settings like SAM training on static images, we don't need the memory encoder.
851
+ run_mem_encoder=True,
852
+ # The previously predicted SAM mask logits (which can be fed together with new clicks in demo).
853
+ prev_sam_mask_logits=None,
854
+ ):
855
+ current_out, sam_outputs, _, _ = self._track_step(
856
+ frame_idx,
857
+ is_init_cond_frame,
858
+ current_vision_feats,
859
+ current_vision_pos_embeds,
860
+ feat_sizes,
861
+ point_inputs,
862
+ mask_inputs,
863
+ output_dict,
864
+ num_frames,
865
+ track_in_reverse,
866
+ prev_sam_mask_logits,
867
+ )
868
+
869
+ (
870
+ _,
871
+ _,
872
+ _,
873
+ low_res_masks,
874
+ high_res_masks,
875
+ obj_ptr,
876
+ object_score_logits,
877
+ ) = sam_outputs
878
+
879
+ current_out["pred_masks"] = low_res_masks.clone()
880
+ current_out["pred_masks_high_res"] = high_res_masks.clone()
881
+ current_out["obj_ptr"] = obj_ptr.clone()
882
+ if not self.training:
883
+ # Only add this in inference (to avoid unused param in activation checkpointing;
884
+ # it's mainly used in the demo to encode spatial memories w/ consolidated masks)
885
+ current_out["object_score_logits"] = object_score_logits.clone()
886
+
887
+ # Finally run the memory encoder on the predicted mask to encode
888
+ # it into a new memory feature (that can be used in future frames)
889
+ self._encode_memory_in_output(
890
+ current_vision_feats,
891
+ feat_sizes,
892
+ point_inputs,
893
+ run_mem_encoder,
894
+ high_res_masks,
895
+ object_score_logits.clone(),
896
+ current_out,
897
+ )
898
+
899
+ return current_out
900
+
901
+ def _use_multimask(self, is_init_cond_frame, point_inputs):
902
+ """Whether to use multimask output in the SAM head."""
903
+ num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1)
904
+ multimask_output = (
905
+ self.multimask_output_in_sam
906
+ and (is_init_cond_frame or self.multimask_output_for_tracking)
907
+ and (self.multimask_min_pt_num <= num_pts <= self.multimask_max_pt_num)
908
+ )
909
+ return multimask_output
910
+
911
+ def _apply_non_overlapping_constraints(self, pred_masks):
912
+ """
913
+ Apply non-overlapping constraints to the object scores in pred_masks. Here we
914
+ keep only the highest scoring object at each spatial location in pred_masks.
915
+ """
916
+ batch_size = pred_masks.size(0)
917
+ if batch_size == 1:
918
+ return pred_masks
919
+
920
+ device = pred_masks.device
921
+ # "max_obj_inds": object index of the object with the highest score at each location
922
+ max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True)
923
+ # "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks`
924
+ batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None]
925
+ keep = max_obj_inds == batch_obj_inds
926
+ # suppress overlapping regions' scores below -10.0 so that the foreground regions
927
+ # don't overlap (here sigmoid(-10.0)=4.5398e-05)
928
+ pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0))
929
+ return pred_masks
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam2_utils.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+
8
+ import copy
9
+ from typing import Tuple
10
+
11
+ import numpy as np
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+
16
+ from torchao._models.sam2.utils.misc import mask_to_box
17
+
18
+
19
+ def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num):
20
+ """
21
+ Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs`
22
+ that are temporally closest to the current frame at `frame_idx`. Here, we take
23
+ - a) the closest conditioning frame before `frame_idx` (if any);
24
+ - b) the closest conditioning frame after `frame_idx` (if any);
25
+ - c) any other temporally closest conditioning frames until reaching a total
26
+ of `max_cond_frame_num` conditioning frames.
27
+
28
+ Outputs:
29
+ - selected_outputs: selected items (keys & values) from `cond_frame_outputs`.
30
+ - unselected_outputs: items (keys & values) not selected in `cond_frame_outputs`.
31
+ """
32
+ if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num:
33
+ selected_outputs = cond_frame_outputs
34
+ unselected_outputs = {}
35
+ else:
36
+ assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames"
37
+ selected_outputs = {}
38
+
39
+ # the closest conditioning frame before `frame_idx` (if any)
40
+ idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None)
41
+ if idx_before is not None:
42
+ selected_outputs[idx_before] = cond_frame_outputs[idx_before]
43
+
44
+ # the closest conditioning frame after `frame_idx` (if any)
45
+ idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None)
46
+ if idx_after is not None:
47
+ selected_outputs[idx_after] = cond_frame_outputs[idx_after]
48
+
49
+ # add other temporally closest conditioning frames until reaching a total
50
+ # of `max_cond_frame_num` conditioning frames.
51
+ num_remain = max_cond_frame_num - len(selected_outputs)
52
+ inds_remain = sorted(
53
+ (t for t in cond_frame_outputs if t not in selected_outputs),
54
+ key=lambda x: abs(x - frame_idx),
55
+ )[:num_remain]
56
+ selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain)
57
+ unselected_outputs = {
58
+ t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs
59
+ }
60
+
61
+ return selected_outputs, unselected_outputs
62
+
63
+
64
+ def get_1d_sine_pe(pos_inds, dim, temperature=10000):
65
+ """
66
+ Get 1D sine positional embedding as in the original Transformer paper.
67
+ """
68
+ pe_dim = dim // 2
69
+ dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device)
70
+ dim_t = temperature ** (2 * (dim_t // 2) / pe_dim)
71
+
72
+ pos_embed = pos_inds.unsqueeze(-1) / dim_t
73
+ pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1)
74
+ return pos_embed
75
+
76
+
77
+ def get_activation_fn(activation):
78
+ """Return an activation function given a string"""
79
+ if activation == "relu":
80
+ return F.relu
81
+ if activation == "gelu":
82
+ return F.gelu
83
+ if activation == "glu":
84
+ return F.glu
85
+ raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
86
+
87
+
88
+ def get_clones(module, N):
89
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
90
+
91
+
92
+ class DropPath(nn.Module):
93
+ # adapted from https://github.com/huggingface/pytorch-image-models/blob/main/timm/layers/drop.py
94
+ def __init__(self, drop_prob=0.0, scale_by_keep=True):
95
+ super(DropPath, self).__init__()
96
+ self.drop_prob = drop_prob
97
+ self.scale_by_keep = scale_by_keep
98
+
99
+ def forward(self, x):
100
+ if self.drop_prob == 0.0 or not self.training:
101
+ return x
102
+ keep_prob = 1 - self.drop_prob
103
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1)
104
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
105
+ if keep_prob > 0.0 and self.scale_by_keep:
106
+ random_tensor.div_(keep_prob)
107
+ return x * random_tensor
108
+
109
+
110
+ # Lightly adapted from
111
+ # https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
112
+ class MLP(nn.Module):
113
+ def __init__(
114
+ self,
115
+ input_dim: int,
116
+ hidden_dim: int,
117
+ output_dim: int,
118
+ num_layers: int,
119
+ activation: nn.Module = nn.ReLU,
120
+ sigmoid_output: bool = False,
121
+ ) -> None:
122
+ super().__init__()
123
+ self.num_layers = num_layers
124
+ h = [hidden_dim] * (num_layers - 1)
125
+ self.layers = nn.ModuleList(
126
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
127
+ )
128
+ self.sigmoid_output = sigmoid_output
129
+ self.act = activation()
130
+
131
+ def forward(self, x):
132
+ for i, layer in enumerate(self.layers):
133
+ x = self.act(layer(x)) if i < self.num_layers - 1 else layer(x)
134
+ if self.sigmoid_output:
135
+ x = F.sigmoid(x)
136
+ return x
137
+
138
+
139
+ # From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
140
+ # Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
141
+ class LayerNorm2d(nn.Module):
142
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
143
+ super().__init__()
144
+ self.weight = nn.Parameter(torch.ones(num_channels))
145
+ self.bias = nn.Parameter(torch.zeros(num_channels))
146
+ self.eps = eps
147
+
148
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
149
+ u = x.mean(1, keepdim=True)
150
+ s = (x - u).pow(2).mean(1, keepdim=True)
151
+ x = (x - u) / torch.sqrt(s + self.eps)
152
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
153
+ return x
154
+
155
+
156
+ def sample_box_points(
157
+ masks: torch.Tensor,
158
+ noise: float = 0.1, # SAM default
159
+ noise_bound: int = 20, # SAM default
160
+ top_left_label: int = 2,
161
+ bottom_right_label: int = 3,
162
+ ) -> Tuple[np.array, np.array]:
163
+ """
164
+ Sample a noised version of the top left and bottom right corners of a given `bbox`
165
+
166
+ Inputs:
167
+ - masks: [B, 1, H,W] boxes, dtype=torch.Tensor
168
+ - noise: noise as a fraction of box width and height, dtype=float
169
+ - noise_bound: maximum amount of noise (in pure pixesl), dtype=int
170
+
171
+ Returns:
172
+ - box_coords: [B, num_pt, 2], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.float
173
+ - box_labels: [B, num_pt], label 2 is reserverd for top left and 3 for bottom right corners, dtype=torch.int32
174
+ """
175
+ device = masks.device
176
+ box_coords = mask_to_box(masks)
177
+ B, _, H, W = masks.shape
178
+ box_labels = torch.tensor(
179
+ [top_left_label, bottom_right_label], dtype=torch.int, device=device
180
+ ).repeat(B)
181
+ if noise > 0.0:
182
+ if not isinstance(noise_bound, torch.Tensor):
183
+ noise_bound = torch.tensor(noise_bound, device=device)
184
+ bbox_w = box_coords[..., 2] - box_coords[..., 0]
185
+ bbox_h = box_coords[..., 3] - box_coords[..., 1]
186
+ max_dx = torch.min(bbox_w * noise, noise_bound)
187
+ max_dy = torch.min(bbox_h * noise, noise_bound)
188
+ box_noise = 2 * torch.rand(B, 1, 4, device=device) - 1
189
+ box_noise = box_noise * torch.stack((max_dx, max_dy, max_dx, max_dy), dim=-1)
190
+
191
+ box_coords = box_coords + box_noise
192
+ img_bounds = (
193
+ torch.tensor([W, H, W, H], device=device) - 1
194
+ ) # uncentered pixel coords
195
+ box_coords.clamp_(torch.zeros_like(img_bounds), img_bounds) # In place clamping
196
+
197
+ box_coords = box_coords.reshape(-1, 2, 2) # always 2 points
198
+ box_labels = box_labels.reshape(-1, 2)
199
+ return box_coords, box_labels
200
+
201
+
202
+ def sample_random_points_from_errors(gt_masks, pred_masks, num_pt=1):
203
+ """
204
+ Sample `num_pt` random points (along with their labels) independently from the error regions.
205
+
206
+ Inputs:
207
+ - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
208
+ - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
209
+ - num_pt: int, number of points to sample independently for each of the B error maps
210
+
211
+ Outputs:
212
+ - points: [B, num_pt, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
213
+ - labels: [B, num_pt], dtype=torch.int32, where 1 means positive clicks and 0 means
214
+ negative clicks
215
+ """
216
+ if pred_masks is None: # if pred_masks is not provided, treat it as empty
217
+ pred_masks = torch.zeros_like(gt_masks)
218
+ assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
219
+ assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
220
+ assert num_pt >= 0
221
+
222
+ B, _, H_im, W_im = gt_masks.shape
223
+ device = gt_masks.device
224
+
225
+ # false positive region, a new point sampled in this region should have
226
+ # negative label to correct the FP error
227
+ fp_masks = ~gt_masks & pred_masks
228
+ # false negative region, a new point sampled in this region should have
229
+ # positive label to correct the FN error
230
+ fn_masks = gt_masks & ~pred_masks
231
+ # whether the prediction completely match the ground-truth on each mask
232
+ all_correct = torch.all((gt_masks == pred_masks).flatten(2), dim=2)
233
+ all_correct = all_correct[..., None, None]
234
+
235
+ # channel 0 is FP map, while channel 1 is FN map
236
+ pts_noise = torch.rand(B, num_pt, H_im, W_im, 2, device=device)
237
+ # sample a negative new click from FP region or a positive new click
238
+ # from FN region, depend on where the maximum falls,
239
+ # and in case the predictions are all correct (no FP or FN), we just
240
+ # sample a negative click from the background region
241
+ pts_noise[..., 0] *= fp_masks | (all_correct & ~gt_masks)
242
+ pts_noise[..., 1] *= fn_masks
243
+ pts_idx = pts_noise.flatten(2).argmax(dim=2)
244
+ labels = (pts_idx % 2).to(torch.int32)
245
+ pts_idx = pts_idx // 2
246
+ pts_x = pts_idx % W_im
247
+ pts_y = pts_idx // W_im
248
+ points = torch.stack([pts_x, pts_y], dim=2).to(torch.float)
249
+ return points, labels
250
+
251
+
252
+ def sample_one_point_from_error_center(gt_masks, pred_masks, padding=True):
253
+ """
254
+ Sample 1 random point (along with its label) from the center of each error region,
255
+ that is, the point with the largest distance to the boundary of each error region.
256
+ This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py
257
+
258
+ Inputs:
259
+ - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool
260
+ - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None
261
+ - padding: if True, pad with boundary of 1 px for distance transform
262
+
263
+ Outputs:
264
+ - points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point
265
+ - labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks
266
+ """
267
+ import cv2
268
+
269
+ if pred_masks is None:
270
+ pred_masks = torch.zeros_like(gt_masks)
271
+ assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1
272
+ assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape
273
+
274
+ B, _, _, W_im = gt_masks.shape
275
+ device = gt_masks.device
276
+
277
+ # false positive region, a new point sampled in this region should have
278
+ # negative label to correct the FP error
279
+ fp_masks = ~gt_masks & pred_masks
280
+ # false negative region, a new point sampled in this region should have
281
+ # positive label to correct the FN error
282
+ fn_masks = gt_masks & ~pred_masks
283
+
284
+ fp_masks = fp_masks.cpu().numpy()
285
+ fn_masks = fn_masks.cpu().numpy()
286
+ points = torch.zeros(B, 1, 2, dtype=torch.float)
287
+ labels = torch.ones(B, 1, dtype=torch.int32)
288
+ for b in range(B):
289
+ fn_mask = fn_masks[b, 0]
290
+ fp_mask = fp_masks[b, 0]
291
+ if padding:
292
+ fn_mask = np.pad(fn_mask, ((1, 1), (1, 1)), "constant")
293
+ fp_mask = np.pad(fp_mask, ((1, 1), (1, 1)), "constant")
294
+ # compute the distance of each point in FN/FP region to its boundary
295
+ fn_mask_dt = cv2.distanceTransform(fn_mask.astype(np.uint8), cv2.DIST_L2, 0)
296
+ fp_mask_dt = cv2.distanceTransform(fp_mask.astype(np.uint8), cv2.DIST_L2, 0)
297
+ if padding:
298
+ fn_mask_dt = fn_mask_dt[1:-1, 1:-1]
299
+ fp_mask_dt = fp_mask_dt[1:-1, 1:-1]
300
+
301
+ # take the point in FN/FP region with the largest distance to its boundary
302
+ fn_mask_dt_flat = fn_mask_dt.reshape(-1)
303
+ fp_mask_dt_flat = fp_mask_dt.reshape(-1)
304
+ fn_argmax = np.argmax(fn_mask_dt_flat)
305
+ fp_argmax = np.argmax(fp_mask_dt_flat)
306
+ is_positive = fn_mask_dt_flat[fn_argmax] > fp_mask_dt_flat[fp_argmax]
307
+ pt_idx = fn_argmax if is_positive else fp_argmax
308
+ points[b, 0, 0] = pt_idx % W_im # x
309
+ points[b, 0, 1] = pt_idx // W_im # y
310
+ labels[b, 0] = int(is_positive)
311
+
312
+ points = points.to(device)
313
+ labels = labels.to(device)
314
+ return points, labels
315
+
316
+
317
+ def get_next_point(gt_masks, pred_masks, method):
318
+ if method == "uniform":
319
+ return sample_random_points_from_errors(gt_masks, pred_masks)
320
+ elif method == "center":
321
+ return sample_one_point_from_error_center(gt_masks, pred_masks)
322
+ else:
323
+ raise ValueError(f"unknown sampling method {method}")
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_b+.yaml ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base
6
+ image_encoder:
7
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 1
9
+ trunk:
10
+ _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera
11
+ embed_dim: 112
12
+ num_heads: 2
13
+ neck:
14
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck
15
+ position_encoding:
16
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
17
+ num_pos_feats: 256
18
+ normalize: true
19
+ scale: null
20
+ temperature: 10000
21
+ d_model: 256
22
+ backbone_channel_list: [896, 448, 224, 112]
23
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
24
+ fpn_interp_model: nearest
25
+
26
+ memory_attention:
27
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention
28
+ d_model: 256
29
+ pos_enc_at_input: true
30
+ layer:
31
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer
32
+ activation: relu
33
+ dim_feedforward: 2048
34
+ dropout: 0.1
35
+ pos_enc_at_attn: false
36
+ self_attention:
37
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
38
+ rope_theta: 10000.0
39
+ feat_sizes: [32, 32]
40
+ embedding_dim: 256
41
+ num_heads: 1
42
+ downsample_rate: 1
43
+ dropout: 0.1
44
+ d_model: 256
45
+ pos_enc_at_cross_attn_keys: true
46
+ pos_enc_at_cross_attn_queries: false
47
+ cross_attention:
48
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
49
+ rope_theta: 10000.0
50
+ feat_sizes: [32, 32]
51
+ rope_k_repeat: True
52
+ embedding_dim: 256
53
+ num_heads: 1
54
+ downsample_rate: 1
55
+ dropout: 0.1
56
+ kv_in_dim: 64
57
+ num_layers: 4
58
+
59
+ memory_encoder:
60
+ _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder
61
+ out_dim: 64
62
+ position_encoding:
63
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
64
+ num_pos_feats: 64
65
+ normalize: true
66
+ scale: null
67
+ temperature: 10000
68
+ mask_downsampler:
69
+ _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler
70
+ kernel_size: 3
71
+ stride: 2
72
+ padding: 1
73
+ fuser:
74
+ _target_: torchao._models.sam2.modeling.memory_encoder.Fuser
75
+ layer:
76
+ _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock
77
+ dim: 256
78
+ kernel_size: 7
79
+ padding: 3
80
+ layer_scale_init_value: 1e-6
81
+ use_dwconv: True # depth-wise convs
82
+ num_layers: 2
83
+
84
+ num_maskmem: 7
85
+ image_size: 1024
86
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
87
+ sigmoid_scale_for_mem_enc: 20.0
88
+ sigmoid_bias_for_mem_enc: -10.0
89
+ use_mask_input_as_output_without_sam: true
90
+ # Memory
91
+ directly_add_no_mem_embed: true
92
+ # use high-resolution feature map in the SAM mask decoder
93
+ use_high_res_features_in_sam: true
94
+ # output 3 masks on the first click on initial conditioning frames
95
+ multimask_output_in_sam: true
96
+ # SAM heads
97
+ iou_prediction_use_sigmoid: True
98
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
99
+ use_obj_ptrs_in_encoder: true
100
+ add_tpos_enc_to_obj_ptrs: false
101
+ only_obj_ptrs_in_the_past_for_eval: true
102
+ # object occlusion prediction
103
+ pred_obj_scores: true
104
+ pred_obj_scores_mlp: true
105
+ fixed_no_obj_ptr: true
106
+ # multimask tracking settings
107
+ multimask_output_for_tracking: true
108
+ use_multimask_token_for_obj_ptr: true
109
+ multimask_min_pt_num: 0
110
+ multimask_max_pt_num: 1
111
+ use_mlp_for_obj_ptr_proj: true
112
+ # Compilation flag
113
+ compile_image_encoder: False
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_l.yaml ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base
6
+ image_encoder:
7
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 1
9
+ trunk:
10
+ _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera
11
+ embed_dim: 144
12
+ num_heads: 2
13
+ stages: [2, 6, 36, 4]
14
+ global_att_blocks: [23, 33, 43]
15
+ window_pos_embed_bkg_spatial_size: [7, 7]
16
+ window_spec: [8, 4, 16, 8]
17
+ neck:
18
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck
19
+ position_encoding:
20
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
21
+ num_pos_feats: 256
22
+ normalize: true
23
+ scale: null
24
+ temperature: 10000
25
+ d_model: 256
26
+ backbone_channel_list: [1152, 576, 288, 144]
27
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
28
+ fpn_interp_model: nearest
29
+
30
+ memory_attention:
31
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention
32
+ d_model: 256
33
+ pos_enc_at_input: true
34
+ layer:
35
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer
36
+ activation: relu
37
+ dim_feedforward: 2048
38
+ dropout: 0.1
39
+ pos_enc_at_attn: false
40
+ self_attention:
41
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
42
+ rope_theta: 10000.0
43
+ feat_sizes: [32, 32]
44
+ embedding_dim: 256
45
+ num_heads: 1
46
+ downsample_rate: 1
47
+ dropout: 0.1
48
+ d_model: 256
49
+ pos_enc_at_cross_attn_keys: true
50
+ pos_enc_at_cross_attn_queries: false
51
+ cross_attention:
52
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
53
+ rope_theta: 10000.0
54
+ feat_sizes: [32, 32]
55
+ rope_k_repeat: True
56
+ embedding_dim: 256
57
+ num_heads: 1
58
+ downsample_rate: 1
59
+ dropout: 0.1
60
+ kv_in_dim: 64
61
+ num_layers: 4
62
+
63
+ memory_encoder:
64
+ _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder
65
+ out_dim: 64
66
+ position_encoding:
67
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
68
+ num_pos_feats: 64
69
+ normalize: true
70
+ scale: null
71
+ temperature: 10000
72
+ mask_downsampler:
73
+ _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler
74
+ kernel_size: 3
75
+ stride: 2
76
+ padding: 1
77
+ fuser:
78
+ _target_: torchao._models.sam2.modeling.memory_encoder.Fuser
79
+ layer:
80
+ _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock
81
+ dim: 256
82
+ kernel_size: 7
83
+ padding: 3
84
+ layer_scale_init_value: 1e-6
85
+ use_dwconv: True # depth-wise convs
86
+ num_layers: 2
87
+
88
+ num_maskmem: 7
89
+ image_size: 1024
90
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
91
+ sigmoid_scale_for_mem_enc: 20.0
92
+ sigmoid_bias_for_mem_enc: -10.0
93
+ use_mask_input_as_output_without_sam: true
94
+ # Memory
95
+ directly_add_no_mem_embed: true
96
+ # use high-resolution feature map in the SAM mask decoder
97
+ use_high_res_features_in_sam: true
98
+ # output 3 masks on the first click on initial conditioning frames
99
+ multimask_output_in_sam: true
100
+ # SAM heads
101
+ iou_prediction_use_sigmoid: True
102
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
103
+ use_obj_ptrs_in_encoder: true
104
+ add_tpos_enc_to_obj_ptrs: false
105
+ only_obj_ptrs_in_the_past_for_eval: true
106
+ # object occlusion prediction
107
+ pred_obj_scores: true
108
+ pred_obj_scores_mlp: true
109
+ fixed_no_obj_ptr: true
110
+ # multimask tracking settings
111
+ multimask_output_for_tracking: true
112
+ use_multimask_token_for_obj_ptr: true
113
+ multimask_min_pt_num: 0
114
+ multimask_max_pt_num: 1
115
+ use_mlp_for_obj_ptr_proj: true
116
+ # Compilation flag
117
+ compile_image_encoder: False
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_s.yaml ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base
6
+ image_encoder:
7
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 1
9
+ trunk:
10
+ _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera
11
+ embed_dim: 96
12
+ num_heads: 1
13
+ stages: [1, 2, 11, 2]
14
+ global_att_blocks: [7, 10, 13]
15
+ window_pos_embed_bkg_spatial_size: [7, 7]
16
+ neck:
17
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck
18
+ position_encoding:
19
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
20
+ num_pos_feats: 256
21
+ normalize: true
22
+ scale: null
23
+ temperature: 10000
24
+ d_model: 256
25
+ backbone_channel_list: [768, 384, 192, 96]
26
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
27
+ fpn_interp_model: nearest
28
+
29
+ memory_attention:
30
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention
31
+ d_model: 256
32
+ pos_enc_at_input: true
33
+ layer:
34
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer
35
+ activation: relu
36
+ dim_feedforward: 2048
37
+ dropout: 0.1
38
+ pos_enc_at_attn: false
39
+ self_attention:
40
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
41
+ rope_theta: 10000.0
42
+ feat_sizes: [32, 32]
43
+ embedding_dim: 256
44
+ num_heads: 1
45
+ downsample_rate: 1
46
+ dropout: 0.1
47
+ d_model: 256
48
+ pos_enc_at_cross_attn_keys: true
49
+ pos_enc_at_cross_attn_queries: false
50
+ cross_attention:
51
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
52
+ rope_theta: 10000.0
53
+ feat_sizes: [32, 32]
54
+ rope_k_repeat: True
55
+ embedding_dim: 256
56
+ num_heads: 1
57
+ downsample_rate: 1
58
+ dropout: 0.1
59
+ kv_in_dim: 64
60
+ num_layers: 4
61
+
62
+ memory_encoder:
63
+ _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder
64
+ out_dim: 64
65
+ position_encoding:
66
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
67
+ num_pos_feats: 64
68
+ normalize: true
69
+ scale: null
70
+ temperature: 10000
71
+ mask_downsampler:
72
+ _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler
73
+ kernel_size: 3
74
+ stride: 2
75
+ padding: 1
76
+ fuser:
77
+ _target_: torchao._models.sam2.modeling.memory_encoder.Fuser
78
+ layer:
79
+ _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock
80
+ dim: 256
81
+ kernel_size: 7
82
+ padding: 3
83
+ layer_scale_init_value: 1e-6
84
+ use_dwconv: True # depth-wise convs
85
+ num_layers: 2
86
+
87
+ num_maskmem: 7
88
+ image_size: 1024
89
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
90
+ sigmoid_scale_for_mem_enc: 20.0
91
+ sigmoid_bias_for_mem_enc: -10.0
92
+ use_mask_input_as_output_without_sam: true
93
+ # Memory
94
+ directly_add_no_mem_embed: true
95
+ # use high-resolution feature map in the SAM mask decoder
96
+ use_high_res_features_in_sam: true
97
+ # output 3 masks on the first click on initial conditioning frames
98
+ multimask_output_in_sam: true
99
+ # SAM heads
100
+ iou_prediction_use_sigmoid: True
101
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
102
+ use_obj_ptrs_in_encoder: true
103
+ add_tpos_enc_to_obj_ptrs: false
104
+ only_obj_ptrs_in_the_past_for_eval: true
105
+ # object occlusion prediction
106
+ pred_obj_scores: true
107
+ pred_obj_scores_mlp: true
108
+ fixed_no_obj_ptr: true
109
+ # multimask tracking settings
110
+ multimask_output_for_tracking: true
111
+ use_multimask_token_for_obj_ptr: true
112
+ multimask_min_pt_num: 0
113
+ multimask_max_pt_num: 1
114
+ use_mlp_for_obj_ptr_proj: true
115
+ # Compilation flag
116
+ compile_image_encoder: False
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_t.yaml ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # @package _global_
2
+
3
+ # Model
4
+ model:
5
+ _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base
6
+ image_encoder:
7
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder
8
+ scalp: 1
9
+ trunk:
10
+ _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera
11
+ embed_dim: 96
12
+ num_heads: 1
13
+ stages: [1, 2, 7, 2]
14
+ global_att_blocks: [5, 7, 9]
15
+ window_pos_embed_bkg_spatial_size: [7, 7]
16
+ neck:
17
+ _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck
18
+ position_encoding:
19
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
20
+ num_pos_feats: 256
21
+ normalize: true
22
+ scale: null
23
+ temperature: 10000
24
+ d_model: 256
25
+ backbone_channel_list: [768, 384, 192, 96]
26
+ fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features
27
+ fpn_interp_model: nearest
28
+
29
+ memory_attention:
30
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention
31
+ d_model: 256
32
+ pos_enc_at_input: true
33
+ layer:
34
+ _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer
35
+ activation: relu
36
+ dim_feedforward: 2048
37
+ dropout: 0.1
38
+ pos_enc_at_attn: false
39
+ self_attention:
40
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
41
+ rope_theta: 10000.0
42
+ feat_sizes: [32, 32]
43
+ embedding_dim: 256
44
+ num_heads: 1
45
+ downsample_rate: 1
46
+ dropout: 0.1
47
+ d_model: 256
48
+ pos_enc_at_cross_attn_keys: true
49
+ pos_enc_at_cross_attn_queries: false
50
+ cross_attention:
51
+ _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention
52
+ rope_theta: 10000.0
53
+ feat_sizes: [32, 32]
54
+ rope_k_repeat: True
55
+ embedding_dim: 256
56
+ num_heads: 1
57
+ downsample_rate: 1
58
+ dropout: 0.1
59
+ kv_in_dim: 64
60
+ num_layers: 4
61
+
62
+ memory_encoder:
63
+ _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder
64
+ out_dim: 64
65
+ position_encoding:
66
+ _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine
67
+ num_pos_feats: 64
68
+ normalize: true
69
+ scale: null
70
+ temperature: 10000
71
+ mask_downsampler:
72
+ _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler
73
+ kernel_size: 3
74
+ stride: 2
75
+ padding: 1
76
+ fuser:
77
+ _target_: torchao._models.sam2.modeling.memory_encoder.Fuser
78
+ layer:
79
+ _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock
80
+ dim: 256
81
+ kernel_size: 7
82
+ padding: 3
83
+ layer_scale_init_value: 1e-6
84
+ use_dwconv: True # depth-wise convs
85
+ num_layers: 2
86
+
87
+ num_maskmem: 7
88
+ image_size: 1024
89
+ # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask
90
+ # SAM decoder
91
+ sigmoid_scale_for_mem_enc: 20.0
92
+ sigmoid_bias_for_mem_enc: -10.0
93
+ use_mask_input_as_output_without_sam: true
94
+ # Memory
95
+ directly_add_no_mem_embed: true
96
+ # use high-resolution feature map in the SAM mask decoder
97
+ use_high_res_features_in_sam: true
98
+ # output 3 masks on the first click on initial conditioning frames
99
+ multimask_output_in_sam: true
100
+ # SAM heads
101
+ iou_prediction_use_sigmoid: True
102
+ # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder
103
+ use_obj_ptrs_in_encoder: true
104
+ add_tpos_enc_to_obj_ptrs: false
105
+ only_obj_ptrs_in_the_past_for_eval: true
106
+ # object occlusion prediction
107
+ pred_obj_scores: true
108
+ pred_obj_scores_mlp: true
109
+ fixed_no_obj_ptr: true
110
+ # multimask tracking settings
111
+ multimask_output_for_tracking: true
112
+ use_multimask_token_for_obj_ptr: true
113
+ multimask_min_pt_num: 0
114
+ multimask_max_pt_num: 1
115
+ use_mlp_for_obj_ptr_proj: true
116
+ # Compilation flag
117
+ # HieraT does not currently support compilation, should always be set to False
118
+ compile_image_encoder: False
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_image_predictor.py ADDED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import logging
8
+ from typing import List, Optional, Tuple, Union
9
+
10
+ import numpy as np
11
+ import torch
12
+ from PIL.Image import Image
13
+
14
+ from torchao._models.sam2.modeling.sam2_base import SAM2Base
15
+ from torchao._models.sam2.utils.misc import get_image_size
16
+ from torchao._models.sam2.utils.transforms import SAM2Transforms
17
+
18
+
19
+ class SAM2ImagePredictor(torch.nn.Module):
20
+ def __init__(
21
+ self,
22
+ sam_model: SAM2Base,
23
+ mask_threshold=0.0,
24
+ max_hole_area=0.0,
25
+ max_sprinkle_area=0.0,
26
+ **kwargs,
27
+ ) -> None:
28
+ """
29
+ Uses SAM-2 to calculate the image embedding for an image, and then
30
+ allow repeated, efficient mask prediction given prompts.
31
+
32
+ Arguments:
33
+ sam_model (Sam-2): The model to use for mask prediction.
34
+ mask_threshold (float): The threshold to use when converting mask logits
35
+ to binary masks. Masks are thresholded at 0 by default.
36
+ max_hole_area (int): If max_hole_area > 0, we fill small holes in up to
37
+ the maximum area of max_hole_area in low_res_masks.
38
+ max_sprinkle_area (int): If max_sprinkle_area > 0, we remove small sprinkles up to
39
+ the maximum area of max_sprinkle_area in low_res_masks.
40
+ """
41
+ super().__init__()
42
+ self.model = sam_model
43
+ self._transforms = SAM2Transforms(
44
+ resolution=self.model.image_size,
45
+ mask_threshold=mask_threshold,
46
+ max_hole_area=max_hole_area,
47
+ max_sprinkle_area=max_sprinkle_area,
48
+ )
49
+
50
+ # Predictor state
51
+ self._is_image_set = False
52
+ self._features = None
53
+ self._orig_hw = None
54
+ # Whether the predictor is set for single image or a batch of images
55
+ self._is_batch = False
56
+
57
+ # Predictor config
58
+ self.mask_threshold = mask_threshold
59
+
60
+ # Spatial dim for backbone feature maps
61
+ self._bb_feat_sizes = [
62
+ (256, 256),
63
+ (128, 128),
64
+ (64, 64),
65
+ ]
66
+
67
+ self._image_dtype = torch.float32
68
+ self._transforms_device = "cpu"
69
+
70
+ @classmethod
71
+ def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2ImagePredictor":
72
+ """
73
+ Load a pretrained model from the Hugging Face hub.
74
+
75
+ Arguments:
76
+ model_id (str): The Hugging Face repository ID.
77
+ **kwargs: Additional arguments to pass to the model constructor.
78
+
79
+ Returns:
80
+ (SAM2ImagePredictor): The loaded model.
81
+ """
82
+ from sam2.build_sam import build_sam2_hf
83
+
84
+ sam_model = build_sam2_hf(model_id, **kwargs)
85
+ return cls(sam_model, **kwargs)
86
+
87
+ @torch.no_grad()
88
+ def set_image(
89
+ self,
90
+ image: Union[np.ndarray, Image, torch.Tensor],
91
+ ) -> None:
92
+ """
93
+ Calculates the image embeddings for the provided image, allowing
94
+ masks to be predicted with the 'predict' method.
95
+
96
+ Arguments:
97
+ image (np.ndarray or PIL Image): The input image to embed in RGB format. The image should be in HWC format if np.ndarray, or WHC format if PIL Image
98
+ with pixel values in [0, 255].
99
+ image_format (str): The color format of the image, in ['RGB', 'BGR'].
100
+ """
101
+ self.reset_predictor()
102
+ # Transform the image to the form expected by the model
103
+ self._orig_hw = [get_image_size(image)]
104
+
105
+ if isinstance(image, torch.Tensor):
106
+ # from torchvision.transforms.v2 import functional as F
107
+ # input_image = F.to_dtype(image, torch.float32, scale=True)
108
+ input_image = image
109
+ else:
110
+ input_image = self._transforms.to_tensor(image)
111
+
112
+ # NOTE: Doing these transforms on the GPU changes the numerics
113
+ input_image = input_image.to(device=self._transforms_device)
114
+ input_image = self._transforms.transforms(input_image)
115
+ input_image = input_image.to(device=self.device)
116
+ # input_image = self._transforms.transforms(input_image)
117
+ input_image = input_image[None, ...].to(dtype=self._image_dtype)
118
+
119
+ assert len(input_image.shape) == 4 and input_image.shape[1] == 3, (
120
+ f"input_image must be of size 1x3xHxW, got {input_image.shape}"
121
+ )
122
+ logging.info("Computing image embeddings for the provided image...")
123
+ with torch.autograd.profiler.record_function("forward_image"):
124
+ backbone_out = self.model.forward_image(input_image)
125
+ _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
126
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
127
+ if self.model.directly_add_no_mem_embed:
128
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
129
+
130
+ feats = [
131
+ feat.permute(1, 2, 0).view(1, -1, *feat_size)
132
+ for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
133
+ ][::-1]
134
+ self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
135
+ self._is_image_set = True
136
+ logging.info("Image embeddings computed.")
137
+
138
+ @torch.no_grad()
139
+ def set_image_batch(
140
+ self,
141
+ image_list: List[Union[np.ndarray, torch.Tensor]],
142
+ ) -> None:
143
+ """
144
+ Calculates the image embeddings for the provided image batch, allowing
145
+ masks to be predicted with the 'predict_batch' method.
146
+
147
+ Arguments:
148
+ image_list (List[np.ndarray]): The input images to embed in RGB format. The image should be in HWC format if np.ndarray
149
+ with pixel values in [0, 255].
150
+ """
151
+ self.reset_predictor()
152
+ assert isinstance(image_list, list)
153
+ self._orig_hw = list(map(get_image_size, image_list))
154
+ with torch.autograd.profiler.record_function("forward_batch"):
155
+ # Transform the image to the form expected by the model
156
+ # img_batch = self._transforms.forward_batch(image_list)
157
+ image_list = [
158
+ self._transforms.to_tensor(img) if isinstance(img, np.ndarray) else img
159
+ for img in image_list
160
+ ]
161
+ image_list = [self._transforms.transforms(img) for img in image_list]
162
+ img_batch = torch.stack(image_list, dim=0)
163
+ img_batch = img_batch.to(self.device)
164
+ img_batch = img_batch.to(self._image_dtype)
165
+ batch_size = img_batch.shape[0]
166
+ assert len(img_batch.shape) == 4 and img_batch.shape[1] == 3, (
167
+ f"img_batch must be of size Bx3xHxW, got {img_batch.shape}"
168
+ )
169
+ logging.info("Computing image embeddings for the provided images...")
170
+ with torch.autograd.profiler.record_function("forward_image"):
171
+ backbone_out = self.model.forward_image(img_batch)
172
+ with torch.autograd.profiler.record_function("_prepare_backbone_features"):
173
+ _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out)
174
+ # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos
175
+ if self.model.directly_add_no_mem_embed:
176
+ vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed
177
+
178
+ feats = [
179
+ feat.permute(1, 2, 0).view(batch_size, -1, *feat_size)
180
+ for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1])
181
+ ][::-1]
182
+ self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]}
183
+ self._is_image_set = True
184
+ self._is_batch = True
185
+ logging.info("Image embeddings computed.")
186
+
187
+ def predict_batch(
188
+ self,
189
+ point_coords_batch: List[np.ndarray] = None,
190
+ point_labels_batch: List[np.ndarray] = None,
191
+ box_batch: List[np.ndarray] = None,
192
+ mask_input_batch: List[np.ndarray] = None,
193
+ multimask_output: bool = True,
194
+ return_logits: bool = False,
195
+ normalize_coords=True,
196
+ return_type: str = "numpy",
197
+ ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]:
198
+ """This function is very similar to predict(...), however it is used for batched mode, when the model is expected to generate predictions on multiple images.
199
+ It returns a tuple of lists of masks, ious, and low_res_masks_logits.
200
+ """
201
+ if return_type not in ["numpy", "torch"]:
202
+ raise ValueError(
203
+ f"Expected return_type to be either numpy or torch, but got {return_type}"
204
+ )
205
+ assert self._is_batch, "This function should only be used when in batched mode"
206
+ if not self._is_image_set:
207
+ raise RuntimeError(
208
+ "An image must be set with .set_image_batch(...) before mask prediction."
209
+ )
210
+ num_images = len(self._features["image_embed"])
211
+ all_masks = []
212
+ all_ious = []
213
+ all_low_res_masks = []
214
+ for img_idx in range(num_images):
215
+ # Transform input prompts
216
+ point_coords = (
217
+ point_coords_batch[img_idx] if point_coords_batch is not None else None
218
+ )
219
+ point_labels = (
220
+ point_labels_batch[img_idx] if point_labels_batch is not None else None
221
+ )
222
+ box = box_batch[img_idx] if box_batch is not None else None
223
+ mask_input = (
224
+ mask_input_batch[img_idx] if mask_input_batch is not None else None
225
+ )
226
+ mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts(
227
+ point_coords,
228
+ point_labels,
229
+ box,
230
+ mask_input,
231
+ normalize_coords,
232
+ img_idx=img_idx,
233
+ )
234
+ masks, iou_predictions, low_res_masks = self._predict(
235
+ unnorm_coords,
236
+ labels,
237
+ unnorm_box,
238
+ mask_input,
239
+ multimask_output,
240
+ return_logits=return_logits,
241
+ img_idx=img_idx,
242
+ )
243
+ if return_type == "numpy":
244
+ masks = masks.squeeze(0).float().detach().cpu().numpy()
245
+ iou_predictions = (
246
+ iou_predictions.squeeze(0).float().detach().cpu().numpy()
247
+ )
248
+ low_res_masks = low_res_masks.squeeze(0).float().detach().cpu().numpy()
249
+ # NOTE: Need these additional clones to prevent overwriting tensor output of CUDAGraph
250
+ all_masks.append(masks.clone())
251
+ all_ious.append(iou_predictions.clone())
252
+ all_low_res_masks.append(low_res_masks.clone())
253
+
254
+ return all_masks, all_ious, all_low_res_masks
255
+
256
+ def predict(
257
+ self,
258
+ point_coords: Optional[np.ndarray] = None,
259
+ point_labels: Optional[np.ndarray] = None,
260
+ box: Optional[np.ndarray] = None,
261
+ mask_input: Optional[np.ndarray] = None,
262
+ multimask_output: bool = True,
263
+ return_logits: bool = False,
264
+ normalize_coords=True,
265
+ return_type: str = "numpy",
266
+ ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
267
+ """
268
+ Predict masks for the given input prompts, using the currently set image.
269
+
270
+ Arguments:
271
+ point_coords (np.ndarray or None): A Nx2 array of point prompts to the
272
+ model. Each point is in (X,Y) in pixels.
273
+ point_labels (np.ndarray or None): A length N array of labels for the
274
+ point prompts. 1 indicates a foreground point and 0 indicates a
275
+ background point.
276
+ box (np.ndarray or None): A length 4 array given a box prompt to the
277
+ model, in XYXY format.
278
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
279
+ coming from a previous prediction iteration. Has form 1xHxW, where
280
+ for SAM, H=W=256.
281
+ multimask_output (bool): If true, the model will return three masks.
282
+ For ambiguous input prompts (such as a single click), this will often
283
+ produce better masks than a single prediction. If only a single
284
+ mask is needed, the model's predicted quality score can be used
285
+ to select the best mask. For non-ambiguous prompts, such as multiple
286
+ input prompts, multimask_output=False can give better results.
287
+ return_logits (bool): If true, returns un-thresholded masks logits
288
+ instead of a binary mask.
289
+ normalize_coords (bool): If true, the point coordinates will be normalized to the range [0,1] and point_coords is expected to be wrt. image dimensions.
290
+
291
+ Returns:
292
+ (np.ndarray): The output masks in CxHxW format, where C is the
293
+ number of masks, and (H, W) is the original image size.
294
+ (np.ndarray): An array of length C containing the model's
295
+ predictions for the quality of each mask.
296
+ (np.ndarray): An array of shape CxHxW, where C is the number
297
+ of masks and H=W=256. These low resolution logits can be passed to
298
+ a subsequent iteration as mask input.
299
+ """
300
+ if return_type not in ["numpy", "torch"]:
301
+ raise ValueError(
302
+ f"Expected return_type to be either numpy or torch, but got {return_type}"
303
+ )
304
+ if not self._is_image_set:
305
+ raise RuntimeError(
306
+ "An image must be set with .set_image(...) before mask prediction."
307
+ )
308
+
309
+ # Transform input prompts
310
+
311
+ mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts(
312
+ point_coords, point_labels, box, mask_input, normalize_coords
313
+ )
314
+
315
+ masks, iou_predictions, low_res_masks = self._predict(
316
+ unnorm_coords,
317
+ labels,
318
+ unnorm_box,
319
+ mask_input,
320
+ multimask_output,
321
+ return_logits=return_logits,
322
+ )
323
+
324
+ if return_type == "torch":
325
+ return (
326
+ masks.squeeze(0),
327
+ iou_predictions.squeeze(0),
328
+ low_res_masks.squeeze(0),
329
+ )
330
+
331
+ masks_np = masks.squeeze(0).float().detach().cpu().numpy()
332
+ iou_predictions_np = iou_predictions.squeeze(0).float().detach().cpu().numpy()
333
+ low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy()
334
+ return masks_np, iou_predictions_np, low_res_masks_np
335
+
336
+ def _prep_prompts(
337
+ self, point_coords, point_labels, box, mask_logits, normalize_coords, img_idx=-1
338
+ ):
339
+ unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None
340
+ if point_coords is not None:
341
+ assert point_labels is not None, (
342
+ "point_labels must be supplied if point_coords is supplied."
343
+ )
344
+ point_coords = (
345
+ torch.as_tensor(point_coords, dtype=torch.float)
346
+ .pin_memory()
347
+ .to(self.device, non_blocking=True)
348
+ )
349
+ unnorm_coords = self._transforms.transform_coords(
350
+ point_coords, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx]
351
+ )
352
+ labels = (
353
+ torch.as_tensor(point_labels, dtype=torch.int)
354
+ .pin_memory()
355
+ .to(self.device, non_blocking=True)
356
+ )
357
+ if len(unnorm_coords.shape) == 2:
358
+ unnorm_coords, labels = unnorm_coords[None, ...], labels[None, ...]
359
+ if box is not None:
360
+ box = torch.as_tensor(box, dtype=torch.float, device=self.device)
361
+ unnorm_box = self._transforms.transform_boxes(
362
+ box, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx]
363
+ ) # Bx2x2
364
+ if mask_logits is not None:
365
+ mask_input = torch.as_tensor(
366
+ mask_logits, dtype=torch.float, device=self.device
367
+ )
368
+ if len(mask_input.shape) == 3:
369
+ mask_input = mask_input[None, :, :, :]
370
+ return mask_input, unnorm_coords, labels, unnorm_box
371
+
372
+ @torch.no_grad()
373
+ def _predict(
374
+ self,
375
+ point_coords: Optional[torch.Tensor],
376
+ point_labels: Optional[torch.Tensor],
377
+ boxes: Optional[torch.Tensor] = None,
378
+ mask_input: Optional[torch.Tensor] = None,
379
+ multimask_output: bool = True,
380
+ return_logits: bool = False,
381
+ img_idx: int = -1,
382
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
383
+ """
384
+ Predict masks for the given input prompts, using the currently set image.
385
+ Input prompts are batched torch tensors and are expected to already be
386
+ transformed to the input frame using SAM2Transforms.
387
+
388
+ Arguments:
389
+ point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the
390
+ model. Each point is in (X,Y) in pixels.
391
+ point_labels (torch.Tensor or None): A BxN array of labels for the
392
+ point prompts. 1 indicates a foreground point and 0 indicates a
393
+ background point.
394
+ boxes (np.ndarray or None): A Bx4 array given a box prompt to the
395
+ model, in XYXY format.
396
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
397
+ coming from a previous prediction iteration. Has form Bx1xHxW, where
398
+ for SAM, H=W=256. Masks returned by a previous iteration of the
399
+ predict method do not need further transformation.
400
+ multimask_output (bool): If true, the model will return three masks.
401
+ For ambiguous input prompts (such as a single click), this will often
402
+ produce better masks than a single prediction. If only a single
403
+ mask is needed, the model's predicted quality score can be used
404
+ to select the best mask. For non-ambiguous prompts, such as multiple
405
+ input prompts, multimask_output=False can give better results.
406
+ return_logits (bool): If true, returns un-thresholded masks logits
407
+ instead of a binary mask.
408
+
409
+ Returns:
410
+ (torch.Tensor): The output masks in BxCxHxW format, where C is the
411
+ number of masks, and (H, W) is the original image size.
412
+ (torch.Tensor): An array of shape BxC containing the model's
413
+ predictions for the quality of each mask.
414
+ (torch.Tensor): An array of shape BxCxHxW, where C is the number
415
+ of masks and H=W=256. These low res logits can be passed to
416
+ a subsequent iteration as mask input.
417
+ """
418
+ if not self._is_image_set:
419
+ raise RuntimeError(
420
+ "An image must be set with .set_image(...) before mask prediction."
421
+ )
422
+
423
+ with torch.autograd.profiler.record_function("_predict_masks"):
424
+ high_res_feats = self._features["high_res_feats"]
425
+ image_embed = self._features["image_embed"]
426
+ image_pe = self.model.sam_prompt_encoder.get_dense_pe().clone()
427
+ high_res_feats_input = [
428
+ feat_level[img_idx].unsqueeze(0).clone()
429
+ # for feat_level in self._features["high_res_feats"]
430
+ for feat_level in high_res_feats
431
+ ]
432
+ image_embed_input = image_embed[img_idx].unsqueeze(0).clone()
433
+ assert boxes is None
434
+ assert mask_input is None
435
+ assert multimask_output is True
436
+ low_res_masks, iou_predictions = self._predict_masks(
437
+ [t.contiguous() for t in high_res_feats_input],
438
+ image_embed_input.contiguous(),
439
+ image_pe.contiguous(),
440
+ point_coords.contiguous(),
441
+ point_labels.contiguous(),
442
+ boxes=boxes,
443
+ mask_input=mask_input,
444
+ multimask_output=multimask_output,
445
+ )
446
+ # img_idx=img_idx)
447
+ with torch.autograd.profiler.record_function("_predict_masks_postprocess"):
448
+ masks, low_res_masks = self._predict_masks_postprocess(
449
+ low_res_masks, img_idx, return_logits
450
+ )
451
+ return masks, iou_predictions, low_res_masks
452
+
453
+ def _predict_masks(
454
+ self,
455
+ high_res_feats_input,
456
+ image_embed,
457
+ image_pe,
458
+ point_coords,
459
+ point_labels,
460
+ boxes: Optional[torch.Tensor] = None,
461
+ mask_input: Optional[torch.Tensor] = None,
462
+ multimask_output: bool = True,
463
+ ):
464
+ # NOTE: img_idx causes unnecessary recompilations, because
465
+ # the int guard will fail otherwise.
466
+ # img_idx: int = -1):
467
+ if point_coords is not None:
468
+ concat_points = (point_coords, point_labels)
469
+ else:
470
+ concat_points = None
471
+
472
+ # Embed prompts
473
+ if boxes is not None:
474
+ box_coords = boxes.reshape(-1, 2, 2)
475
+ box_labels = torch.tensor([[2, 3]], dtype=torch.int, device=boxes.device)
476
+ box_labels = box_labels.repeat(boxes.size(0), 1)
477
+ # we merge "boxes" and "points" into a single "concat_points" input (where
478
+ # boxes are added at the beginning) to sam_prompt_encoder
479
+ if concat_points is not None:
480
+ concat_coords = torch.cat([box_coords, concat_points[0]], dim=1)
481
+ concat_labels = torch.cat([box_labels, concat_points[1]], dim=1)
482
+ concat_points = (concat_coords, concat_labels)
483
+ else:
484
+ concat_points = (box_coords, box_labels)
485
+
486
+ with torch.autograd.profiler.record_function("self.model.sam_prompt_encoder"):
487
+ sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder(
488
+ points=concat_points,
489
+ boxes=None,
490
+ masks=mask_input,
491
+ )
492
+
493
+ # Predict masks
494
+ batched_mode = (
495
+ concat_points is not None and concat_points[0].shape[0] > 1
496
+ ) # multi object prediction
497
+ # high_res_features = [
498
+ # feat_level[img_idx].unsqueeze(0).clone()
499
+ # # for feat_level in self._features["high_res_feats"]
500
+ # for feat_level in high_res_feats_input
501
+ # ]
502
+ high_res_features = high_res_feats_input
503
+ with torch.autograd.profiler.record_function("self.model.sam_mask_decoder"):
504
+ # if not multimask_output:
505
+ # raise ValueError("Expected multimask_output.")
506
+ # if batched_mode:
507
+ # raise ValueError("Did not expected repeat_image.")
508
+ low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder(
509
+ # image_embeddings=self._features["image_embed"][img_idx].unsqueeze(0).clone(),
510
+ # image_embeddings=image_embed[img_idx].unsqueeze(0).clone(),
511
+ image_embeddings=image_embed,
512
+ # image_pe=self.model.sam_prompt_encoder.get_dense_pe().clone(),
513
+ image_pe=image_pe,
514
+ sparse_prompt_embeddings=sparse_embeddings.clone(),
515
+ dense_prompt_embeddings=dense_embeddings.clone(),
516
+ multimask_output=multimask_output,
517
+ repeat_image=batched_mode,
518
+ high_res_features=high_res_features,
519
+ )
520
+
521
+ return low_res_masks, iou_predictions
522
+
523
+ def _predict_masks_postprocess(
524
+ self, low_res_masks, img_idx, return_logits, channel_1=False
525
+ ):
526
+ # TODO: Might want to defer this until after data["iou_preds"] > self.pred_iou_thresh
527
+ with torch.autograd.profiler.record_function(
528
+ "self._transforms.postprocess_masks"
529
+ ):
530
+ # Upscale the masks to the original image resolution
531
+ if channel_1:
532
+ masks = self._transforms.postprocess_masks_1_channel(
533
+ low_res_masks, self._orig_hw[img_idx], self._image_dtype
534
+ )
535
+ else:
536
+ masks = self._transforms.postprocess_masks(
537
+ low_res_masks, self._orig_hw[img_idx], self._image_dtype
538
+ )
539
+ low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0)
540
+ if not return_logits:
541
+ masks = masks > self.mask_threshold
542
+
543
+ return masks, low_res_masks
544
+
545
+ def get_image_embedding(self) -> torch.Tensor:
546
+ """
547
+ Returns the image embeddings for the currently set image, with
548
+ shape 1xCxHxW, where C is the embedding dimension and (H,W) are
549
+ the embedding spatial dimension of SAM (typically C=256, H=W=64).
550
+ """
551
+ if not self._is_image_set:
552
+ raise RuntimeError(
553
+ "An image must be set with .set_image(...) to generate an embedding."
554
+ )
555
+ assert self._features is not None, (
556
+ "Features must exist if an image has been set."
557
+ )
558
+ return self._features["image_embed"]
559
+
560
+ @property
561
+ def device(self) -> torch.device:
562
+ return self.model.device
563
+
564
+ def reset_predictor(self) -> None:
565
+ """
566
+ Resets the image embeddings and other state variables.
567
+ """
568
+ self._is_image_set = False
569
+ self._features = None
570
+ self._orig_hw = None
571
+ self._is_batch = False
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_video_predictor.py ADDED
@@ -0,0 +1,1192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import warnings
8
+ from collections import OrderedDict
9
+
10
+ import torch
11
+ from tqdm import tqdm
12
+
13
+ from torchao._models.sam2.modeling.sam2_base import NO_OBJ_SCORE, SAM2Base
14
+ from torchao._models.sam2.utils.misc import (
15
+ concat_points,
16
+ fill_holes_in_mask_scores,
17
+ load_video_frames,
18
+ )
19
+
20
+
21
+ class SAM2VideoPredictor(SAM2Base):
22
+ """The predictor class to handle user interactions and manage inference states."""
23
+
24
+ def __init__(
25
+ self,
26
+ fill_hole_area=0,
27
+ # whether to apply non-overlapping constraints on the output object masks
28
+ non_overlap_masks=False,
29
+ # whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks;
30
+ # note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True)
31
+ clear_non_cond_mem_around_input=False,
32
+ # whether to also clear non-conditioning memory of the surrounding frames (only effective when `clear_non_cond_mem_around_input` is True).
33
+ clear_non_cond_mem_for_multi_obj=False,
34
+ # if `add_all_frames_to_correct_as_cond` is True, we also append to the conditioning frame list any frame that receives a later correction click
35
+ # if `add_all_frames_to_correct_as_cond` is False, we conditioning frame list to only use those initial conditioning frames
36
+ add_all_frames_to_correct_as_cond=False,
37
+ **kwargs,
38
+ ):
39
+ super().__init__(**kwargs)
40
+ self.fill_hole_area = fill_hole_area
41
+ self.non_overlap_masks = non_overlap_masks
42
+ self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input
43
+ self.clear_non_cond_mem_for_multi_obj = clear_non_cond_mem_for_multi_obj
44
+ self.add_all_frames_to_correct_as_cond = add_all_frames_to_correct_as_cond
45
+
46
+ @staticmethod
47
+ def batch_inference_states(inference_states: list):
48
+ assert all(dict == type(state) for state in inference_states)
49
+ num_states = len(inference_states)
50
+ assert num_states > 0
51
+ import copy
52
+
53
+ batched_inference_state = copy.copy(inference_states[0])
54
+
55
+ from torchao._models.sam2.map_tensor import to_map_tensor
56
+
57
+ # NOTE: Making a build assumption only images differ
58
+ all_images = torch.stack([state["images"] for state in inference_states])
59
+ batched_inference_state["images"] = to_map_tensor(all_images)
60
+ return batched_inference_state
61
+
62
+ @torch.no_grad()
63
+ def init_state(
64
+ self,
65
+ video_path,
66
+ offload_video_to_cpu=False,
67
+ offload_state_to_cpu=False,
68
+ async_loading_frames=False,
69
+ ):
70
+ """Initialize an inference state."""
71
+ compute_device = self.device # device of the model
72
+ images, video_height, video_width = load_video_frames(
73
+ video_path=video_path,
74
+ image_size=self.image_size,
75
+ offload_video_to_cpu=offload_video_to_cpu,
76
+ async_loading_frames=async_loading_frames,
77
+ compute_device=compute_device,
78
+ )
79
+ inference_state = {}
80
+ inference_state["images"] = images
81
+ inference_state["num_frames"] = len(images)
82
+ # whether to offload the video frames to CPU memory
83
+ # turning on this option saves the GPU memory with only a very small overhead
84
+ inference_state["offload_video_to_cpu"] = offload_video_to_cpu
85
+ # whether to offload the inference state to CPU memory
86
+ # turning on this option saves the GPU memory at the cost of a lower tracking fps
87
+ # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object
88
+ # and from 24 to 21 when tracking two objects)
89
+ inference_state["offload_state_to_cpu"] = offload_state_to_cpu
90
+ # the original video height and width, used for resizing final output scores
91
+ inference_state["video_height"] = video_height
92
+ inference_state["video_width"] = video_width
93
+ inference_state["device"] = compute_device
94
+ if offload_state_to_cpu:
95
+ inference_state["storage_device"] = torch.device("cpu")
96
+ else:
97
+ inference_state["storage_device"] = compute_device
98
+ # inputs on each frame
99
+ inference_state["point_inputs_per_obj"] = {}
100
+ inference_state["mask_inputs_per_obj"] = {}
101
+ # visual features on a small number of recently visited frames for quick interactions
102
+ inference_state["cached_features"] = {}
103
+ # values that don't change across frames (so we only need to hold one copy of them)
104
+ inference_state["constants"] = {}
105
+ # mapping between client-side object id and model-side object index
106
+ inference_state["obj_id_to_idx"] = OrderedDict()
107
+ inference_state["obj_idx_to_id"] = OrderedDict()
108
+ inference_state["obj_ids"] = []
109
+ # A storage to hold the model's tracking results and states on each frame
110
+ inference_state["output_dict"] = {
111
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
112
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
113
+ }
114
+ # Slice (view) of each object tracking results, sharing the same memory with "output_dict"
115
+ inference_state["output_dict_per_obj"] = {}
116
+ # A temporary storage to hold new outputs when user interact with a frame
117
+ # to add clicks or mask (it's merged into "output_dict" before propagation starts)
118
+ inference_state["temp_output_dict_per_obj"] = {}
119
+ # Frames that already holds consolidated outputs from click or mask inputs
120
+ # (we directly use their consolidated outputs during tracking)
121
+ inference_state["consolidated_frame_inds"] = {
122
+ "cond_frame_outputs": set(), # set containing frame indices
123
+ "non_cond_frame_outputs": set(), # set containing frame indices
124
+ }
125
+ # metadata for each tracking frame (e.g. which direction it's tracked)
126
+ inference_state["tracking_has_started"] = False
127
+ inference_state["frames_already_tracked"] = {}
128
+ # Warm up the visual backbone and cache the image feature on frame 0
129
+ self._get_image_feature(inference_state, frame_idx=0, batch_size=1)
130
+ return inference_state
131
+
132
+ @classmethod
133
+ def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2VideoPredictor":
134
+ """
135
+ Load a pretrained model from the Hugging Face hub.
136
+
137
+ Arguments:
138
+ model_id (str): The Hugging Face repository ID.
139
+ **kwargs: Additional arguments to pass to the model constructor.
140
+
141
+ Returns:
142
+ (SAM2VideoPredictor): The loaded model.
143
+ """
144
+ from sam2.build_sam import build_sam2_video_predictor_hf
145
+
146
+ sam_model = build_sam2_video_predictor_hf(model_id, **kwargs)
147
+ return sam_model
148
+
149
+ def _obj_id_to_idx(self, inference_state, obj_id):
150
+ """Map client-side object id to model-side object index."""
151
+ obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None)
152
+ if obj_idx is not None:
153
+ return obj_idx
154
+
155
+ # This is a new object id not sent to the server before. We only allow adding
156
+ # new objects *before* the tracking starts.
157
+ allow_new_object = not inference_state["tracking_has_started"]
158
+ if allow_new_object:
159
+ # get the next object slot
160
+ obj_idx = len(inference_state["obj_id_to_idx"])
161
+ inference_state["obj_id_to_idx"][obj_id] = obj_idx
162
+ inference_state["obj_idx_to_id"][obj_idx] = obj_id
163
+ inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"])
164
+ # set up input and output structures for this object
165
+ inference_state["point_inputs_per_obj"][obj_idx] = {}
166
+ inference_state["mask_inputs_per_obj"][obj_idx] = {}
167
+ inference_state["output_dict_per_obj"][obj_idx] = {
168
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
169
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
170
+ }
171
+ inference_state["temp_output_dict_per_obj"][obj_idx] = {
172
+ "cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
173
+ "non_cond_frame_outputs": {}, # dict containing {frame_idx: <out>}
174
+ }
175
+ return obj_idx
176
+ else:
177
+ raise RuntimeError(
178
+ f"Cannot add new object id {obj_id} after tracking starts. "
179
+ f"All existing object ids: {inference_state['obj_ids']}. "
180
+ f"Please call 'reset_state' to restart from scratch."
181
+ )
182
+
183
+ def _obj_idx_to_id(self, inference_state, obj_idx):
184
+ """Map model-side object index to client-side object id."""
185
+ return inference_state["obj_idx_to_id"][obj_idx]
186
+
187
+ def _get_obj_num(self, inference_state):
188
+ """Get the total number of unique object ids received so far in this session."""
189
+ return len(inference_state["obj_idx_to_id"])
190
+
191
+ @torch.no_grad()
192
+ def add_new_points_or_box(
193
+ self,
194
+ inference_state,
195
+ frame_idx,
196
+ obj_id,
197
+ points=None,
198
+ labels=None,
199
+ clear_old_points=True,
200
+ normalize_coords=True,
201
+ box=None,
202
+ ):
203
+ """Add new points to a frame."""
204
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
205
+ point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
206
+ mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
207
+
208
+ if (points is not None) != (labels is not None):
209
+ raise ValueError("points and labels must be provided together")
210
+ if points is None and box is None:
211
+ raise ValueError("at least one of points or box must be provided as input")
212
+
213
+ if points is None:
214
+ points = torch.zeros(0, 2, dtype=torch.float32)
215
+ elif not isinstance(points, torch.Tensor):
216
+ points = torch.tensor(points, dtype=torch.float32)
217
+ if labels is None:
218
+ labels = torch.zeros(0, dtype=torch.int32)
219
+ elif not isinstance(labels, torch.Tensor):
220
+ labels = torch.tensor(labels, dtype=torch.int32)
221
+ if points.dim() == 2:
222
+ points = points.unsqueeze(0) # add batch dimension
223
+ if labels.dim() == 1:
224
+ labels = labels.unsqueeze(0) # add batch dimension
225
+
226
+ # If `box` is provided, we add it as the first two points with labels 2 and 3
227
+ # along with the user-provided points (consistent with how SAM 2 is trained).
228
+ if box is not None:
229
+ if not clear_old_points:
230
+ raise ValueError(
231
+ "cannot add box without clearing old points, since "
232
+ "box prompt must be provided before any point prompt "
233
+ "(please use clear_old_points=True instead)"
234
+ )
235
+ if inference_state["tracking_has_started"]:
236
+ warnings.warn(
237
+ "You are adding a box after tracking starts. SAM 2 may not always be "
238
+ "able to incorporate a box prompt for *refinement*. If you intend to "
239
+ "use box prompt as an *initial* input before tracking, please call "
240
+ "'reset_state' on the inference state to restart from scratch.",
241
+ category=UserWarning,
242
+ stacklevel=2,
243
+ )
244
+ if not isinstance(box, torch.Tensor):
245
+ box = torch.tensor(box, dtype=torch.float32, device=points.device)
246
+ box_coords = box.reshape(1, 2, 2)
247
+ box_labels = torch.tensor([2, 3], dtype=torch.int32, device=labels.device)
248
+ box_labels = box_labels.reshape(1, 2)
249
+ points = torch.cat([box_coords, points], dim=1)
250
+ labels = torch.cat([box_labels, labels], dim=1)
251
+
252
+ if normalize_coords:
253
+ video_H = inference_state["video_height"]
254
+ video_W = inference_state["video_width"]
255
+ points = points / torch.tensor([video_W, video_H]).to(points.device)
256
+ # scale the (normalized) coordinates by the model's internal image size
257
+ points = points * self.image_size
258
+ points = points.to(inference_state["device"])
259
+ labels = labels.to(inference_state["device"])
260
+
261
+ if not clear_old_points:
262
+ point_inputs = point_inputs_per_frame.get(frame_idx, None)
263
+ else:
264
+ point_inputs = None
265
+ point_inputs = concat_points(point_inputs, points, labels)
266
+
267
+ point_inputs_per_frame[frame_idx] = point_inputs
268
+ mask_inputs_per_frame.pop(frame_idx, None)
269
+ # If this frame hasn't been tracked before, we treat it as an initial conditioning
270
+ # frame, meaning that the inputs points are to generate segments on this frame without
271
+ # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
272
+ # the input points will be used to correct the already tracked masks.
273
+ is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"]
274
+ # whether to track in reverse time order
275
+ if is_init_cond_frame:
276
+ reverse = False
277
+ else:
278
+ reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"]
279
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
280
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
281
+ # Add a frame to conditioning output if it's an initial conditioning frame or
282
+ # if the model sees all frames receiving clicks/mask as conditioning frames.
283
+ is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
284
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
285
+
286
+ # Get any previously predicted mask logits on this object and feed it along with
287
+ # the new clicks into the SAM mask decoder.
288
+ prev_sam_mask_logits = None
289
+ # lookup temporary output dict first, which contains the most recent output
290
+ # (if not found, then lookup conditioning and non-conditioning frame output)
291
+ prev_out = obj_temp_output_dict[storage_key].get(frame_idx)
292
+ if prev_out is None:
293
+ prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx)
294
+ if prev_out is None:
295
+ prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx)
296
+
297
+ if prev_out is not None and prev_out["pred_masks"] is not None:
298
+ device = inference_state["device"]
299
+ prev_sam_mask_logits = prev_out["pred_masks"].to(device, non_blocking=True)
300
+ # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues.
301
+ prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0)
302
+ current_out, _ = self._run_single_frame_inference(
303
+ inference_state=inference_state,
304
+ output_dict=obj_output_dict, # run on the slice of a single object
305
+ frame_idx=frame_idx,
306
+ batch_size=1, # run on the slice of a single object
307
+ is_init_cond_frame=is_init_cond_frame,
308
+ point_inputs=point_inputs,
309
+ mask_inputs=None,
310
+ reverse=reverse,
311
+ # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
312
+ # at the beginning of `propagate_in_video` (after user finalize their clicks). This
313
+ # allows us to enforce non-overlapping constraints on all objects before encoding
314
+ # them into memory.
315
+ run_mem_encoder=False,
316
+ prev_sam_mask_logits=prev_sam_mask_logits,
317
+ )
318
+ # Add the output to the output dict (to be used as future memory)
319
+ obj_temp_output_dict[storage_key][frame_idx] = current_out
320
+
321
+ # Resize the output mask to the original video resolution
322
+ obj_ids = inference_state["obj_ids"]
323
+ consolidated_out = self._consolidate_temp_output_across_obj(
324
+ inference_state,
325
+ frame_idx,
326
+ is_cond=is_cond,
327
+ run_mem_encoder=False,
328
+ consolidate_at_video_res=True,
329
+ )
330
+ _, video_res_masks = self._get_orig_video_res_output(
331
+ inference_state, consolidated_out["pred_masks_video_res"]
332
+ )
333
+ return frame_idx, obj_ids, video_res_masks
334
+
335
+ def add_new_points(self, *args, **kwargs):
336
+ """Deprecated method. Please use `add_new_points_or_box` instead."""
337
+ return self.add_new_points_or_box(*args, **kwargs)
338
+
339
+ @torch.no_grad()
340
+ def add_new_mask(
341
+ self,
342
+ inference_state,
343
+ frame_idx,
344
+ obj_id,
345
+ mask,
346
+ ):
347
+ """Add new mask to a frame."""
348
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
349
+ point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx]
350
+ mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx]
351
+
352
+ if not isinstance(mask, torch.Tensor):
353
+ mask = torch.tensor(mask, dtype=torch.bool)
354
+ assert mask.dim() == 2
355
+ mask_H, mask_W = mask.shape
356
+ mask_inputs_orig = mask[None, None] # add batch and channel dimension
357
+ mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"])
358
+
359
+ # resize the mask if it doesn't match the model's image size
360
+ if mask_H != self.image_size or mask_W != self.image_size:
361
+ mask_inputs = torch.nn.functional.interpolate(
362
+ mask_inputs_orig,
363
+ size=(self.image_size, self.image_size),
364
+ align_corners=False,
365
+ mode="bilinear",
366
+ antialias=True, # use antialias for downsampling
367
+ )
368
+ mask_inputs = (mask_inputs >= 0.5).float()
369
+ else:
370
+ mask_inputs = mask_inputs_orig
371
+
372
+ mask_inputs_per_frame[frame_idx] = mask_inputs
373
+ point_inputs_per_frame.pop(frame_idx, None)
374
+ # If this frame hasn't been tracked before, we treat it as an initial conditioning
375
+ # frame, meaning that the inputs points are to generate segments on this frame without
376
+ # using any memory from other frames, like in SAM. Otherwise (if it has been tracked),
377
+ # the input points will be used to correct the already tracked masks.
378
+ is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"]
379
+ # whether to track in reverse time order
380
+ if is_init_cond_frame:
381
+ reverse = False
382
+ else:
383
+ reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"]
384
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
385
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
386
+ # Add a frame to conditioning output if it's an initial conditioning frame or
387
+ # if the model sees all frames receiving clicks/mask as conditioning frames.
388
+ is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond
389
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
390
+
391
+ current_out, _ = self._run_single_frame_inference(
392
+ inference_state=inference_state,
393
+ output_dict=obj_output_dict, # run on the slice of a single object
394
+ frame_idx=frame_idx,
395
+ batch_size=1, # run on the slice of a single object
396
+ is_init_cond_frame=is_init_cond_frame,
397
+ point_inputs=None,
398
+ mask_inputs=mask_inputs,
399
+ reverse=reverse,
400
+ # Skip the memory encoder when adding clicks or mask. We execute the memory encoder
401
+ # at the beginning of `propagate_in_video` (after user finalize their clicks). This
402
+ # allows us to enforce non-overlapping constraints on all objects before encoding
403
+ # them into memory.
404
+ run_mem_encoder=False,
405
+ )
406
+ # Add the output to the output dict (to be used as future memory)
407
+ obj_temp_output_dict[storage_key][frame_idx] = current_out
408
+
409
+ # Resize the output mask to the original video resolution
410
+ obj_ids = inference_state["obj_ids"]
411
+ consolidated_out = self._consolidate_temp_output_across_obj(
412
+ inference_state,
413
+ frame_idx,
414
+ is_cond=is_cond,
415
+ run_mem_encoder=False,
416
+ consolidate_at_video_res=True,
417
+ )
418
+ _, video_res_masks = self._get_orig_video_res_output(
419
+ inference_state, consolidated_out["pred_masks_video_res"]
420
+ )
421
+ return frame_idx, obj_ids, video_res_masks
422
+
423
+ def _get_orig_video_res_output(self, inference_state, any_res_masks):
424
+ """
425
+ Resize the object scores to the original video resolution (video_res_masks)
426
+ and apply non-overlapping constraints for final output.
427
+ """
428
+ device = inference_state["device"]
429
+ video_H = inference_state["video_height"]
430
+ video_W = inference_state["video_width"]
431
+ any_res_masks = any_res_masks.to(device, non_blocking=True)
432
+ if any_res_masks.shape[-2:] == (video_H, video_W):
433
+ video_res_masks = any_res_masks
434
+ else:
435
+ video_res_masks = torch.nn.functional.interpolate(
436
+ any_res_masks,
437
+ size=(video_H, video_W),
438
+ mode="bilinear",
439
+ align_corners=False,
440
+ )
441
+ if self.non_overlap_masks:
442
+ video_res_masks = self._apply_non_overlapping_constraints(video_res_masks)
443
+ return any_res_masks, video_res_masks
444
+
445
+ def _consolidate_temp_output_across_obj(
446
+ self,
447
+ inference_state,
448
+ frame_idx,
449
+ is_cond,
450
+ run_mem_encoder,
451
+ consolidate_at_video_res=False,
452
+ ):
453
+ """
454
+ Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on
455
+ a frame into a single output for all objects, including
456
+ 1) fill any missing objects either from `output_dict_per_obj` (if they exist in
457
+ `output_dict_per_obj` for this frame) or leave them as placeholder values
458
+ (if they don't exist in `output_dict_per_obj` for this frame);
459
+ 2) if specified, rerun memory encoder after apply non-overlapping constraints
460
+ on the object scores.
461
+ """
462
+ batch_size = self._get_obj_num(inference_state)
463
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
464
+ # Optionally, we allow consolidating the temporary outputs at the original
465
+ # video resolution (to provide a better editing experience for mask prompts).
466
+ if consolidate_at_video_res:
467
+ assert not run_mem_encoder, "memory encoder cannot run at video resolution"
468
+ consolidated_H = inference_state["video_height"]
469
+ consolidated_W = inference_state["video_width"]
470
+ consolidated_mask_key = "pred_masks_video_res"
471
+ else:
472
+ consolidated_H = consolidated_W = self.image_size // 4
473
+ consolidated_mask_key = "pred_masks"
474
+
475
+ # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc"
476
+ # will be added when rerunning the memory encoder after applying non-overlapping
477
+ # constraints to object scores. Its "pred_masks" are prefilled with a large
478
+ # negative value (NO_OBJ_SCORE) to represent missing objects.
479
+ consolidated_out = {
480
+ "maskmem_features": None,
481
+ "maskmem_pos_enc": None,
482
+ consolidated_mask_key: torch.full(
483
+ size=(batch_size, 1, consolidated_H, consolidated_W),
484
+ fill_value=NO_OBJ_SCORE,
485
+ dtype=torch.float32,
486
+ device=inference_state["storage_device"],
487
+ ),
488
+ "obj_ptr": torch.full(
489
+ size=(batch_size, self.hidden_dim),
490
+ fill_value=NO_OBJ_SCORE,
491
+ dtype=torch.float32,
492
+ device=inference_state["device"],
493
+ ),
494
+ "object_score_logits": torch.full(
495
+ size=(batch_size, 1),
496
+ # default to 10.0 for object_score_logits, i.e. assuming the object is
497
+ # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder`
498
+ fill_value=10.0,
499
+ dtype=torch.float32,
500
+ device=inference_state["device"],
501
+ ),
502
+ }
503
+ empty_mask_ptr = None
504
+ for obj_idx in range(batch_size):
505
+ obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx]
506
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx]
507
+ out = obj_temp_output_dict[storage_key].get(frame_idx, None)
508
+ # If the object doesn't appear in "temp_output_dict_per_obj" on this frame,
509
+ # we fall back and look up its previous output in "output_dict_per_obj".
510
+ # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in
511
+ # "output_dict_per_obj" to find a previous output for this object.
512
+ if out is None:
513
+ out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None)
514
+ if out is None:
515
+ out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None)
516
+ # If the object doesn't appear in "output_dict_per_obj" either, we skip it
517
+ # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE
518
+ # placeholder above) and set its object pointer to be a dummy pointer.
519
+ if out is None:
520
+ # Fill in dummy object pointers for those objects without any inputs or
521
+ # tracking outcomes on this frame (only do it under `run_mem_encoder=True`,
522
+ # i.e. when we need to build the memory for tracking).
523
+ if run_mem_encoder:
524
+ if empty_mask_ptr is None:
525
+ empty_mask_ptr = self._get_empty_mask_ptr(
526
+ inference_state, frame_idx
527
+ )
528
+ # fill object pointer with a dummy pointer (based on an empty mask)
529
+ consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = empty_mask_ptr
530
+ continue
531
+ # Add the temporary object output mask to consolidated output mask
532
+ obj_mask = out["pred_masks"]
533
+ consolidated_pred_masks = consolidated_out[consolidated_mask_key]
534
+ if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]:
535
+ consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask
536
+ else:
537
+ # Resize first if temporary object mask has a different resolution
538
+ resized_obj_mask = torch.nn.functional.interpolate(
539
+ obj_mask,
540
+ size=consolidated_pred_masks.shape[-2:],
541
+ mode="bilinear",
542
+ align_corners=False,
543
+ )
544
+ consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask
545
+ consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"]
546
+ consolidated_out["object_score_logits"][obj_idx : obj_idx + 1] = out[
547
+ "object_score_logits"
548
+ ]
549
+
550
+ # Optionally, apply non-overlapping constraints on the consolidated scores
551
+ # and rerun the memory encoder
552
+ if run_mem_encoder:
553
+ device = inference_state["device"]
554
+ high_res_masks = torch.nn.functional.interpolate(
555
+ consolidated_out["pred_masks"].to(device, non_blocking=True),
556
+ size=(self.image_size, self.image_size),
557
+ mode="bilinear",
558
+ align_corners=False,
559
+ )
560
+ if self.non_overlap_masks_for_mem_enc:
561
+ high_res_masks = self._apply_non_overlapping_constraints(high_res_masks)
562
+ maskmem_features, maskmem_pos_enc = self._run_memory_encoder(
563
+ inference_state=inference_state,
564
+ frame_idx=frame_idx,
565
+ batch_size=batch_size,
566
+ high_res_masks=high_res_masks,
567
+ object_score_logits=consolidated_out["object_score_logits"],
568
+ is_mask_from_pts=True, # these frames are what the user interacted with
569
+ )
570
+ consolidated_out["maskmem_features"] = maskmem_features
571
+ consolidated_out["maskmem_pos_enc"] = maskmem_pos_enc
572
+
573
+ return consolidated_out
574
+
575
+ def _get_empty_mask_ptr(self, inference_state, frame_idx):
576
+ """Get a dummy object pointer based on an empty mask on the current frame."""
577
+ # A dummy (empty) mask with a single object
578
+ batch_size = 1
579
+ mask_inputs = torch.zeros(
580
+ (batch_size, 1, self.image_size, self.image_size),
581
+ dtype=torch.float32,
582
+ device=inference_state["device"],
583
+ )
584
+
585
+ # Retrieve correct image features
586
+ (
587
+ _,
588
+ _,
589
+ current_vision_feats,
590
+ current_vision_pos_embeds,
591
+ feat_sizes,
592
+ ) = self._get_image_feature(inference_state, frame_idx, batch_size)
593
+
594
+ # Feed the empty mask and image feature above to get a dummy object pointer
595
+ current_out = self.track_step(
596
+ frame_idx=frame_idx,
597
+ is_init_cond_frame=True,
598
+ current_vision_feats=current_vision_feats,
599
+ current_vision_pos_embeds=current_vision_pos_embeds,
600
+ feat_sizes=feat_sizes,
601
+ point_inputs=None,
602
+ mask_inputs=mask_inputs,
603
+ output_dict={},
604
+ num_frames=inference_state["num_frames"],
605
+ track_in_reverse=False,
606
+ run_mem_encoder=False,
607
+ prev_sam_mask_logits=None,
608
+ )
609
+ return current_out["obj_ptr"]
610
+
611
+ @torch.no_grad()
612
+ def propagate_in_video_preflight(self, inference_state):
613
+ """Prepare inference_state and consolidate temporary outputs before tracking."""
614
+ # Tracking has started and we don't allow adding new objects until session is reset.
615
+ inference_state["tracking_has_started"] = True
616
+ batch_size = self._get_obj_num(inference_state)
617
+
618
+ # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and
619
+ # add them into "output_dict".
620
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
621
+ output_dict = inference_state["output_dict"]
622
+ # "consolidated_frame_inds" contains indices of those frames where consolidated
623
+ # temporary outputs have been added (either in this call or any previous calls
624
+ # to `propagate_in_video_preflight`).
625
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
626
+ for is_cond in [False, True]:
627
+ # Separately consolidate conditioning and non-conditioning temp outputs
628
+ storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs"
629
+ # Find all the frames that contain temporary outputs for any objects
630
+ # (these should be the frames that have just received clicks for mask inputs
631
+ # via `add_new_points_or_box` or `add_new_mask`)
632
+ temp_frame_inds = set()
633
+ for obj_temp_output_dict in temp_output_dict_per_obj.values():
634
+ temp_frame_inds.update(obj_temp_output_dict[storage_key].keys())
635
+ consolidated_frame_inds[storage_key].update(temp_frame_inds)
636
+ # consolidate the temporary output across all objects on this frame
637
+ for frame_idx in temp_frame_inds:
638
+ consolidated_out = self._consolidate_temp_output_across_obj(
639
+ inference_state, frame_idx, is_cond=is_cond, run_mem_encoder=True
640
+ )
641
+ # merge them into "output_dict" and also create per-object slices
642
+ output_dict[storage_key][frame_idx] = consolidated_out
643
+ self._add_output_per_object(
644
+ inference_state, frame_idx, consolidated_out, storage_key
645
+ )
646
+ clear_non_cond_mem = self.clear_non_cond_mem_around_input and (
647
+ self.clear_non_cond_mem_for_multi_obj or batch_size <= 1
648
+ )
649
+ if clear_non_cond_mem:
650
+ # clear non-conditioning memory of the surrounding frames
651
+ self._clear_non_cond_mem_around_input(inference_state, frame_idx)
652
+
653
+ # clear temporary outputs in `temp_output_dict_per_obj`
654
+ for obj_temp_output_dict in temp_output_dict_per_obj.values():
655
+ obj_temp_output_dict[storage_key].clear()
656
+
657
+ # edge case: if an output is added to "cond_frame_outputs", we remove any prior
658
+ # output on the same frame in "non_cond_frame_outputs"
659
+ for frame_idx in output_dict["cond_frame_outputs"]:
660
+ output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
661
+ for obj_output_dict in inference_state["output_dict_per_obj"].values():
662
+ for frame_idx in obj_output_dict["cond_frame_outputs"]:
663
+ obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None)
664
+ for frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
665
+ assert frame_idx in output_dict["cond_frame_outputs"]
666
+ consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
667
+
668
+ # Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames
669
+ # with either points or mask inputs (which should be true under a correct workflow).
670
+ all_consolidated_frame_inds = (
671
+ consolidated_frame_inds["cond_frame_outputs"]
672
+ | consolidated_frame_inds["non_cond_frame_outputs"]
673
+ )
674
+ input_frames_inds = set()
675
+ for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values():
676
+ input_frames_inds.update(point_inputs_per_frame.keys())
677
+ for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values():
678
+ input_frames_inds.update(mask_inputs_per_frame.keys())
679
+ assert all_consolidated_frame_inds == input_frames_inds
680
+
681
+ @torch.no_grad()
682
+ def propagate_in_video(
683
+ self,
684
+ inference_state,
685
+ start_frame_idx=None,
686
+ max_frame_num_to_track=None,
687
+ reverse=False,
688
+ ):
689
+ """Propagate the input points across frames to track in the entire video."""
690
+ self.propagate_in_video_preflight(inference_state)
691
+
692
+ output_dict = inference_state["output_dict"]
693
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
694
+ obj_ids = inference_state["obj_ids"]
695
+ num_frames = inference_state["num_frames"]
696
+ batch_size = self._get_obj_num(inference_state)
697
+ if len(output_dict["cond_frame_outputs"]) == 0:
698
+ raise RuntimeError("No points are provided; please add points first")
699
+ clear_non_cond_mem = self.clear_non_cond_mem_around_input and (
700
+ self.clear_non_cond_mem_for_multi_obj or batch_size <= 1
701
+ )
702
+
703
+ # set start index, end index, and processing order
704
+ if start_frame_idx is None:
705
+ # default: start from the earliest frame with input points
706
+ start_frame_idx = min(output_dict["cond_frame_outputs"])
707
+ if max_frame_num_to_track is None:
708
+ # default: track all the frames in the video
709
+ max_frame_num_to_track = num_frames
710
+ if reverse:
711
+ end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0)
712
+ if start_frame_idx > 0:
713
+ processing_order = range(start_frame_idx, end_frame_idx - 1, -1)
714
+ else:
715
+ processing_order = [] # skip reverse tracking if starting from frame 0
716
+ else:
717
+ end_frame_idx = min(
718
+ start_frame_idx + max_frame_num_to_track, num_frames - 1
719
+ )
720
+ processing_order = range(start_frame_idx, end_frame_idx + 1)
721
+
722
+ for frame_idx in tqdm(processing_order, desc="propagate in video"):
723
+ # We skip those frames already in consolidated outputs (these are frames
724
+ # that received input clicks or mask). Note that we cannot directly run
725
+ # batched forward on them via `_run_single_frame_inference` because the
726
+ # number of clicks on each object might be different.
727
+ if frame_idx in consolidated_frame_inds["cond_frame_outputs"]:
728
+ storage_key = "cond_frame_outputs"
729
+ current_out = output_dict[storage_key][frame_idx]
730
+ pred_masks = current_out["pred_masks"]
731
+ if clear_non_cond_mem:
732
+ # clear non-conditioning memory of the surrounding frames
733
+ self._clear_non_cond_mem_around_input(inference_state, frame_idx)
734
+ elif frame_idx in consolidated_frame_inds["non_cond_frame_outputs"]:
735
+ storage_key = "non_cond_frame_outputs"
736
+ current_out = output_dict[storage_key][frame_idx]
737
+ pred_masks = current_out["pred_masks"]
738
+ else:
739
+ storage_key = "non_cond_frame_outputs"
740
+ current_out, pred_masks = self._run_single_frame_inference(
741
+ inference_state=inference_state,
742
+ output_dict=output_dict,
743
+ frame_idx=frame_idx,
744
+ batch_size=batch_size,
745
+ is_init_cond_frame=False,
746
+ point_inputs=None,
747
+ mask_inputs=None,
748
+ reverse=reverse,
749
+ run_mem_encoder=True,
750
+ )
751
+ output_dict[storage_key][frame_idx] = current_out
752
+ # Create slices of per-object outputs for subsequent interaction with each
753
+ # individual object after tracking.
754
+ self._add_output_per_object(
755
+ inference_state, frame_idx, current_out, storage_key
756
+ )
757
+ inference_state["frames_already_tracked"][frame_idx] = {"reverse": reverse}
758
+
759
+ # Resize the output mask to the original video resolution (we directly use
760
+ # the mask scores on GPU for output to avoid any CPU conversion in between)
761
+ _, video_res_masks = self._get_orig_video_res_output(
762
+ inference_state, pred_masks
763
+ )
764
+ yield frame_idx, obj_ids, video_res_masks
765
+
766
+ def _add_output_per_object(
767
+ self, inference_state, frame_idx, current_out, storage_key
768
+ ):
769
+ """
770
+ Split a multi-object output into per-object output slices and add them into
771
+ `output_dict_per_obj`. The resulting slices share the same tensor storage.
772
+ """
773
+ maskmem_features = current_out["maskmem_features"]
774
+ assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor)
775
+
776
+ maskmem_pos_enc = current_out["maskmem_pos_enc"]
777
+ assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list)
778
+
779
+ output_dict_per_obj = inference_state["output_dict_per_obj"]
780
+ for obj_idx, obj_output_dict in output_dict_per_obj.items():
781
+ obj_slice = slice(obj_idx, obj_idx + 1)
782
+ obj_out = {
783
+ "maskmem_features": None,
784
+ "maskmem_pos_enc": None,
785
+ "pred_masks": current_out["pred_masks"][obj_slice],
786
+ "obj_ptr": current_out["obj_ptr"][obj_slice],
787
+ "object_score_logits": current_out["object_score_logits"][obj_slice],
788
+ }
789
+ if maskmem_features is not None:
790
+ obj_out["maskmem_features"] = maskmem_features[obj_slice]
791
+ if maskmem_pos_enc is not None:
792
+ obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc]
793
+ obj_output_dict[storage_key][frame_idx] = obj_out
794
+
795
+ @torch.no_grad()
796
+ def clear_all_prompts_in_frame(
797
+ self, inference_state, frame_idx, obj_id, need_output=True
798
+ ):
799
+ """Remove all input points or mask in a specific frame for a given object."""
800
+ obj_idx = self._obj_id_to_idx(inference_state, obj_id)
801
+
802
+ # Clear the conditioning information on the given frame
803
+ inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None)
804
+ inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None)
805
+
806
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
807
+ temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None)
808
+ temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None)
809
+
810
+ # Check and see if there are still any inputs left on this frame
811
+ batch_size = self._get_obj_num(inference_state)
812
+ frame_has_input = False
813
+ for obj_idx2 in range(batch_size):
814
+ if frame_idx in inference_state["point_inputs_per_obj"][obj_idx2]:
815
+ frame_has_input = True
816
+ break
817
+ if frame_idx in inference_state["mask_inputs_per_obj"][obj_idx2]:
818
+ frame_has_input = True
819
+ break
820
+
821
+ # If this frame has no remaining inputs for any objects, we further clear its
822
+ # conditioning frame status
823
+ if not frame_has_input:
824
+ output_dict = inference_state["output_dict"]
825
+ consolidated_frame_inds = inference_state["consolidated_frame_inds"]
826
+ consolidated_frame_inds["cond_frame_outputs"].discard(frame_idx)
827
+ consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx)
828
+ # Remove the frame's conditioning output (possibly downgrading it to non-conditioning)
829
+ out = output_dict["cond_frame_outputs"].pop(frame_idx, None)
830
+ if out is not None:
831
+ # The frame is not a conditioning frame anymore since it's not receiving inputs,
832
+ # so we "downgrade" its output (if exists) to a non-conditioning frame output.
833
+ output_dict["non_cond_frame_outputs"][frame_idx] = out
834
+ inference_state["frames_already_tracked"].pop(frame_idx, None)
835
+ # Similarly, do it for the sliced output on each object.
836
+ for obj_idx2 in range(batch_size):
837
+ obj_output_dict = inference_state["output_dict_per_obj"][obj_idx2]
838
+ obj_out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None)
839
+ if obj_out is not None:
840
+ obj_output_dict["non_cond_frame_outputs"][frame_idx] = obj_out
841
+
842
+ # If all the conditioning frames have been removed, we also clear the tracking outputs
843
+ if len(output_dict["cond_frame_outputs"]) == 0:
844
+ self._reset_tracking_results(inference_state)
845
+
846
+ if not need_output:
847
+ return
848
+ # Finally, output updated masks per object (after removing the inputs above)
849
+ obj_ids = inference_state["obj_ids"]
850
+ is_cond = any(
851
+ frame_idx in obj_temp_output_dict["cond_frame_outputs"]
852
+ for obj_temp_output_dict in temp_output_dict_per_obj.values()
853
+ )
854
+ consolidated_out = self._consolidate_temp_output_across_obj(
855
+ inference_state,
856
+ frame_idx,
857
+ is_cond=is_cond,
858
+ run_mem_encoder=False,
859
+ consolidate_at_video_res=True,
860
+ )
861
+ _, video_res_masks = self._get_orig_video_res_output(
862
+ inference_state, consolidated_out["pred_masks_video_res"]
863
+ )
864
+ return frame_idx, obj_ids, video_res_masks
865
+
866
+ @torch.no_grad()
867
+ def reset_state(self, inference_state):
868
+ """Remove all input points or mask in all frames throughout the video."""
869
+ self._reset_tracking_results(inference_state)
870
+ # Remove all object ids
871
+ inference_state["obj_id_to_idx"].clear()
872
+ inference_state["obj_idx_to_id"].clear()
873
+ inference_state["obj_ids"].clear()
874
+ inference_state["point_inputs_per_obj"].clear()
875
+ inference_state["mask_inputs_per_obj"].clear()
876
+ inference_state["output_dict_per_obj"].clear()
877
+ inference_state["temp_output_dict_per_obj"].clear()
878
+
879
+ def _reset_tracking_results(self, inference_state):
880
+ """Reset all tracking inputs and results across the videos."""
881
+ for v in inference_state["point_inputs_per_obj"].values():
882
+ v.clear()
883
+ for v in inference_state["mask_inputs_per_obj"].values():
884
+ v.clear()
885
+ for v in inference_state["output_dict_per_obj"].values():
886
+ v["cond_frame_outputs"].clear()
887
+ v["non_cond_frame_outputs"].clear()
888
+ for v in inference_state["temp_output_dict_per_obj"].values():
889
+ v["cond_frame_outputs"].clear()
890
+ v["non_cond_frame_outputs"].clear()
891
+ inference_state["output_dict"]["cond_frame_outputs"].clear()
892
+ inference_state["output_dict"]["non_cond_frame_outputs"].clear()
893
+ inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear()
894
+ inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear()
895
+ inference_state["tracking_has_started"] = False
896
+ inference_state["frames_already_tracked"].clear()
897
+
898
+ def _get_image_feature(self, inference_state, frame_idx, batch_size):
899
+ """Compute the image features on a given frame."""
900
+ # Look up in the cache first
901
+ image, backbone_out = inference_state["cached_features"].get(
902
+ frame_idx, (None, None)
903
+ )
904
+ if backbone_out is None:
905
+ # Cache miss -- we will run inference on a single image
906
+ device = inference_state["device"]
907
+ image = inference_state["images"][frame_idx].to(device).float().unsqueeze(0)
908
+ backbone_out = self.forward_image(image)
909
+ # Cache the most recent frame's feature (for repeated interactions with
910
+ # a frame; we can use an LRU cache for more frames in the future).
911
+ inference_state["cached_features"] = {frame_idx: (image, backbone_out)}
912
+
913
+ # expand the features to have the same dimension as the number of objects
914
+ expanded_image = image.expand(batch_size, -1, -1, -1)
915
+ expanded_backbone_out = {
916
+ "backbone_fpn": backbone_out["backbone_fpn"].copy(),
917
+ "vision_pos_enc": backbone_out["vision_pos_enc"].copy(),
918
+ }
919
+ for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]):
920
+ expanded_backbone_out["backbone_fpn"][i] = feat.expand(
921
+ batch_size, -1, -1, -1
922
+ )
923
+ for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]):
924
+ pos = pos.expand(batch_size, -1, -1, -1)
925
+ expanded_backbone_out["vision_pos_enc"][i] = pos
926
+
927
+ features = self._prepare_backbone_features(expanded_backbone_out)
928
+ features = (expanded_image,) + features
929
+ return features
930
+
931
+ @torch.autograd.profiler.record_function("_run_single_frame_inference")
932
+ def _run_single_frame_inference(
933
+ self,
934
+ inference_state,
935
+ output_dict,
936
+ frame_idx,
937
+ batch_size,
938
+ is_init_cond_frame,
939
+ point_inputs,
940
+ mask_inputs,
941
+ reverse,
942
+ run_mem_encoder,
943
+ prev_sam_mask_logits=None,
944
+ ):
945
+ """Run tracking on a single frame based on current inputs and previous memory."""
946
+ # Retrieve correct image features
947
+ (
948
+ _,
949
+ _,
950
+ current_vision_feats,
951
+ current_vision_pos_embeds,
952
+ feat_sizes,
953
+ ) = self._get_image_feature(inference_state, frame_idx, batch_size)
954
+
955
+ # point and mask should not appear as input simultaneously on the same frame
956
+ assert point_inputs is None or mask_inputs is None
957
+ current_out = self.track_step(
958
+ frame_idx=frame_idx,
959
+ is_init_cond_frame=is_init_cond_frame,
960
+ current_vision_feats=current_vision_feats,
961
+ current_vision_pos_embeds=current_vision_pos_embeds,
962
+ feat_sizes=feat_sizes,
963
+ point_inputs=point_inputs,
964
+ mask_inputs=mask_inputs,
965
+ output_dict=output_dict,
966
+ num_frames=inference_state["num_frames"],
967
+ track_in_reverse=reverse,
968
+ run_mem_encoder=run_mem_encoder,
969
+ prev_sam_mask_logits=prev_sam_mask_logits,
970
+ )
971
+
972
+ # optionally offload the output to CPU memory to save GPU space
973
+ storage_device = inference_state["storage_device"]
974
+ maskmem_features = current_out["maskmem_features"]
975
+ if maskmem_features is not None:
976
+ maskmem_features = maskmem_features.to(torch.bfloat16)
977
+ maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
978
+ pred_masks_gpu = current_out["pred_masks"]
979
+ # potentially fill holes in the predicted masks
980
+ if self.fill_hole_area > 0:
981
+ pred_masks_gpu = fill_holes_in_mask_scores(
982
+ pred_masks_gpu, self.fill_hole_area
983
+ )
984
+ pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True)
985
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
986
+ maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out)
987
+ # object pointer is a small tensor, so we always keep it on GPU memory for fast access
988
+ obj_ptr = current_out["obj_ptr"]
989
+ object_score_logits = current_out["object_score_logits"]
990
+ # make a compact version of this frame's output to reduce the state size
991
+ compact_current_out = {
992
+ "maskmem_features": maskmem_features,
993
+ "maskmem_pos_enc": maskmem_pos_enc,
994
+ "pred_masks": pred_masks,
995
+ "obj_ptr": obj_ptr,
996
+ "object_score_logits": object_score_logits,
997
+ }
998
+ return compact_current_out, pred_masks_gpu
999
+
1000
+ def _run_memory_encoder(
1001
+ self,
1002
+ inference_state,
1003
+ frame_idx,
1004
+ batch_size,
1005
+ high_res_masks,
1006
+ object_score_logits,
1007
+ is_mask_from_pts,
1008
+ ):
1009
+ """
1010
+ Run the memory encoder on `high_res_masks`. This is usually after applying
1011
+ non-overlapping constraints to object scores. Since their scores changed, their
1012
+ memory also need to be computed again with the memory encoder.
1013
+ """
1014
+ # Retrieve correct image features
1015
+ _, _, current_vision_feats, _, feat_sizes = self._get_image_feature(
1016
+ inference_state, frame_idx, batch_size
1017
+ )
1018
+ maskmem_features, maskmem_pos_enc = self._encode_new_memory(
1019
+ current_vision_feats=current_vision_feats,
1020
+ feat_sizes=feat_sizes,
1021
+ pred_masks_high_res=high_res_masks,
1022
+ object_score_logits=object_score_logits,
1023
+ is_mask_from_pts=is_mask_from_pts,
1024
+ )
1025
+
1026
+ # optionally offload the output to CPU memory to save GPU space
1027
+ storage_device = inference_state["storage_device"]
1028
+ maskmem_features = maskmem_features.to(torch.bfloat16)
1029
+ maskmem_features = maskmem_features.to(storage_device, non_blocking=True)
1030
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1031
+ maskmem_pos_enc = self._get_maskmem_pos_enc(
1032
+ inference_state, {"maskmem_pos_enc": maskmem_pos_enc}
1033
+ )
1034
+ return maskmem_features, maskmem_pos_enc
1035
+
1036
+ def _get_maskmem_pos_enc(self, inference_state, current_out):
1037
+ """
1038
+ `maskmem_pos_enc` is the same across frames and objects, so we cache it as
1039
+ a constant in the inference session to reduce session storage size.
1040
+ """
1041
+ model_constants = inference_state["constants"]
1042
+ # "out_maskmem_pos_enc" should be either a list of tensors or None
1043
+ out_maskmem_pos_enc = current_out["maskmem_pos_enc"]
1044
+ if out_maskmem_pos_enc is not None:
1045
+ if "maskmem_pos_enc" not in model_constants:
1046
+ assert isinstance(out_maskmem_pos_enc, list)
1047
+ # only take the slice for one object, since it's same across objects
1048
+ maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc]
1049
+ model_constants["maskmem_pos_enc"] = maskmem_pos_enc
1050
+ else:
1051
+ maskmem_pos_enc = model_constants["maskmem_pos_enc"]
1052
+ # expand the cached maskmem_pos_enc to the actual batch size
1053
+ batch_size = out_maskmem_pos_enc[0].size(0)
1054
+ expanded_maskmem_pos_enc = [
1055
+ x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc
1056
+ ]
1057
+ else:
1058
+ expanded_maskmem_pos_enc = None
1059
+ return expanded_maskmem_pos_enc
1060
+
1061
+ @torch.no_grad()
1062
+ def remove_object(self, inference_state, obj_id, strict=False, need_output=True):
1063
+ """
1064
+ Remove an object id from the tracking state. If strict is True, we check whether
1065
+ the object id actually exists and raise an error if it doesn't exist.
1066
+ """
1067
+ old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None)
1068
+ updated_frames = []
1069
+ # Check whether this object_id to remove actually exists and possibly raise an error.
1070
+ if old_obj_idx_to_rm is None:
1071
+ if not strict:
1072
+ return inference_state["obj_ids"], updated_frames
1073
+ raise RuntimeError(
1074
+ f"Cannot remove object id {obj_id} as it doesn't exist. "
1075
+ f"All existing object ids: {inference_state['obj_ids']}."
1076
+ )
1077
+
1078
+ # If this is the only remaining object id, we simply reset the state.
1079
+ if len(inference_state["obj_id_to_idx"]) == 1:
1080
+ self.reset_state(inference_state)
1081
+ return inference_state["obj_ids"], updated_frames
1082
+
1083
+ # There are still remaining objects after removing this object id. In this case,
1084
+ # we need to delete the object storage from inference state tensors.
1085
+ # Step 0: clear the input on those frames where this object id has point or mask input
1086
+ # (note that this step is required as it might downgrade conditioning frames to
1087
+ # non-conditioning ones)
1088
+ obj_input_frames_inds = set()
1089
+ obj_input_frames_inds.update(
1090
+ inference_state["point_inputs_per_obj"][old_obj_idx_to_rm]
1091
+ )
1092
+ obj_input_frames_inds.update(
1093
+ inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm]
1094
+ )
1095
+ for frame_idx in obj_input_frames_inds:
1096
+ self.clear_all_prompts_in_frame(
1097
+ inference_state, frame_idx, obj_id, need_output=False
1098
+ )
1099
+
1100
+ # Step 1: Update the object id mapping (note that it must be done after Step 0,
1101
+ # since Step 0 still requires the old object id mappings in inference_state)
1102
+ old_obj_ids = inference_state["obj_ids"]
1103
+ old_obj_inds = list(range(len(old_obj_ids)))
1104
+ remain_old_obj_inds = old_obj_inds.copy()
1105
+ remain_old_obj_inds.remove(old_obj_idx_to_rm)
1106
+ new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds]
1107
+ new_obj_inds = list(range(len(new_obj_ids)))
1108
+ # build new mappings
1109
+ old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds))
1110
+ inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds))
1111
+ inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids))
1112
+ inference_state["obj_ids"] = new_obj_ids
1113
+
1114
+ # Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys.
1115
+ # (note that "consolidated_frame_inds" doesn't need to be updated in this step as
1116
+ # it's already handled in Step 0)
1117
+ def _map_keys(container):
1118
+ new_kvs = []
1119
+ for k in old_obj_inds:
1120
+ v = container.pop(k)
1121
+ if k in old_idx_to_new_idx:
1122
+ new_kvs.append((old_idx_to_new_idx[k], v))
1123
+ container.update(new_kvs)
1124
+
1125
+ _map_keys(inference_state["point_inputs_per_obj"])
1126
+ _map_keys(inference_state["mask_inputs_per_obj"])
1127
+ _map_keys(inference_state["output_dict_per_obj"])
1128
+ _map_keys(inference_state["temp_output_dict_per_obj"])
1129
+
1130
+ # Step 3: For packed tensor storage, we index the remaining ids and rebuild the per-object slices.
1131
+ def _slice_state(output_dict, storage_key):
1132
+ for frame_idx, out in output_dict[storage_key].items():
1133
+ out["maskmem_features"] = out["maskmem_features"][remain_old_obj_inds]
1134
+ out["maskmem_pos_enc"] = [
1135
+ x[remain_old_obj_inds] for x in out["maskmem_pos_enc"]
1136
+ ]
1137
+ # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it
1138
+ out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(inference_state, out)
1139
+ out["pred_masks"] = out["pred_masks"][remain_old_obj_inds]
1140
+ out["obj_ptr"] = out["obj_ptr"][remain_old_obj_inds]
1141
+ out["object_score_logits"] = out["object_score_logits"][
1142
+ remain_old_obj_inds
1143
+ ]
1144
+ # also update the per-object slices
1145
+ self._add_output_per_object(
1146
+ inference_state, frame_idx, out, storage_key
1147
+ )
1148
+
1149
+ _slice_state(inference_state["output_dict"], "cond_frame_outputs")
1150
+ _slice_state(inference_state["output_dict"], "non_cond_frame_outputs")
1151
+
1152
+ # Step 4: Further collect the outputs on those frames in `obj_input_frames_inds`, which
1153
+ # could show an updated mask for objects previously occluded by the object being removed
1154
+ if need_output:
1155
+ temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"]
1156
+ for frame_idx in obj_input_frames_inds:
1157
+ is_cond = any(
1158
+ frame_idx in obj_temp_output_dict["cond_frame_outputs"]
1159
+ for obj_temp_output_dict in temp_output_dict_per_obj.values()
1160
+ )
1161
+ consolidated_out = self._consolidate_temp_output_across_obj(
1162
+ inference_state,
1163
+ frame_idx,
1164
+ is_cond=is_cond,
1165
+ run_mem_encoder=False,
1166
+ consolidate_at_video_res=True,
1167
+ )
1168
+ _, video_res_masks = self._get_orig_video_res_output(
1169
+ inference_state, consolidated_out["pred_masks_video_res"]
1170
+ )
1171
+ updated_frames.append((frame_idx, video_res_masks))
1172
+
1173
+ return inference_state["obj_ids"], updated_frames
1174
+
1175
+ def _clear_non_cond_mem_around_input(self, inference_state, frame_idx):
1176
+ """
1177
+ Remove the non-conditioning memory around the input frame. When users provide
1178
+ correction clicks, the surrounding frames' non-conditioning memories can still
1179
+ contain outdated object appearance information and could confuse the model.
1180
+
1181
+ This method clears those non-conditioning memories surrounding the interacted
1182
+ frame to avoid giving the model both old and new information about the object.
1183
+ """
1184
+ r = self.memory_temporal_stride_for_eval
1185
+ frame_idx_begin = frame_idx - r * self.num_maskmem
1186
+ frame_idx_end = frame_idx + r * self.num_maskmem
1187
+ output_dict = inference_state["output_dict"]
1188
+ non_cond_frame_outputs = output_dict["non_cond_frame_outputs"]
1189
+ for t in range(frame_idx_begin, frame_idx_end + 1):
1190
+ non_cond_frame_outputs.pop(t, None)
1191
+ for obj_output_dict in inference_state["output_dict_per_obj"].values():
1192
+ obj_output_dict["non_cond_frame_outputs"].pop(t, None)
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/amg.py ADDED
@@ -0,0 +1,523 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import math
8
+ from copy import deepcopy
9
+ from dataclasses import dataclass
10
+ from itertools import product
11
+ from typing import Any, Dict, Generator, ItemsView, List, Tuple
12
+
13
+ import numpy as np
14
+ import torch
15
+
16
+
17
+ @dataclass
18
+ class RLEData:
19
+ alt_lens_nt: torch.Tensor
20
+ counts_init: torch.Tensor
21
+ b: int
22
+ h: int
23
+ w: int
24
+
25
+ def __len__(self):
26
+ return self.b
27
+
28
+
29
+ def nt_index_select_dim_0(nt, index):
30
+ values = nt.values()
31
+ offsets = nt.offsets()
32
+ lengths = offsets.diff()
33
+ offsets_index = offsets[index].cpu()
34
+ lengths_index = lengths[index].cpu()
35
+ indices = [o + torch.arange(l) for (o, l) in zip(offsets_index, lengths_index)]
36
+ indices = torch.cat(indices).to(values.device)
37
+ values_index = torch.index_select(values, 0, indices)
38
+ lengths_index = lengths_index.to(values.device)
39
+ return torch.nested.nested_tensor_from_jagged(values_index, lengths=lengths_index)
40
+
41
+
42
+ def nt_cat_dim_0(nts: List[torch.Tensor]):
43
+ all_values = []
44
+ all_lengths = []
45
+ for nt in nts:
46
+ all_values.append(nt.values())
47
+ all_lengths.append(nt.offsets().diff())
48
+ new_values = torch.cat(all_values)
49
+ new_lengths = torch.cat(all_lengths)
50
+ return torch.nested.nested_tensor_from_jagged(new_values, lengths=new_lengths)
51
+
52
+
53
+ # Very lightly adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/utils/amg.py
54
+ class MaskData:
55
+ """
56
+ A structure for storing masks and their related data in batched format.
57
+ Implements basic filtering and concatenation.
58
+ """
59
+
60
+ def __init__(self, **kwargs) -> None:
61
+ for v in kwargs.values():
62
+ assert isinstance(v, (list, np.ndarray, torch.Tensor, RLEData)), (
63
+ "MaskData only supports list, numpy arrays, and torch tensors."
64
+ )
65
+ self._stats = dict(**kwargs)
66
+
67
+ def __setitem__(self, key: str, item: Any) -> None:
68
+ assert isinstance(item, (list, np.ndarray, torch.Tensor, RLEData)), (
69
+ "MaskData only supports list, numpy arrays, and torch tensors."
70
+ )
71
+ self._stats[key] = item
72
+
73
+ def __delitem__(self, key: str) -> None:
74
+ del self._stats[key]
75
+
76
+ def __getitem__(self, key: str) -> Any:
77
+ return self._stats[key]
78
+
79
+ def items(self) -> ItemsView[str, Any]:
80
+ return self._stats.items()
81
+
82
+ def filter(self, keep: torch.Tensor) -> None:
83
+ for k, v in self._stats.items():
84
+ if v is None:
85
+ self._stats[k] = None
86
+ elif isinstance(v, torch.Tensor):
87
+ # self._stats[k] = v[torch.as_tensor(keep, device=v.device)]
88
+ self._stats[k] = v[keep]
89
+ elif isinstance(v, np.ndarray):
90
+ self._stats[k] = v[keep.detach().cpu().numpy()]
91
+ elif isinstance(v, list) and keep.dtype == torch.bool:
92
+ self._stats[k] = [a for i, a in enumerate(v) if keep[i]]
93
+ elif isinstance(v, list):
94
+ self._stats[k] = [v[i] for i in keep]
95
+ elif isinstance(v, RLEData):
96
+ new_alt_lens_nt = nt_index_select_dim_0(v.alt_lens_nt, keep)
97
+ self._stats[k] = RLEData(
98
+ alt_lens_nt=new_alt_lens_nt,
99
+ counts_init=v.counts_init[keep],
100
+ b=new_alt_lens_nt.size(0),
101
+ h=v.h,
102
+ w=v.w,
103
+ )
104
+ else:
105
+ raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
106
+
107
+ def cat(self, new_stats: "MaskData") -> None:
108
+ for k, v in new_stats.items():
109
+ if k not in self._stats or self._stats[k] is None:
110
+ self._stats[k] = deepcopy(v)
111
+ elif isinstance(v, torch.Tensor):
112
+ self._stats[k] = torch.cat([self._stats[k], v], dim=0)
113
+ elif isinstance(v, np.ndarray):
114
+ self._stats[k] = np.concatenate([self._stats[k], v], axis=0)
115
+ elif isinstance(v, list):
116
+ self._stats[k] = self._stats[k] + deepcopy(v)
117
+ elif isinstance(v, RLEData):
118
+ assert self._stats[k].h == v.h
119
+ assert self._stats[k].w == v.w
120
+ self._stats[k] = RLEData(
121
+ alt_lens_nt=nt_cat_dim_0(
122
+ [self._stats[k].alt_lens_nt, v.alt_lens_nt]
123
+ ),
124
+ counts_init=torch.cat([self._stats[k].counts_init, v.counts_init]),
125
+ b=self._stats[k].b + v.b,
126
+ h=v.h,
127
+ w=v.w,
128
+ )
129
+ else:
130
+ raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
131
+
132
+ def to_numpy(self) -> None:
133
+ for k, v in self._stats.items():
134
+ if isinstance(v, torch.Tensor):
135
+ self._stats[k] = v.float().detach().cpu().numpy()
136
+
137
+
138
+ def is_box_near_crop_edge_torch(
139
+ boxes: torch.Tensor,
140
+ crop_box: List[int],
141
+ crop_box_torch: torch.Tensor,
142
+ orig_box_torch: torch.Tensor,
143
+ atol: float = 20.0,
144
+ ) -> torch.Tensor:
145
+ """Filter masks at the edge of a crop, but not at the edge of the original image."""
146
+ boxes = uncrop_boxes_xyxy(boxes, crop_box).float()
147
+ near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)
148
+ near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)
149
+ near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)
150
+ return torch.any(near_crop_edge, dim=1)
151
+
152
+
153
+ def is_box_near_crop_edge(
154
+ boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0
155
+ ) -> torch.Tensor:
156
+ crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
157
+ orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)
158
+ return is_box_near_crop_edge_torch(
159
+ boxes, crop_box, crop_box_torch, orig_box_torch, atol
160
+ )
161
+
162
+
163
+ def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor:
164
+ box_xywh = deepcopy(box_xyxy)
165
+ box_xywh[2] = box_xywh[2] - box_xywh[0]
166
+ box_xywh[3] = box_xywh[3] - box_xywh[1]
167
+ return box_xywh
168
+
169
+
170
+ def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:
171
+ assert len(args) > 0 and all(len(a) == len(args[0]) for a in args), (
172
+ "Batched iteration must have inputs of all the same size."
173
+ )
174
+ n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)
175
+ for b in range(n_batches):
176
+ yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args]
177
+
178
+
179
+ def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:
180
+ """
181
+ Encodes masks to an uncompressed RLE, in the format expected by
182
+ pycoco tools.
183
+ """
184
+ # Put in fortran order and flatten h,w
185
+ b, h, w = tensor.shape
186
+ tensor = tensor.permute(0, 2, 1).flatten(1)
187
+
188
+ # Compute change indices
189
+ diff = tensor[:, 1:] ^ tensor[:, :-1]
190
+ change_indices = diff.nonzero()
191
+
192
+ # Encode run length
193
+ out = []
194
+ for i in range(b):
195
+ cur_idxs = change_indices[change_indices[:, 0] == i, 1]
196
+ cur_idxs = torch.cat(
197
+ [
198
+ torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device),
199
+ cur_idxs + 1,
200
+ torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device),
201
+ ]
202
+ )
203
+ btw_idxs = cur_idxs[1:] - cur_idxs[:-1]
204
+ counts = [] if tensor[i, 0] == 0 else [0]
205
+ counts.extend(btw_idxs.detach().cpu().tolist())
206
+ out.append({"size": [h, w], "counts": counts})
207
+ return out
208
+
209
+
210
+ def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
211
+ """Compute a binary mask from an uncompressed RLE."""
212
+ h, w = rle["size"]
213
+ mask = np.empty(h * w, dtype=bool)
214
+ idx = 0
215
+ parity = False
216
+ for count in rle["counts"]:
217
+ mask[idx : idx + count] = parity
218
+ idx += count
219
+ parity ^= True
220
+ mask = mask.reshape(w, h)
221
+ return mask.transpose() # Put in C order
222
+
223
+
224
+ # @torch.compile(fullgraph=True, dynamic=True)
225
+ def _mask_to_rle_pytorch_2_0_0(tensor: torch.Tensor) -> (torch.Tensor, torch.Tensor):
226
+ """
227
+ Encodes masks to an uncompressed RLE, in the format expected by
228
+ pycoco tools.
229
+ """
230
+ # Put in fortran order and flatten h,w
231
+ b, h, w = tensor.shape
232
+ tensor = tensor.permute(0, 2, 1).flatten(1)
233
+
234
+ # Compute change indices
235
+ diff = tensor[:, 1:] ^ tensor[:, :-1]
236
+ # a = torch.tensor([[True]])
237
+ a = torch.ones((1, 1), dtype=bool, device=diff.device)
238
+ # if diff.is_cuda:
239
+ # a = a.pin_memory().cuda()
240
+ # # a = a.to(diff.device)
241
+ a = a.expand_as(diff.narrow(1, 0, 1))
242
+ diff = torch.cat([a, diff, a], dim=1)
243
+ return diff
244
+
245
+
246
+ # @torch.compile(fullgraph=True, dynamic=True)
247
+ def _mask_to_rle_pytorch_2_0_1(
248
+ tensor: torch.Tensor, diff: torch.Tensor, change_indices: torch.Tensor
249
+ ) -> (torch.Tensor, torch.Tensor):
250
+ tensor = tensor.permute(0, 2, 1).flatten(1)
251
+
252
+ alt_lens = diff.sum(dim=1)
253
+
254
+ all_cur_idx = change_indices[:, 1]
255
+ if all_cur_idx.numel() == 0:
256
+ all_cur_idx_0 = all_cur_idx
257
+ all_cur_idx_1 = all_cur_idx
258
+ else:
259
+ all_cur_idx_0 = all_cur_idx.narrow(0, 1, all_cur_idx.size(0) - 1)
260
+ all_cur_idx_1 = all_cur_idx.narrow(0, 0, 1)
261
+ all_btw_idx = torch.cat([all_cur_idx_0, all_cur_idx_1])
262
+ all_btw_idx = all_btw_idx - all_cur_idx
263
+
264
+ alt_lens_nt = torch.nested.nested_tensor_from_jagged(all_btw_idx, lengths=alt_lens)
265
+ # Encode run length
266
+ counts_init = tensor[:, 0] == 0
267
+ return alt_lens_nt, counts_init
268
+
269
+
270
+ def _mask_to_rle_pytorch_2_0(tensor: torch.Tensor) -> RLEData:
271
+ b, h, w = tensor.shape
272
+ with torch.autograd.profiler.record_function(
273
+ "mask_to_rle_pytorch_2: _mask_to_rle_pytorch_2_0_0"
274
+ ):
275
+ diff = _mask_to_rle_pytorch_2_0_0(tensor)
276
+ with torch.autograd.profiler.record_function("mask_to_rle_pytorch_2: nonzero"):
277
+ # NOTE: While we could operate on less chunks, a set number of chunks prevents recompilations
278
+ # if diff.numel() > 2147483646:
279
+ # num_chunks = (diff.numel() + 2147483646) // 2147483646
280
+ # change_indices = torch.cat([d.nonzero() for d in diff.chunk(num_chunks)])
281
+ # else:
282
+ # change_indices = diff.nonzero()
283
+ num_chunks = 8
284
+ assert num_chunks >= ((diff.numel() + 2147483646) // 2147483646), (
285
+ "Needed more chunks than expected."
286
+ )
287
+ change_indices = torch.cat([d.nonzero() for d in diff.chunk(num_chunks)])
288
+ with torch.autograd.profiler.record_function(
289
+ "mask_to_rle_pytorch_2: _mask_to_rle_pytorch_2_0_1"
290
+ ):
291
+ alt_lens_nt, counts_init = _mask_to_rle_pytorch_2_0_1(
292
+ tensor, diff, change_indices
293
+ )
294
+ return RLEData(alt_lens_nt=alt_lens_nt, counts_init=counts_init, b=b, h=h, w=w)
295
+
296
+
297
+ def _mask_to_rle_pytorch_2_1(rle_data: RLEData):
298
+ with torch.autograd.profiler.record_function(
299
+ "mask_to_rle_pytorch_2: Encode run length"
300
+ ):
301
+ out = []
302
+ alt_lens = rle_data.alt_lens_nt.offsets().diff()
303
+ all_btw_idx = rle_data.alt_lens_nt.values()
304
+ alt_lens = alt_lens.tolist()
305
+ all_btw_idx = all_btw_idx.tolist()
306
+ counts_init = rle_data.counts_init.tolist()
307
+ offset = 0
308
+ for i, ci in zip(range(rle_data.b), counts_init):
309
+ btw_idxs = all_btw_idx[offset : offset + alt_lens[i]][:-1]
310
+ offset += alt_lens[i]
311
+ counts = [] if ci else [0]
312
+ counts.extend(btw_idxs)
313
+ out.append({"size": [rle_data.h, rle_data.w], "counts": counts})
314
+
315
+ return out
316
+
317
+
318
+ def mask_to_rle_pytorch_2(tensor: torch.Tensor) -> List[Dict[str, Any]]:
319
+ with torch.autograd.profiler.record_function("mask_to_rle_pytorch_2"):
320
+ return _mask_to_rle_pytorch_2_1(_mask_to_rle_pytorch_2_0(tensor))
321
+
322
+
323
+ def area_from_rle(rle: Dict[str, Any]) -> int:
324
+ return sum(rle["counts"][1::2])
325
+
326
+
327
+ # TODO: Turn this on if you can mitigate recompiles!
328
+ # @torch.compile(fullgraph=True, dynamic=True)
329
+ def calculate_stability_score(
330
+ masks: torch.Tensor, mask_threshold: float, threshold_offset: float
331
+ ) -> torch.Tensor:
332
+ """
333
+ Computes the stability score for a batch of masks. The stability
334
+ score is the IoU between the binary masks obtained by thresholding
335
+ the predicted mask logits at high and low values.
336
+ """
337
+ # One mask is always contained inside the other.
338
+ # Save memory by preventing unnecessary cast to torch.int64
339
+ intersections = (
340
+ (masks > (mask_threshold + threshold_offset))
341
+ .sum(-1, dtype=torch.int16)
342
+ .sum(-1, dtype=torch.int32)
343
+ )
344
+ unions = (
345
+ (masks > (mask_threshold - threshold_offset))
346
+ .sum(-1, dtype=torch.int16)
347
+ .sum(-1, dtype=torch.int32)
348
+ )
349
+ return intersections / unions
350
+
351
+
352
+ def build_point_grid(n_per_side: int) -> np.ndarray:
353
+ """Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""
354
+ offset = 1 / (2 * n_per_side)
355
+ points_one_side = np.linspace(offset, 1 - offset, n_per_side)
356
+ points_x = np.tile(points_one_side[None, :], (n_per_side, 1))
357
+ points_y = np.tile(points_one_side[:, None], (1, n_per_side))
358
+ points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2)
359
+ return points
360
+
361
+
362
+ def build_all_layer_point_grids(
363
+ n_per_side: int, n_layers: int, scale_per_layer: int
364
+ ) -> List[np.ndarray]:
365
+ """Generates point grids for all crop layers."""
366
+ points_by_layer = []
367
+ for i in range(n_layers + 1):
368
+ n_points = int(n_per_side / (scale_per_layer**i))
369
+ points_by_layer.append(build_point_grid(n_points))
370
+ return points_by_layer
371
+
372
+
373
+ def generate_crop_boxes(
374
+ im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float
375
+ ) -> Tuple[List[List[int]], List[int]]:
376
+ """
377
+ Generates a list of crop boxes of different sizes. Each layer
378
+ has (2**i)**2 boxes for the ith layer.
379
+ """
380
+ crop_boxes, layer_idxs = [], []
381
+ im_h, im_w = im_size
382
+ short_side = min(im_h, im_w)
383
+
384
+ # Original image
385
+ crop_boxes.append([0, 0, im_w, im_h])
386
+ layer_idxs.append(0)
387
+
388
+ def crop_len(orig_len, n_crops, overlap):
389
+ return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops))
390
+
391
+ for i_layer in range(n_layers):
392
+ n_crops_per_side = 2 ** (i_layer + 1)
393
+ overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))
394
+
395
+ crop_w = crop_len(im_w, n_crops_per_side, overlap)
396
+ crop_h = crop_len(im_h, n_crops_per_side, overlap)
397
+
398
+ crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)]
399
+ crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)]
400
+
401
+ # Crops in XYWH format
402
+ for x0, y0 in product(crop_box_x0, crop_box_y0):
403
+ box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)]
404
+ crop_boxes.append(box)
405
+ layer_idxs.append(i_layer + 1)
406
+
407
+ return crop_boxes, layer_idxs
408
+
409
+
410
+ def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
411
+ x0, y0, _, _ = crop_box
412
+ offset = torch.tensor([[x0, y0, x0, y0]]).pin_memory()
413
+ offset = offset.to(device=boxes.device, non_blocking=True)
414
+ # Check if boxes has a channel dimension
415
+ if len(boxes.shape) == 3:
416
+ offset = offset.unsqueeze(1)
417
+ return boxes + offset
418
+
419
+
420
+ def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
421
+ x0, y0, _, _ = crop_box
422
+ offset = torch.tensor([[x0, y0]]).pin_memory()
423
+ offset = offset.to(device=points.device, non_blocking=True)
424
+ # Check if points has a channel dimension
425
+ if len(points.shape) == 3:
426
+ offset = offset.unsqueeze(1)
427
+ return points + offset
428
+
429
+
430
+ def uncrop_masks(
431
+ masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int
432
+ ) -> torch.Tensor:
433
+ x0, y0, x1, y1 = crop_box
434
+ if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h:
435
+ return masks
436
+ # Coordinate transform masks
437
+ pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0)
438
+ pad = (x0, pad_x - x0, y0, pad_y - y0)
439
+ return torch.nn.functional.pad(masks, pad, value=0)
440
+
441
+
442
+ def remove_small_regions(
443
+ mask: np.ndarray, area_thresh: float, mode: str
444
+ ) -> Tuple[np.ndarray, bool]:
445
+ """
446
+ Removes small disconnected regions and holes in a mask. Returns the
447
+ mask and an indicator of if the mask has been modified.
448
+ """
449
+ import cv2 # type: ignore
450
+
451
+ assert mode in ["holes", "islands"]
452
+ correct_holes = mode == "holes"
453
+ working_mask = (correct_holes ^ mask).astype(np.uint8)
454
+ n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)
455
+ sizes = stats[:, -1][1:] # Row 0 is background label
456
+ small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]
457
+ if len(small_regions) == 0:
458
+ return mask, False
459
+ fill_labels = [0] + small_regions
460
+ if not correct_holes:
461
+ fill_labels = [i for i in range(n_labels) if i not in fill_labels]
462
+ # If every region is below threshold, keep largest
463
+ if len(fill_labels) == 0:
464
+ fill_labels = [int(np.argmax(sizes)) + 1]
465
+ mask = np.isin(regions, fill_labels)
466
+ return mask, True
467
+
468
+
469
+ def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]:
470
+ from pycocotools import mask as mask_utils # type: ignore
471
+
472
+ h, w = uncompressed_rle["size"]
473
+ rle = mask_utils.frPyObjects(uncompressed_rle, h, w)
474
+ rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json
475
+ return rle
476
+
477
+
478
+ # TODO: Turn this on if you can mitigate recompiles!
479
+ # @torch.compile(fullgraph=True, dynamic=True)
480
+ def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:
481
+ """
482
+ Calculates boxes in XYXY format around masks. Return [0,0,0,0] for
483
+ an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
484
+ """
485
+ # # torch.max below raises an error on empty inputs, just skip in this case
486
+ # if torch.numel(masks) == 0:
487
+ # return torch.zeros(*masks.shape[:-2], 4, device=masks.device)
488
+
489
+ # Normalize shape to CxHxW
490
+ shape = masks.shape
491
+ h, w = shape[-2:]
492
+ if len(shape) > 2:
493
+ masks = masks.flatten(0, -3)
494
+ else:
495
+ masks = masks.unsqueeze(0)
496
+
497
+ # Get top and bottom edges
498
+ in_height, _ = torch.max(masks, dim=-1)
499
+ in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]
500
+ bottom_edges, _ = torch.max(in_height_coords, dim=-1)
501
+ in_height_coords = in_height_coords + h * (~in_height)
502
+ top_edges, _ = torch.min(in_height_coords, dim=-1)
503
+
504
+ # Get left and right edges
505
+ in_width, _ = torch.max(masks, dim=-2)
506
+ in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]
507
+ right_edges, _ = torch.max(in_width_coords, dim=-1)
508
+ in_width_coords = in_width_coords + w * (~in_width)
509
+ left_edges, _ = torch.min(in_width_coords, dim=-1)
510
+
511
+ # If the mask is empty the right edge will be to the left of the left edge.
512
+ # Replace these boxes with [0, 0, 0, 0]
513
+ empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
514
+ out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)
515
+ out = out * (~empty_filter).unsqueeze(-1)
516
+
517
+ # Return to original shape
518
+ if len(shape) > 2:
519
+ out = out.reshape(*shape[:-2], 4)
520
+ else:
521
+ out = out[0]
522
+
523
+ return out
tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/misc.py ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ # All rights reserved.
3
+
4
+ # This source code is licensed under the license found in the
5
+ # LICENSE file in the root directory of this source tree.
6
+
7
+ import os
8
+ import warnings
9
+ from threading import Thread
10
+ from typing import Tuple, Union
11
+
12
+ import numpy as np
13
+ import torch
14
+ from PIL import Image
15
+ from tqdm import tqdm
16
+
17
+
18
+ def get_sdpa_settings():
19
+ if torch.cuda.is_available():
20
+ old_gpu = torch.cuda.get_device_properties(0).major < 7
21
+ # only use Flash Attention on Ampere (8.0) or newer GPUs
22
+ use_flash_attn = torch.cuda.get_device_properties(0).major >= 8
23
+ if not use_flash_attn:
24
+ warnings.warn(
25
+ "Flash Attention is disabled as it requires a GPU with Ampere (8.0) CUDA capability.",
26
+ category=UserWarning,
27
+ stacklevel=2,
28
+ )
29
+ # keep math kernel for PyTorch versions before 2.2 (Flash Attention v2 is only
30
+ # available on PyTorch 2.2+, while Flash Attention v1 cannot handle all cases)
31
+ pytorch_version = tuple(int(v) for v in torch.__version__.split(".")[:2])
32
+ if pytorch_version < (2, 2):
33
+ warnings.warn(
34
+ f"You are using PyTorch {torch.__version__} without Flash Attention v2 support. "
35
+ "Consider upgrading to PyTorch 2.2+ for Flash Attention v2 (which could be faster).",
36
+ category=UserWarning,
37
+ stacklevel=2,
38
+ )
39
+ math_kernel_on = pytorch_version < (2, 2) or not use_flash_attn
40
+ else:
41
+ old_gpu = True
42
+ use_flash_attn = False
43
+ math_kernel_on = True
44
+
45
+ return old_gpu, use_flash_attn, math_kernel_on
46
+
47
+
48
+ def get_connected_components(mask):
49
+ """
50
+ Get the connected components (8-connectivity) of binary masks of shape (N, 1, H, W).
51
+
52
+ Inputs:
53
+ - mask: A binary mask tensor of shape (N, 1, H, W), where 1 is foreground and 0 is
54
+ background.
55
+
56
+ Outputs:
57
+ - labels: A tensor of shape (N, 1, H, W) containing the connected component labels
58
+ for foreground pixels and 0 for background pixels.
59
+ - counts: A tensor of shape (N, 1, H, W) containing the area of the connected
60
+ components for foreground pixels and 0 for background pixels.
61
+ """
62
+ from sam2 import _C
63
+
64
+ return _C.get_connected_componnets(mask.to(torch.uint8).contiguous())
65
+
66
+
67
+ def mask_to_box(masks: torch.Tensor):
68
+ """
69
+ compute bounding box given an input mask
70
+
71
+ Inputs:
72
+ - masks: [B, 1, H, W] masks, dtype=torch.Tensor
73
+
74
+ Returns:
75
+ - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor
76
+ """
77
+ B, _, h, w = masks.shape
78
+ device = masks.device
79
+ xs = torch.arange(w, device=device, dtype=torch.int32)
80
+ ys = torch.arange(h, device=device, dtype=torch.int32)
81
+ grid_xs, grid_ys = torch.meshgrid(xs, ys, indexing="xy")
82
+ grid_xs = grid_xs[None, None, ...].expand(B, 1, h, w)
83
+ grid_ys = grid_ys[None, None, ...].expand(B, 1, h, w)
84
+ min_xs, _ = torch.min(torch.where(masks, grid_xs, w).flatten(-2), dim=-1)
85
+ max_xs, _ = torch.max(torch.where(masks, grid_xs, -1).flatten(-2), dim=-1)
86
+ min_ys, _ = torch.min(torch.where(masks, grid_ys, h).flatten(-2), dim=-1)
87
+ max_ys, _ = torch.max(torch.where(masks, grid_ys, -1).flatten(-2), dim=-1)
88
+ bbox_coords = torch.stack((min_xs, min_ys, max_xs, max_ys), dim=-1)
89
+
90
+ return bbox_coords
91
+
92
+
93
+ def _load_img_as_tensor(img_path, image_size):
94
+ img_pil = Image.open(img_path)
95
+ img_np = np.array(img_pil.convert("RGB").resize((image_size, image_size)))
96
+ if img_np.dtype == np.uint8: # np.uint8 is expected for JPEG images
97
+ img_np = img_np / 255.0
98
+ else:
99
+ raise RuntimeError(f"Unknown image dtype: {img_np.dtype} on {img_path}")
100
+ img = torch.from_numpy(img_np).permute(2, 0, 1)
101
+ video_width, video_height = img_pil.size # the original video size
102
+ return img, video_height, video_width
103
+
104
+
105
+ class AsyncVideoFrameLoader:
106
+ """
107
+ A list of video frames to be load asynchronously without blocking session start.
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ img_paths,
113
+ image_size,
114
+ offload_video_to_cpu,
115
+ img_mean,
116
+ img_std,
117
+ compute_device,
118
+ ):
119
+ self.img_paths = img_paths
120
+ self.image_size = image_size
121
+ self.offload_video_to_cpu = offload_video_to_cpu
122
+ self.img_mean = img_mean
123
+ self.img_std = img_std
124
+ # items in `self.images` will be loaded asynchronously
125
+ self.images = [None] * len(img_paths)
126
+ # catch and raise any exceptions in the async loading thread
127
+ self.exception = None
128
+ # video_height and video_width be filled when loading the first image
129
+ self.video_height = None
130
+ self.video_width = None
131
+ self.compute_device = compute_device
132
+
133
+ # load the first frame to fill video_height and video_width and also
134
+ # to cache it (since it's most likely where the user will click)
135
+ self.__getitem__(0)
136
+
137
+ # load the rest of frames asynchronously without blocking the session start
138
+ def _load_frames():
139
+ try:
140
+ for n in tqdm(range(len(self.images)), desc="frame loading (JPEG)"):
141
+ self.__getitem__(n)
142
+ except Exception as e:
143
+ self.exception = e
144
+
145
+ self.thread = Thread(target=_load_frames, daemon=True)
146
+ self.thread.start()
147
+
148
+ def __getitem__(self, index):
149
+ if self.exception is not None:
150
+ raise RuntimeError("Failure in frame loading thread") from self.exception
151
+
152
+ img = self.images[index]
153
+ if img is not None:
154
+ return img
155
+
156
+ img, video_height, video_width = _load_img_as_tensor(
157
+ self.img_paths[index], self.image_size
158
+ )
159
+ self.video_height = video_height
160
+ self.video_width = video_width
161
+ # normalize by mean and std
162
+ img -= self.img_mean
163
+ img /= self.img_std
164
+ if not self.offload_video_to_cpu:
165
+ img = img.to(self.compute_device, non_blocking=True)
166
+ self.images[index] = img
167
+ return img
168
+
169
+ def __len__(self):
170
+ return len(self.images)
171
+
172
+
173
+ def load_video_frames(
174
+ video_path,
175
+ image_size,
176
+ offload_video_to_cpu,
177
+ img_mean=(0.485, 0.456, 0.406),
178
+ img_std=(0.229, 0.224, 0.225),
179
+ async_loading_frames=False,
180
+ compute_device=torch.device("cuda"),
181
+ ):
182
+ """
183
+ Load the video frames from video_path. The frames are resized to image_size as in
184
+ the model and are loaded to GPU if offload_video_to_cpu=False. This is used by the demo.
185
+ """
186
+ is_bytes = isinstance(video_path, bytes)
187
+ is_str = isinstance(video_path, str)
188
+ is_mp4_path = is_str and os.path.splitext(video_path)[-1] in [".mp4", ".MP4"]
189
+ if is_bytes or is_mp4_path:
190
+ return load_video_frames_from_video_file(
191
+ video_path=video_path,
192
+ image_size=image_size,
193
+ offload_video_to_cpu=offload_video_to_cpu,
194
+ img_mean=img_mean,
195
+ img_std=img_std,
196
+ compute_device=compute_device,
197
+ )
198
+ elif is_str and os.path.isdir(video_path):
199
+ return load_video_frames_from_jpg_images(
200
+ video_path=video_path,
201
+ image_size=image_size,
202
+ offload_video_to_cpu=offload_video_to_cpu,
203
+ img_mean=img_mean,
204
+ img_std=img_std,
205
+ async_loading_frames=async_loading_frames,
206
+ compute_device=compute_device,
207
+ )
208
+ else:
209
+ raise NotImplementedError(
210
+ "Only MP4 video and JPEG folder are supported at this moment"
211
+ )
212
+
213
+
214
+ def load_video_frames_from_jpg_images(
215
+ video_path,
216
+ image_size,
217
+ offload_video_to_cpu,
218
+ img_mean=(0.485, 0.456, 0.406),
219
+ img_std=(0.229, 0.224, 0.225),
220
+ async_loading_frames=False,
221
+ compute_device=torch.device("cuda"),
222
+ ):
223
+ """
224
+ Load the video frames from a directory of JPEG files ("<frame_index>.jpg" format).
225
+
226
+ The frames are resized to image_size x image_size and are loaded to GPU if
227
+ `offload_video_to_cpu` is `False` and to CPU if `offload_video_to_cpu` is `True`.
228
+
229
+ You can load a frame asynchronously by setting `async_loading_frames` to `True`.
230
+ """
231
+ if isinstance(video_path, str) and os.path.isdir(video_path):
232
+ jpg_folder = video_path
233
+ else:
234
+ raise NotImplementedError(
235
+ "Only JPEG frames are supported at this moment. For video files, you may use "
236
+ "ffmpeg (https://ffmpeg.org/) to extract frames into a folder of JPEG files, such as \n"
237
+ "```\n"
238
+ "ffmpeg -i <your_video>.mp4 -q:v 2 -start_number 0 <output_dir>/'%05d.jpg'\n"
239
+ "```\n"
240
+ "where `-q:v` generates high-quality JPEG frames and `-start_number 0` asks "
241
+ "ffmpeg to start the JPEG file from 00000.jpg."
242
+ )
243
+
244
+ frame_names = [
245
+ p
246
+ for p in os.listdir(jpg_folder)
247
+ if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"]
248
+ ]
249
+ frame_names.sort(key=lambda p: int(os.path.splitext(p)[0]))
250
+ num_frames = len(frame_names)
251
+ if num_frames == 0:
252
+ raise RuntimeError(f"no images found in {jpg_folder}")
253
+ img_paths = [os.path.join(jpg_folder, frame_name) for frame_name in frame_names]
254
+ img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None]
255
+ img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None]
256
+
257
+ if async_loading_frames:
258
+ lazy_images = AsyncVideoFrameLoader(
259
+ img_paths,
260
+ image_size,
261
+ offload_video_to_cpu,
262
+ img_mean,
263
+ img_std,
264
+ compute_device,
265
+ )
266
+ return lazy_images, lazy_images.video_height, lazy_images.video_width
267
+
268
+ images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float32)
269
+ for n, img_path in enumerate(tqdm(img_paths, desc="frame loading (JPEG)")):
270
+ images[n], video_height, video_width = _load_img_as_tensor(img_path, image_size)
271
+ if not offload_video_to_cpu:
272
+ images = images.to(compute_device)
273
+ img_mean = img_mean.to(compute_device)
274
+ img_std = img_std.to(compute_device)
275
+ # normalize by mean and std
276
+ images -= img_mean
277
+ images /= img_std
278
+ return images, video_height, video_width
279
+
280
+
281
+ def load_video_frames_from_video_file(
282
+ video_path,
283
+ image_size,
284
+ offload_video_to_cpu,
285
+ img_mean=(0.485, 0.456, 0.406),
286
+ img_std=(0.229, 0.224, 0.225),
287
+ compute_device=torch.device("cuda"),
288
+ ):
289
+ """Load the video frames from a video file."""
290
+ import decord
291
+
292
+ img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None]
293
+ img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None]
294
+ # Get the original video height and width
295
+ decord.bridge.set_bridge("torch")
296
+ video_height, video_width, _ = decord.VideoReader(video_path).next().shape
297
+ # Iterate over all frames in the video
298
+ images = []
299
+ for frame in decord.VideoReader(video_path, width=image_size, height=image_size):
300
+ images.append(frame.permute(2, 0, 1))
301
+
302
+ images = torch.stack(images, dim=0).float() / 255.0
303
+ if not offload_video_to_cpu:
304
+ images = images.to(compute_device)
305
+ img_mean = img_mean.to(compute_device)
306
+ img_std = img_std.to(compute_device)
307
+ # normalize by mean and std
308
+ images -= img_mean
309
+ images /= img_std
310
+ return images, video_height, video_width
311
+
312
+
313
+ def fill_holes_in_mask_scores(mask, max_area):
314
+ """
315
+ A post processor to fill small holes in mask scores with area under `max_area`.
316
+ """
317
+ # Holes are those connected components in background with area <= self.max_area
318
+ # (background regions are those with mask scores <= 0)
319
+ assert max_area > 0, "max_area must be positive"
320
+
321
+ input_mask = mask
322
+ try:
323
+ labels, areas = get_connected_components(mask <= 0)
324
+ is_hole = (labels > 0) & (areas <= max_area)
325
+ # We fill holes with a small positive mask score (0.1) to change them to foreground.
326
+ mask = torch.where(is_hole, 0.1, mask)
327
+ except Exception as e:
328
+ # Skip the post-processing step on removing small holes if the CUDA kernel fails
329
+ warnings.warn(
330
+ f"{e}\n\nSkipping the post-processing step due to the error above. You can "
331
+ "still use SAM 2 and it's OK to ignore the error above, although some post-processing "
332
+ "functionality may be limited (which doesn't affect the results in most cases; see "
333
+ "https://github.com/facebookresearch/sam2/blob/main/INSTALL.md).",
334
+ category=UserWarning,
335
+ stacklevel=2,
336
+ )
337
+ mask = input_mask
338
+
339
+ return mask
340
+
341
+
342
+ def concat_points(old_point_inputs, new_points, new_labels):
343
+ """Add new points and labels to previous point inputs (add at the end)."""
344
+ if old_point_inputs is None:
345
+ points, labels = new_points, new_labels
346
+ else:
347
+ points = torch.cat([old_point_inputs["point_coords"], new_points], dim=1)
348
+ labels = torch.cat([old_point_inputs["point_labels"], new_labels], dim=1)
349
+
350
+ return {"point_coords": points, "point_labels": labels}
351
+
352
+
353
+ def get_image_size(image: Union[np.ndarray, torch.Tensor]):
354
+ if isinstance(image, np.ndarray):
355
+ return image.shape[:2]
356
+ elif isinstance(image, torch.Tensor):
357
+ _, h, w = image.shape
358
+ return (h, w)
359
+ elif isinstance(image, Image):
360
+ w, h = image.size
361
+ return (h, w)
362
+ else:
363
+ raise NotImplementedError(
364
+ f"Only support np.ndarray, torch.Tensoror PIL Image, but got {type(image)}"
365
+ )
366
+
367
+
368
+ def crop_image(
369
+ image: Union[np.ndarray, torch.Tensor], crop_box: Tuple[int, int, int, int]
370
+ ):
371
+ x0, y0, x1, y1 = crop_box
372
+ if isinstance(image, np.ndarray):
373
+ # HxWxC
374
+ return image[y0:y1, x0:x1, :]
375
+ elif isinstance(image, torch.Tensor):
376
+ # CxHxW
377
+ return image[:, y0:y1, x0:x1]
378
+ else:
379
+ raise ValueError(
380
+ "Expected image to be of type np.ndarray or "
381
+ f"torch.Tensor, but got {type(image)}"
382
+ )