diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/README.md b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/README.md new file mode 100644 index 0000000000000000000000000000000000000000..300f1ed7d3f78c25c1829b5ec7ac03b30faa85a6 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/README.md @@ -0,0 +1,47 @@ +# LLAMA + +## Eval on Llama 3.1 8B and Llama 3.2 3B + +We use lm-eval tasks for evaluating TorchAO Quantization APIs on HuggingFace models. The results are in the table below: + +| Model Name | Quantization Technique | Acc |Acc Norm| Word perplexity| Model Size (GB) | +|------------|---------------------------|-------|--------|----------------|-------------------| +| Llama 3.1 8B | None | 60.01 | 78.84 | 7.33 | 15.01 | +| Llama 3.1 8B | int4wo-128 | 58.10 | 77.06 | 8.25 | 4.76 | +| Llama 3.1 8B | int8wo | 59.92 | 78.95 | 7.34 | 8.04 | +| Llama 3.1 8B | int8dq | 60.01 | 78.82 | 7.45 | 8.03 | +| Llama 3.1 8B | float8wo | 59.83 | 78.61 | 7.37 | 8.03 | +| Llama 3.1 8B | float8dq (PerRow) | 59.86 | 78.57 | 7.41 | 8.04 | +| Llama 3.1 8B | float8dq (PerTensor) | 59.95 | 78.66 | 7.42 | 8.03 | +| Llama 3.1 8B | gemlite (gp=128) | 58.48 | 77.34 | 8.07 | 4.76 | + +| Model Name | Quantization Technique | Acc |Acc Norm| Word perplexity| Model Size (GB) | +|------------|---------------------------|-------|--------|----------------|-------------------| +| Llama 3.2 3B | None | 55.27 | 73.70 | 9.26 | 6.43 | +| Llama 3.2 3B | int4wo-128 | 53.13 | 71.31 | 10.36 | 2.29 | +| Llama 3.2 3B | int8wo | 55.15 | 73.44 | 9.28 | 3.61 | +| Llama 3.2 3B | int8dq | 55.00 | 73.29 | 9.43 | 3.61 | +| Llama 3.2 3B | float8wo | 55.18 | 73.58 | 9.31 | 3.61 | +| Llama 3.2 3B | float8dq (PerRow) | 55.18 | 73.37 | 9.33 | 3.61 | +| Llama 3.2 3B | float8dq (PerTensor) | 55.16 | 73.53 | 9.35 | 3.61 | +| Llama 3.2 3B | gemlite (gp=128) | 53.71 | 71.99 | 10.05 | 2.29 | + +To generate the above results run: +``` +sh benchmarks/_models/eval_hf_models.sh +``` + +To run lm-eval for a different hf-model with AO quantization technique, run: +``` +python benchmarks/_models/eval_hf_models.py --model_id meta-llama/Llama-3.1-8B --quantization float8dq-row --tasks wikitext hellaswag +``` +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. + +# SAM2 +sam2 is a fork of https://github.com/facebookresearch/sam2 at commit c2ec8e14a185632b0a5d8b161928ceb50197eddc + +It includes +- modifications to enable fullgraph=True compile +- `mask_to_rle_pytorch_2` +- small performance changes and fixes +- integration into torchao's packaging diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/_eval.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/_eval.py new file mode 100644 index 0000000000000000000000000000000000000000..faf059c4008de8267161f05f0468a6690a4c5ab6 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/_eval.py @@ -0,0 +1,209 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD-style license found in the +# LICENSE file in the root directory of this source tree. + + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import lm_eval +import torch +import torch.nn.functional as F + +from torchao.quantization.GPTQ import MultiTensorInputRecorder + +try: # lm_eval version 0.4 + from lm_eval.evaluator import evaluate # pyre-ignore[21] + from lm_eval.models.huggingface import HFLM as eval_wrapper # pyre-ignore[21] + from lm_eval.tasks import get_task_dict # pyre-ignore[21] +except: # lm_eval version 0.3 + from lm_eval import base, evaluator, tasks + + eval_wrapper = base.BaseLM + get_task_dict = tasks.get_task_dict + evaluate = evaluator.evaluate + + +class TransformerEvalWrapper(eval_wrapper): + """ + A wrapper class for GPTFast, providing integration with the lm-evaluation-harness library. + """ + + def __init__( + self, model, tokenizer, max_seq_length, input_prep_func=None, device="cuda" + ): + try: + super().__init__(device=device) + except TypeError: + # lm_eval 0.4.2 removed the default init + super().__init__("gpt2", device="cpu") + + self._model = model + self.tokenizer = tokenizer + self._device = torch.device(device) + self._max_seq_length = max_seq_length + + # need to take inps and convert to corrent input + # for model + self.input_prep_func = ( + input_prep_func if input_prep_func is not None else lambda x: (x,) + ) + + def _model_call(self, inps): + # TODO: make batches work + input = self.input_prep_func(inps) + + max_seq_length = min(max(inps.size()), self.max_length) + with torch.device(self._device): + self._model.setup_caches(self.batch_size, max_seq_length) + logits = self._model(*input) + return logits + + def run_eval(self, tasks, limit): + try: + lm_eval.tasks.initialize_tasks() + except: + pass + + task_dict = get_task_dict(tasks) + print("Evaluating Model On: ", task_dict) + with torch.no_grad(): + result = evaluate( + self, + task_dict, + limit=limit, + ) + for task, res in result["results"].items(): + print(f"{task}: {res}") + return result + + @property + def eot_token_id(self): + try: + return self.tokenizer.eos_id() + except: + return self.tokenizer.eos_id + + @property + def max_length(self): + return self._max_seq_length + + @property + def max_gen_toks(self): + return 50 + + @property + def batch_size(self): + return 1 + + @property + def device(self): + return self._device + + def tok_decode(self, tokens): + decoded = self.tokenizer.decode(tokens) + return decoded + + def tok_encode(self, string: str, **kwargs): + tokens = self.tokenizer.encode(string) + if hasattr(self.tokenizer, "bos_id"): + try: + tokens = [self.tokenizer.bos_id()] + tokens + except: + tokens = [self.tokenizer.bos_id] + tokens + return tokens + + def _model_generate(self, context, max_length, eos_token_id): + raise Exception("unimplemented") + + +class LMEvalInputRecorder(TransformerEvalWrapper): + def __init__( + self, + tokenizer, + calibration_seq_length, + input_prep_func=None, + vocab_size=32000, + pad_calibration_inputs=False, + pad_token=0, + device="cpu", + base_input_recorder_class=MultiTensorInputRecorder, + ): + super().__init__( + model=None, + tokenizer=tokenizer, + max_seq_length=calibration_seq_length, + input_prep_func=input_prep_func, + device=device, + ) + self.vocab_size = vocab_size + self.calibration_seq_length = calibration_seq_length + + self.pad_calibration_inputs = pad_calibration_inputs + self.pad_token = pad_token + + # Initialize inputs as a list of two empty lists for input tensors and indices + self.base_input_recorder = base_input_recorder_class() + + def record_inputs(self, calibration_tasks, calibration_limit): + try: + lm_eval.tasks.initialize_tasks() + except: + pass + + task_dict = get_task_dict(calibration_tasks) + print("Obtaining GPTQ calibration inputs on: ", calibration_tasks) + + evaluate( + self, + task_dict, + limit=calibration_limit, + ) + return self + + def get_inputs(self): # for BC + return self.get_recorded_inputs() + + def get_recorded_inputs(self): + return self.base_input_recorder.get_recorded_inputs() + + def get_recorded_args_and_kwargs(self): + return self.base_input_recorder.get_recorded_args_and_kwargs() + + def _model_call(self, inps): + inps = inps.squeeze(0) + T = len(inps) + if ( + # Can't use inputs that are too short when padding is disabled + (T < self.calibration_seq_length and not self.pad_calibration_inputs) + or + # Can't use inputs that actually use the token we use for padding + (self.pad_calibration_inputs and self.pad_token in inps) + ): + # Give random output + return torch.randn( + (1, T, self.vocab_size), dtype=torch.bfloat16, device=self._device + ) + + # Pad or truncate to the correct size + if T >= self.calibration_seq_length: + inps = inps[: self.calibration_seq_length] + else: + inps = F.pad( + inps, (0, self.calibration_seq_length - T), value=self.pad_token + ) + + inps = inps.unsqueeze(0) + model_in = self.input_prep_func(inps) + + self.base_input_recorder(*model_in) + + # Output `something` with the correct shape to keep eval going + return torch.randn( + (1, T, self.vocab_size), dtype=torch.bfloat16, device=self._device + ) + + +InputRecorder = LMEvalInputRecorder # for BC diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/README.md b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/README.md new file mode 100644 index 0000000000000000000000000000000000000000..22c318aab9c2301eae24dee3dc156456f8ad0e4a --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/README.md @@ -0,0 +1,8 @@ +## Mixtral-MoE + +This folder contains code and scripts for benchmarking the Mixtral-MoE model. +Running + +`sh scripts/prepare.sh` + +should download the model and `sh run.sh` will run teh benchmarks. diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/generate.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/generate.py new file mode 100644 index 0000000000000000000000000000000000000000..11a53043ade46c318fbd169a3efde97209faa4c2 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/generate.py @@ -0,0 +1,506 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +import itertools +import sys +import time +from pathlib import Path +from typing import Optional, Tuple + +import torch +import torch._dynamo.config +import torch._inductor.config + +from torchao.utils import get_model_size_in_bytes + +torch.manual_seed(0) + + +def device_sync(device): + if "cuda" in device: + torch.cuda.synchronize(device) + elif "cpu" in device: + pass + else: + print(f"device={device} is not yet suppported") + + +torch._inductor.config.coordinate_descent_tuning = True +torch._inductor.config.triton.unique_kernel_names = True +torch._inductor.config.fx_graph_cache = True # Experimental feature to reduce compilation times, will be on by default in future +torch._dynamo.config.capture_scalar_outputs = True + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +from model import Transformer +from sentencepiece import SentencePieceProcessor + + +def multinomial_sample_one_no_sync( + probs_sort, +): # Does multinomial sampling without a cuda synchronization + q = torch.empty_like(probs_sort).exponential_(1) + return torch.argmax(probs_sort / q, dim=-1, keepdim=True).to(dtype=torch.int) + + +def logits_to_probs(logits, temperature: float = 1.0, top_k: Optional[int] = None): + logits = logits / max(temperature, 1e-5) + + if top_k is not None: + v, _ = torch.topk(logits, min(top_k, logits.size(-1))) + pivot = v.select(-1, -1).unsqueeze(-1) + logits = torch.where(logits < pivot, -float("Inf"), logits) + probs = torch.nn.functional.softmax(logits, dim=-1) + return probs + + +def sample(logits, temperature: float = 1.0, top_k: Optional[int] = None): + probs = logits_to_probs(logits[:, -1], temperature, top_k) + idx_next = multinomial_sample_one_no_sync(probs) + return idx_next, probs + + +def prefill( + model: Transformer, x: torch.Tensor, input_pos: torch.Tensor, **sampling_kwargs +) -> torch.Tensor: + # input_pos: [B, S] + logits = model(x, input_pos) + return sample(logits, **sampling_kwargs)[0] + + +def decode_one_token( + model: Transformer, x: torch.Tensor, input_pos: torch.Tensor, **sampling_kwargs +) -> Tuple[torch.Tensor, torch.Tensor]: + # input_pos: [B, 1] + assert input_pos.shape[-1] == 1 + logits = model(x, input_pos) + return sample(logits, **sampling_kwargs) + + +def decode_n_tokens( + model: Transformer, + cur_token: torch.Tensor, + input_pos: torch.Tensor, + num_new_tokens: int, + callback=lambda _: _, + **sampling_kwargs, +): + new_tokens, new_probs = [], [] + for i in range(num_new_tokens): + with torch.backends.cuda.sdp_kernel( + enable_flash=False, enable_mem_efficient=False, enable_math=True + ): # Actually better for Inductor to codegen attention here + next_token, next_prob = decode_one_token( + model, cur_token, input_pos, **sampling_kwargs + ) + next_token, next_prob = next_token.clone(), next_prob.clone() + + input_pos += 1 + new_tokens.append(next_token.clone()) + callback(new_tokens[-1]) + new_probs.append(next_prob.clone()) + cur_token = next_token + + return new_tokens, new_probs + + +def model_forward(model, x, input_pos): + return model(x, input_pos) + + +@torch.no_grad() +def generate( + model: Transformer, + prompt: torch.Tensor, + max_new_tokens: int, + batch_size: int, + *, + interactive: bool, + callback=lambda x: x, + **sampling_kwargs, +) -> torch.Tensor: + """ + Takes a conditioning sequence (prompt) as input and continues to generate as many tokens as requested. + """ + device, _ = prompt.device, prompt.dtype + + T = prompt.size(-1) + max_seq_length = ( + min(T + max_new_tokens, model.config.block_size) if not interactive else 350 + ) + new_tokens = max_seq_length - T + + # duplicate prompt for batch_size + prompt = prompt.repeat(batch_size, 1) + + # create an empty tensor of the expected final shape and fill in the current tokens + seq = torch.empty(batch_size, max_seq_length, dtype=prompt.dtype, device=device) + seq[:, :T] = prompt + + with torch.device(device): + model.setup_caches(max_batch_size=batch_size, max_seq_length=max_seq_length) + + input_pos = torch.arange(0, T, device=device) + next_token = prefill( + model, prompt.view(batch_size, -1), input_pos, **sampling_kwargs + ) + seq[:, T] = next_token.squeeze() + + input_pos = torch.tensor([T], device=device, dtype=torch.int) + generated_tokens, _ = decode_n_tokens( + model, + next_token.view(batch_size, -1), + input_pos, + new_tokens - 1, + callback=callback, + **sampling_kwargs, + ) + seq = torch.cat((seq[:, : T + 1], *generated_tokens), dim=-1) + + return seq + + +def encode_tokens(tokenizer, string, bos=True, device="cuda"): + tokens = tokenizer.encode(string) + if bos: + tokens = [tokenizer.bos_id()] + tokens + return torch.tensor(tokens, dtype=torch.int, device=device) + + +def _load_model(checkpoint_path, device, precision): + with torch.device("meta"): + model = Transformer.from_name(checkpoint_path.parent.name) + + try: + checkpoint = torch.load(str(checkpoint_path), mmap=True, weights_only=True) + model.load_state_dict(checkpoint, assign=True) + except: + model = Transformer.from_name(checkpoint_path.parent.name) + + model = model.to(device=device, dtype=precision) + return model.eval() + + +B_INST, E_INST = "[INST]", "[/INST]" + + +def main( + prompt: str = "Hello, my name is", + interactive: bool = False, + num_samples: int = 5, + max_new_tokens: int = 100, + batch_size: int = 1, + top_k: int = 200, + temperature: float = 0.8, + checkpoint_path: Path = Path("checkpoints/mistralai/Mixtral-8x7B-v0.1/model.pth"), + compile: bool = True, + compile_prefill: bool = False, + moe_quant: Optional[str] = None, + profile: Optional[Path] = None, + memory_profile: Optional[Path] = None, + device="cuda", +) -> None: + """Generates text samples based on a pre-trained Transformer model and tokenizer.""" + assert checkpoint_path.is_file(), checkpoint_path + tokenizer_path = checkpoint_path.parent / "tokenizer.model" + assert tokenizer_path.is_file(), str(tokenizer_path) + print(f"Using device={device}") + precision = torch.bfloat16 + is_chat = "chat" in str(checkpoint_path) + + if device == "cuda" and memory_profile is not None: + torch.cuda.memory._record_memory_history( + True, trace_alloc_max_entries=500000, trace_alloc_record_context=True + ) + + print("Loading model ...") + t0 = time.time() + model = _load_model(checkpoint_path, "cpu", precision) + + print(f"Time to load model: {time.time() - t0:.02f} seconds") + t0 = time.time() + + tokenizer = SentencePieceProcessor(model_file=str(tokenizer_path)) + encoded = encode_tokens(tokenizer, prompt, bos=True, device=device) + prompt_length = encoded.size(0) + + torch.manual_seed(1234) + model_size = sum( + [ + p.numel() * p.dtype.itemsize + for p in itertools.chain(model.parameters(), model.buffers()) + ] + ) + + from torchao.prototype.moe_quant.utils import ( + MoEQuantConfig, + UseFakeExtraDimTensor, + cond_ffn_filter, + ) + from torchao.quantization.quant_api import ( + Float8DynamicActivationFloat8WeightConfig, + Float8WeightOnlyConfig, + Int4WeightOnlyConfig, + Int8DynamicActivationInt8WeightConfig, + Int8DynamicActivationIntxWeightConfig, + Int8WeightOnlyConfig, + PackedLinearInt8DynamicActivationIntxWeightLayout, + PerRow, + quantize_, + ) + + if moe_quant: + torch._dynamo.config.capture_dynamic_output_shape_ops = True + config = None + if "int8wo-base" in moe_quant: + config = MoEQuantConfig(Int8WeightOnlyConfig()) + + elif "int8wo" in moe_quant: + config = MoEQuantConfig( + Int8WeightOnlyConfig(), + use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE, + ) + + elif "int8dq-base" in moe_quant: + config = MoEQuantConfig(Int8DynamicActivationInt8WeightConfig()) + + elif "int8dq" in moe_quant: + config = MoEQuantConfig( + Int8DynamicActivationInt8WeightConfig(), + use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE, + ) + + elif "int4wo-base" in moe_quant: + config = MoEQuantConfig(Int4WeightOnlyConfig()) + + elif "int4wo" in moe_quant: + config = MoEQuantConfig( + Int4WeightOnlyConfig(), + use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE, + ) + + elif "fp8wo-base" in moe_quant: + config = MoEQuantConfig(Float8WeightOnlyConfig()) + + elif "fp8wo" in moe_quant: + config = MoEQuantConfig( + Float8WeightOnlyConfig(), + use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE, + ) + + elif "fp8dq-base" in moe_quant: + config = MoEQuantConfig( + Float8DynamicActivationFloat8WeightConfig(granularity=PerRow()) + ) + + elif "fp8dq" in moe_quant: + config = MoEQuantConfig( + Float8DynamicActivationFloat8WeightConfig(granularity=PerRow()), + use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE, + ) + + elif "intxdq" in moe_quant: + config = MoEQuantConfig( + Int8DynamicActivationIntxWeightConfig( + layout=PackedLinearInt8DynamicActivationIntxWeightLayout(), + ), + use_fake_extra_dim_tensor=UseFakeExtraDimTensor.TRUE, + ) + else: + assert config is not None, ( + f"expected moe_quant to match one of the options but got {moe_quant}" + ) + + if config is not None: + quantize_(model, config, filter_fn=cond_ffn_filter, device=device) + print( + f"Time to apply quantization with config {config} to model: {time.time() - t0:.02f} seconds" + ) + + model.to(device=device) + device_sync(device=device) + + if compile: + # moe quant + compile causes repeated warnings + import warnings + + warnings.simplefilter("ignore", lineno=84) + warnings.simplefilter("ignore", lineno=105) + + torch._inductor.config.assert_indirect_indexing = False + + global decode_one_token, prefill + + if batch_size == 1 and (isinstance(moe_quant, str) and "base" in moe_quant): + decode_one_token = torch.compile( + decode_one_token, mode="reduce-overhead", fullgraph=True + ) + else: + decode_one_token = torch.compile(decode_one_token, mode="reduce-overhead") + + if args.compile_prefill: + prefill = torch.compile(prefill, fullgraph=True, dynamic=True) + + aggregate_metrics = { + "tokens_per_sec": [], + } + start = -1 if compile else 0 + + for i in range(start, num_samples): + device_sync(device=device) # MKG + if i >= 0 and interactive: + prompt = input("What is your prompt? ") + if is_chat: + prompt = f"{B_INST} {prompt.strip()} {E_INST}" + encoded = encode_tokens(tokenizer, prompt, bos=True, device=device) + + if interactive and i >= 0: + buffer = [] + period_id = tokenizer.encode(".")[0] + done_generating = False + + def callback(x): + nonlocal done_generating + if done_generating: + return + buffer.append(tokenizer.decode([period_id] + x.tolist())[1:]) + if x.item() == tokenizer.eos_id(): + done_generating = True + if len(buffer) == 4 or done_generating: + print("".join(buffer), end="", flush=True) + buffer.clear() + # print(, end='', flush=True) + else: + callback = lambda x: x + t0 = time.perf_counter() + import contextlib + + if i != num_samples - 1 or not profile: + prof = contextlib.nullcontext() + else: + torch.profiler._utils._init_for_cuda_graphs() + prof = torch.profiler.profile() + with prof: + y = generate( + model, + encoded, + max_new_tokens, + batch_size, + interactive=interactive, + callback=callback, + temperature=temperature, + top_k=top_k, + ) + if i == -1: + print(f"Compilation time: {time.perf_counter() - t0:.2f} seconds") + continue + if hasattr(prof, "export_chrome_trace"): + prof.export_chrome_trace(f"{profile}.json") + device_sync(device=device) # MKG + t = time.perf_counter() - t0 + + if not interactive: + pass + print(tokenizer.decode(y[0].tolist())) + else: + print() + tokens_generated = y.size(-1) - prompt_length + tokens_sec = tokens_generated / t + aggregate_metrics["tokens_per_sec"].append(tokens_sec) + print( + f"Time for inference {i + 1}: {t:.02f} sec total, {tokens_sec:.02f} tokens/sec" + ) + print(f"Bandwidth achieved: {model_size * tokens_sec / 1e9:.02f} GB/s") + + if i == 0 and device == "cuda" and memory_profile is not None: + snapshot = torch.cuda.memory._snapshot() + with open(f"{memory_profile}.pickle", "wb") as f: + from pickle import dump + + dump(snapshot, f) + print( + f"\nmemory profile {memory_profile}.pickle saved, to convert that to a usable file, use", + "python pytorch/torch/cuda/_memory_viz.py trace_plot -o .html", + ) + break + + tokpersec = torch.mean(torch.tensor(aggregate_metrics["tokens_per_sec"])).item() + print(f"Average tokens/sec: {tokpersec:.2f}") + if batch_size > 1: + print(f"Average tokens/sec including batches {batch_size * tokpersec:.2f}") + print(f"Memory used: {torch.cuda.max_memory_reserved() / 1e9:.02f} GB") + print(f"model size: {get_model_size_in_bytes(model) / 1e9:.02f}") + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Your CLI description.") + + parser.add_argument( + "--prompt", type=str, default="Hello, my name is", help="Input prompt." + ) + parser.add_argument( + "--interactive", + action="store_true", + help="Whether to launch in interactive mode", + ) + parser.add_argument("--num_samples", type=int, default=5, help="Number of samples.") + parser.add_argument( + "--max_new_tokens", type=int, default=200, help="Maximum number of new tokens." + ) + parser.add_argument( + "--batch_size", type=int, default=1, help="Batch size to benchmark with" + ) + parser.add_argument("--top_k", type=int, default=200, help="Top-k for sampling.") + parser.add_argument( + "--temperature", type=float, default=0.8, help="Temperature for sampling." + ) + parser.add_argument( + "--checkpoint_path", + type=Path, + default=Path("checkpoints/meta-Transformer/Transformer-2-7b-chat-hf/model.pth"), + help="Model checkpoint path.", + ) + parser.add_argument( + "--compile", action="store_true", help="Whether to compile the model." + ) + parser.add_argument( + "--compile_prefill", + action="store_true", + help="Whether to compile the prefill (improves prefill perf, but higher compile times)", + ) + # parser.add_argument('-q', '--quantization', type=str, help='Which quantization techniques to apply: int8dq, int8wo, int4wo, fp8') + parser.add_argument( + "--moe_quant", + type=str, + help="Which quantization techniques to apply: int8dq, int8wo, int4wo, fp8wo, fp8dq", + ) + parser.add_argument("--profile", type=Path, default=None, help="Profile path.") + parser.add_argument( + "--memory_profile", type=Path, default=None, help="filename for memory profile." + ) + parser.add_argument("--device", type=str, default="cuda", help="device to use") + + args = parser.parse_args() + print(args) + main( + args.prompt, + args.interactive, + args.num_samples, + args.max_new_tokens, + args.batch_size, + args.top_k, + args.temperature, + args.checkpoint_path, + args.compile, + args.compile_prefill, + args.moe_quant, + args.profile, + args.memory_profile, + args.device, + ) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/model.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/model.py new file mode 100644 index 0000000000000000000000000000000000000000..685323843dd5f8fe6b9ce67f0944628179ec322b --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/model.py @@ -0,0 +1,464 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +from dataclasses import dataclass +from typing import Optional + +import torch +import torch.nn as nn +from torch import Tensor +from torch.nn import functional as F + +from torchao.prototype.moe_quant.utils import FakeExtraDimTensor + + +def find_multiple(n: int, k: int) -> int: + if n % k == 0: + return n + return n + k - (n % k) + + +@dataclass +class ModelArgs: + block_size: int = 2048 + vocab_size: int = 32000 + n_layer: int = 32 + n_head: int = 32 + dim: int = 4096 + intermediate_size: int = None + n_local_heads: int = -1 + head_dim: int = 64 + rope_base: float = 10000 + norm_eps: float = 1e-5 + num_experts: int = 8 + num_activated_experts: int = 2 + + def __post_init__(self): + if self.n_local_heads == -1: + self.n_local_heads = self.n_head + if self.intermediate_size is None: + hidden_dim = 4 * self.dim + n_hidden = int(2 * hidden_dim / 3) + self.intermediate_size = find_multiple(n_hidden, 256) + self.head_dim = self.dim // self.n_head + + @classmethod + def from_name(cls, name: str): + if name in transformer_configs: + return cls(**transformer_configs[name]) + # fuzzy search + config = [ + config + for config in transformer_configs + if config in str(name).upper() or config in str(name) + ] + assert len(config) == 1, name + return cls(**transformer_configs[config[0]]) + + +transformer_configs = { + "Mixtral-8x7B-Instruct-v0.1": dict( + block_size=32768, + n_layer=32, + n_head=32, + n_local_heads=8, + dim=4096, + intermediate_size=14336, + rope_base=1000000.0, + num_experts=8, + num_activated_experts=2, + ), +} + + +class KVCache(nn.Module): + def __init__( + self, max_batch_size, max_seq_length, n_heads, head_dim, dtype=torch.bfloat16 + ): + super().__init__() + cache_shape = (max_batch_size, n_heads, max_seq_length, head_dim) + self.register_buffer("k_cache", torch.zeros(cache_shape, dtype=dtype)) + self.register_buffer("v_cache", torch.zeros(cache_shape, dtype=dtype)) + + def update(self, input_pos, k_val, v_val): + # input_pos: [S], k_val: [B, H, S, D] + assert input_pos.shape[0] == k_val.shape[2] + + k_out = self.k_cache + v_out = self.v_cache + k_out[:, :, input_pos] = k_val + v_out[:, :, input_pos] = v_val + + return k_out, v_out + + +class Transformer(nn.Module): + def __init__(self, config: ModelArgs) -> None: + super().__init__() + self.config = config + + self.tok_embeddings = nn.Embedding(config.vocab_size, config.dim) + self.layers = nn.ModuleList( + TransformerBlock(config) for _ in range(config.n_layer) + ) + self.norm = RMSNorm(config.dim, eps=config.norm_eps) + self.output = nn.Linear(config.dim, config.vocab_size, bias=False) + + self.freqs_cis: Optional[Tensor] = None + self.mask_cache: Optional[Tensor] = None + self.max_batch_size = -1 + self.max_seq_length = -1 + + def setup_caches(self, max_batch_size, max_seq_length): + if ( + self.max_seq_length >= max_seq_length + and self.max_batch_size >= max_batch_size + ): + return + head_dim = self.config.dim // self.config.n_head + max_seq_length = find_multiple(max_seq_length, 8) + self.max_seq_length = max_seq_length + self.max_batch_size = max_batch_size + for b in self.layers: + b.attention.kv_cache = KVCache( + max_batch_size, max_seq_length, self.config.n_local_heads, head_dim + ) + + self.freqs_cis = precompute_freqs_cis( + self.config.block_size, + self.config.dim // self.config.n_head, + self.config.rope_base, + ) + self.causal_mask = torch.tril( + torch.ones(self.max_seq_length, self.max_seq_length, dtype=torch.bool) + ) + + def forward(self, idx: Tensor, input_pos: Optional[Tensor] = None) -> Tensor: + assert self.freqs_cis is not None, "Caches must be initialized first" + mask = self.causal_mask[None, None, input_pos] + freqs_cis = self.freqs_cis[input_pos] + x = self.tok_embeddings(idx) + + for i, layer in enumerate(self.layers): + x = layer(x, input_pos, freqs_cis, mask) + x = self.norm(x) + logits = self.output(x) + return logits + + @classmethod + def from_name(cls, name: str): + return cls(ModelArgs.from_name(name)) + + +class TransformerBlock(nn.Module): + def __init__(self, config: ModelArgs) -> None: + super().__init__() + self.attention = Attention(config) + self.block_sparse_moe = MOEFeedForwardAOQuantizable(config) + self.ffn_norm = RMSNorm(config.dim, config.norm_eps) + self.attention_norm = RMSNorm(config.dim, config.norm_eps) + + def forward( + self, x: Tensor, input_pos: Tensor, freqs_cis: Tensor, mask: Tensor + ) -> Tensor: + h = x + self.attention(self.attention_norm(x), freqs_cis, mask, input_pos) + out = h + self.block_sparse_moe(self.ffn_norm(h)) + return out + + +class Attention(nn.Module): + def __init__(self, config: ModelArgs): + super().__init__() + assert config.dim % config.n_head == 0 + + total_head_dim = (config.n_head + 2 * config.n_local_heads) * config.head_dim + # key, query, value projections for all heads, but in a batch + self.wqkv = nn.Linear(config.dim, total_head_dim, bias=False) + self.wo = nn.Linear(config.dim, config.dim, bias=False) + self.kv_cache = None + + self.n_head = config.n_head + self.head_dim = config.head_dim + self.n_local_heads = config.n_local_heads + self.dim = config.dim + self._register_load_state_dict_pre_hook(self.load_hook) + + def load_hook(self, state_dict, prefix, *args): + if prefix + "wq.weight" in state_dict: + wq = state_dict.pop(prefix + "wq.weight") + wk = state_dict.pop(prefix + "wk.weight") + wv = state_dict.pop(prefix + "wv.weight") + state_dict[prefix + "wqkv.weight"] = torch.cat([wq, wk, wv]) + + def forward( + self, + x: Tensor, + freqs_cis: Tensor, + mask: Tensor, + input_pos: Optional[Tensor] = None, + ) -> Tensor: + bsz, seqlen, _ = x.shape + + kv_size = self.n_local_heads * self.head_dim + q, k, v = self.wqkv(x).split([self.dim, kv_size, kv_size], dim=-1) + + q = q.view(bsz, seqlen, self.n_head, self.head_dim) + k = k.view(bsz, seqlen, self.n_local_heads, self.head_dim) + v = v.view(bsz, seqlen, self.n_local_heads, self.head_dim) + + q = apply_rotary_emb(q, freqs_cis) + k = apply_rotary_emb(k, freqs_cis) + + q, k, v = map(lambda x: x.transpose(1, 2), (q, k, v)) + + if self.kv_cache is not None: + k, v = self.kv_cache.update(input_pos, k, v) + + k = k.repeat_interleave(self.n_head // self.n_local_heads, dim=1) + v = v.repeat_interleave(self.n_head // self.n_local_heads, dim=1) + y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0) + + y = y.transpose(1, 2).contiguous().view(bsz, seqlen, self.dim) + + y = self.wo(y) + return y + + +# class ConditionalFeedForward(nn.Module): +# def __init__(self, config): +# super().__init__() +# self.w1 = nn.Parameter(torch.empty(config.num_experts, config.intermediate_size, config.dim)) +# self.w2 = nn.Parameter(torch.empty(config.num_experts, config.dim, config.intermediate_size)) +# self.w3 = nn.Parameter(torch.empty(config.num_experts, config.intermediate_size, config.dim)) + +# def forward(self, x: Tensor, expert_indices: Tensor) -> Tensor: +# w1_weights = self.w1[expert_indices] # [T, A, D, D] +# w3_weights = self.w3[expert_indices] # [T, A, D, D] +# w2_weights = self.w2[expert_indices] # [T, A, D, D] +# x1 = F.silu(torch.einsum('ti,taoi -> tao', x, w1_weights)) +# x3 = torch.einsum('ti, taoi -> tao', x, w3_weights) +# expert_outs = torch.einsum('tao, taio -> tai', (x1 * x3), w2_weights) +# return expert_outs + + +# class MOEFeedForward(nn.Module): +# def __init__(self, config) -> None: +# super().__init__() +# self.gate = nn.Linear(config.dim, config.num_experts, bias=False) +# self.cond_ffn = ConditionalFeedForward(config) +# self.dim = config.dim +# self.num_activated_experts = config.num_activated_experts +# def forward(self, x: Tensor) -> Tensor: +# x = x.view(-1, self.dim) +# # T = num_tokens, E = num_experts, D = hidden dim, A = activated experts +# # x: [T, D] +# scores = self.gate(x) # [T, E] +# expert_weights = F.softmax(scores, dim=-1) +# expert_weights, expert_indices = torch.topk(expert_weights, self.num_activated_experts, dim=-1) # [T, A], [T, A] +# expert_weights /= expert_weights.sum(dim=-1, keepdim=True) # [T, A] +# expert_outs = self.cond_ffn(x, expert_indices) +# return torch.einsum('tai,ta -> ti', expert_outs, expert_weights) + + +class RMSNorm(nn.Module): + def __init__(self, dim: int, eps: float = 1e-5): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def _norm(self, x): + return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps) + + def forward(self, x: Tensor) -> Tensor: + output = self._norm(x.float()).type_as(x) + return output * self.weight + + +def precompute_freqs_cis(seq_len: int, n_elem: int, base: int = 10000) -> Tensor: + freqs = 1.0 / ( + base ** (torch.arange(0, n_elem, 2)[: (n_elem // 2)].float() / n_elem) + ) + t = torch.arange(seq_len, device=freqs.device) + freqs = torch.outer(t, freqs) + freqs_cis = torch.polar(torch.ones_like(freqs), freqs) + cache = torch.stack([freqs_cis.real, freqs_cis.imag], dim=-1) + return cache.to(dtype=torch.bfloat16) + + +def apply_rotary_emb(x: Tensor, freqs_cis: Tensor) -> Tensor: + xshaped = x.float().reshape(*x.shape[:-1], -1, 2) + freqs_cis = freqs_cis.view(1, xshaped.size(1), 1, xshaped.size(3), 2) + x_out2 = torch.stack( + [ + xshaped[..., 0] * freqs_cis[..., 0] - xshaped[..., 1] * freqs_cis[..., 1], + xshaped[..., 1] * freqs_cis[..., 0] + xshaped[..., 0] * freqs_cis[..., 1], + ], + -1, + ) + + x_out2 = x_out2.flatten(3) + return x_out2.type_as(x) + + +# T tokens +# E experts +# D dim +# I intermediate dim +# A activated experts +# T'(e) tokens for expert e + + +class MOEFeedForwardAOQuantizable(nn.Module): + def __init__(self, config) -> None: + super().__init__() + self.gate = nn.Linear(config.dim, config.num_experts, bias=False) + self.cond_ffn = ConditionalFeedForwardAOQuantizable(config) + self.dim = config.dim + self.num_activated_experts = config.num_activated_experts + + def forward(self, x: Tensor) -> Tensor: + batch_size = x.shape[0] + x = x.view(-1, self.dim) # x: [T, D] + scores = self.gate(x) # [T, E] + expert_weights = F.softmax(scores, dim=-1) + expert_weights, expert_indices = torch.topk( + expert_weights, self.num_activated_experts, dim=-1 + ) # [T, A], [T, A] + expert_weights /= expert_weights.sum(dim=-1, keepdim=True).to(x.dtype) # [T, A] + out = self.cond_ffn( + x, expert_indices, expert_weights, self.num_activated_experts + ) + return out.reshape(batch_size, -1, self.dim) + + +class ConditionalFeedForwardAOQuantizable(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.w1 = nn.Parameter( + torch.empty(config.num_experts, config.intermediate_size, config.dim) + ) # E, I, D + self.w2 = nn.Parameter( + torch.empty(config.num_experts, config.dim, config.intermediate_size) + ) # E, D, I + self.w3 = nn.Parameter( + torch.empty(config.num_experts, config.intermediate_size, config.dim) + ) # E, I, D + self.num_experts = config.num_experts + + def forward( + self, + x: Tensor, # T, D + expert_indices: Tensor, # T, A + expert_weights: Tensor, # T, A + num_activated_experts: int, + ) -> Tensor: + num_tokens, dim = x.shape + num_token_activations = num_tokens * num_activated_experts + if x.shape[0] == 1 and not isinstance( + self.w1, FakeExtraDimTensor + ): # only 1 token (can be done without graph breaks when compiled) + outs = [] + expert_indices = expert_indices.view(num_activated_experts) + # collect used experts + w1 = self.w1[expert_indices] + w2 = self.w2[expert_indices] + w3 = self.w3[expert_indices] + + # run token through each expert + for index in range(num_activated_experts): + y1 = F.silu(F.linear(x, w1[index])) + y3 = F.linear(x, w3[index]) + y2 = w2[index] + cur_out = F.linear(y1 * y3, y2) + outs.append(cur_out) + + # combine outputs + final_out = ( + (torch.cat(outs, dim=0) * expert_weights.view(-1, 1)) + .sum(dim=0) + .unsqueeze(-1) + ) + return final_out + else: + expert_list = [x for x in range(self.num_experts)] + + # shuffle tokens into groups for each expert + ordered_token_activations = expert_indices.view(-1).argsort( + stable=True + ) # [A] + ordered_token_indices = ( + ordered_token_activations.div(num_activated_experts) + .floor() + .to(torch.int64) + ) # [T] + + if not expert_indices.is_cuda: # histc doesn't work on cpu for integers + num_tokens_per_expert = torch.bincount( + expert_indices.view(-1) + 1, minlength=self.num_experts + 1 + ) + else: + num_tokens_per_expert = torch.histc( + expert_indices, + bins=self.num_experts + 1, + min=-1, + max=self.num_experts, + ) # [E+1] (added leading 0 so can be used for indexing) + cum_tokens_per_expert = num_tokens_per_expert.cumsum(0).to( + torch.int64 + ) # [E+1] + + @torch._dynamo.disable() + def group_tokens_by_expert( + ordered_token_indices, cum_tokens_per_expert, expert_list + ): + token_indices_per_expert = [ + ordered_token_indices[ + cum_tokens_per_expert[expert] : cum_tokens_per_expert[ + expert + 1 + ] + ] + for expert in expert_list + ] # [T'(e1)], [T'(e2)] ... + return token_indices_per_expert + + token_indices_per_expert = group_tokens_by_expert( + ordered_token_indices, cum_tokens_per_expert, expert_list + ) + tokens_grouped_by_expert = [ + x[indices] for indices in token_indices_per_expert + ] + + # calculate outputs for each expert + outs = [] + for cur_x, expert in zip(tokens_grouped_by_expert, expert_list): + w1 = self.w1[expert] # I, D + w2 = self.w2[expert] # D, I + w3 = self.w3[expert] # I, D + + cur_out = F.linear( + F.silu(F.linear(cur_x, w1)) * F.linear(cur_x, w3), w2 + ) # [T'(e), D] + outs.append(cur_out) + + # weigh outputs + ordered_outs = torch.cat(outs, dim=0) # [T*A, D] + ordered_token_activation_weights = expert_weights.view(-1, 1)[ + ordered_token_activations + ].view(-1, 1) # [T*A, 1] + weighted_ordered_outs = ( + ordered_outs * ordered_token_activation_weights + ) # [T*A, D] + + # sum weighted token-activation outputs together for each token + final_out = torch.zeros_like(x) # [T, D] + final_out = final_out.scatter_add( + dim=0, + index=ordered_token_indices.unsqueeze(-1) + .expand(num_token_activations, dim) + .to(torch.int64), + src=weighted_ordered_outs, + ) + return final_out diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/run.sh b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..d9e3a50405a7cd1b735d2e45762a533085d27eda --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/run.sh @@ -0,0 +1,39 @@ +export MODEL_REPO=mistralai/Mixtral-8x7B-Instruct-v0.1 +export CHECKPOINT_PATH=checkpoints/ + +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --compile +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --compile + +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int8wo --compile +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int8wo --compile + +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int8wo-base --compile +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int8wo-base --compile + +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int4wo --compile +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int4wo --compile + +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int4wo-base --compile +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int4wo-base --compile + +# # EXPERT CHOICE +# # python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int8dq --compile +# # # # python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int8dq --compile +# # python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant int8dq-base --compile +# # # # python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant int8dq-base --compile + +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant fp8wo --compile +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant fp8wo --compile + +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant fp8wo-base --compile +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant fp8wo-base --compile + +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant fp8dq --compile +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant fp8dq --compile + +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 1 --moe_quant fp8dq-base --compile +python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant fp8dq-base --compile + +# ARM +# python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant intxdq --device cpu +# python generate.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --batch_size 8 --moe_quant intxdq --compile --device cpu diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/convert_hf_checkpoint.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/convert_hf_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..6a39578e323c67474606e78e274092839bb918ce --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/convert_hf_checkpoint.py @@ -0,0 +1,115 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +import glob +import re +import sys +from pathlib import Path +from typing import Optional + +import torch + +# support running without installing as a package +wd = Path(__file__).parent.parent.resolve() +sys.path.append(str(wd)) + +from model import ModelArgs + + +@torch.inference_mode() +def convert_hf_checkpoint( + *, + checkpoint_dir: Path = Path("checkpoints/mistralai/Mixtral-8x7B-v0.1"), + model_name: Optional[str] = None, +) -> None: + if model_name is None: + model_name = checkpoint_dir.name + + config = ModelArgs.from_name(model_name) + print(f"Model config {config.__dict__}") + + weight_map = { + "tok_embeddings.weight": "tok_embeddings.weight", + "layers.{}.attention.wq.weight": "layers.{}.attention.wq.weight", + "layers.{}.attention.wk.weight": "layers.{}.attention.wk.weight", + "layers.{}.attention.wv.weight": "layers.{}.attention.wv.weight", + "layers.{}.attention.wo.weight": "layers.{}.attention.wo.weight", + "layers.{}.block_sparse_moe.w1": "layers.{}.block_sparse_moe.cond_ffn.w1", + "layers.{}.block_sparse_moe.w2": "layers.{}.block_sparse_moe.cond_ffn.w2", + "layers.{}.block_sparse_moe.w3": "layers.{}.block_sparse_moe.cond_ffn.w3", + "layers.{}.block_sparse_moe.gate.weight": "layers.{}.block_sparse_moe.gate.weight", + "layers.{}.attention_norm.weight": "layers.{}.attention_norm.weight", + "layers.{}.ffn_norm.weight": "layers.{}.ffn_norm.weight", + "norm.weight": "norm.weight", + "output.weight": "output.weight", + } + + pt_files = glob.glob(str(checkpoint_dir / "*.pt")) + + merged_result = {} + for file in sorted(pt_files): + state_dict = torch.load( + str(file), map_location="cpu", mmap=True, weights_only=True + ) + merged_result.update(state_dict) + final_result = {} + for key, value in merged_result.items(): + if "layers" in key: + abstract_key = re.sub(r".(\d+).", ".{}.", key) + layer_num = re.search(r"\d+", key).group(0) + new_key = weight_map[abstract_key] + if new_key is None: + continue + new_key = new_key.format(layer_num) + else: + new_key = weight_map[key] + + final_result[new_key] = value + + for key in tuple(final_result.keys()): + if "wq" in key: + q = final_result[key] + k = final_result[key.replace("wq", "wk")] + v = final_result[key.replace("wq", "wv")] + final_result[key.replace("wq", "wqkv")] = torch.cat([q, k, v]) + del final_result[key] + del final_result[key.replace("wq", "wk")] + del final_result[key.replace("wq", "wv")] + elif "w1" in key or "w3" in key: + final_result[key] = ( + final_result[key] + .reshape(config.num_experts, config.intermediate_size, config.dim) + .contiguous() + ) + elif "w2" in key: + final_result[key] = ( + final_result[key] + .reshape(config.num_experts, config.intermediate_size, config.dim) + .permute(0, 2, 1) + .contiguous() + ) + elif "gate" in key: + final_result[key] = final_result[key].contiguous() + + print(f"Saving checkpoint to {checkpoint_dir / 'model.pth'}") + torch.save(final_result, checkpoint_dir / "model.pth") + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Convert HuggingFace checkpoint.") + parser.add_argument( + "--checkpoint_dir", + type=Path, + default=Path("checkpoints/mistralai/Mixtral-8x7B-v0.1"), + ) + parser.add_argument("--model_name", type=str, default=None) + + args = parser.parse_args() + convert_hf_checkpoint( + checkpoint_dir=args.checkpoint_dir, + model_name=args.model_name, + ) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/download.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/download.py new file mode 100644 index 0000000000000000000000000000000000000000..8a451b001dae13d35510e7b331d24677a1898af9 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/download.py @@ -0,0 +1,48 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. +import os +from typing import Optional + +from requests.exceptions import HTTPError + + +def hf_download(repo_id: Optional[str] = None, hf_token: Optional[str] = None) -> None: + from huggingface_hub import snapshot_download + + os.makedirs(f"checkpoints/{repo_id}", exist_ok=True) + try: + snapshot_download( + repo_id, + local_dir=f"checkpoints/{repo_id}", + local_dir_use_symlinks=False, + token=hf_token, + ignore_patterns="*.safetensors", + ) + except HTTPError as e: + if e.response.status_code == 401: + print( + "You need to pass a valid `--hf_token=...` to download private checkpoints." + ) + else: + raise e + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description="Download data from HuggingFace Hub.") + parser.add_argument( + "--repo_id", + type=str, + default="mistralai/Mixtral-8x7B-Instruct-v0.1", + help="Repository ID to download from.", + ) + parser.add_argument( + "--hf_token", type=str, default=None, help="HuggingFace API token." + ) + + args = parser.parse_args() + hf_download(args.repo_id, args.hf_token) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/prepare.sh b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/prepare.sh new file mode 100644 index 0000000000000000000000000000000000000000..8ca60b165baf3b0c026ea14d527340e37f29bcb9 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/mixtral-moe/scripts/prepare.sh @@ -0,0 +1,2 @@ +python scripts/download.py --repo_id mistralai/Mixtral-8x7B-Instruct-v0.1 +python scripts/convert_hf_checkpoint.py --checkpoint_dir checkpoints/mistralai/Mixtral-8x7B-Instruct-v0.1 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/.gitignore b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..3e7cc59d91bf797b8750be7bd4623eff1a02b1c3 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/.gitignore @@ -0,0 +1,3 @@ +tmp +checkpoints +datasets diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/README.md b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/README.md new file mode 100644 index 0000000000000000000000000000000000000000..817e73d15259cc26670300379d7b12a9a9872e42 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/README.md @@ -0,0 +1,23 @@ +# benchmarking instructions: + +Setup your enviornment with: +``` +conda env create -n "saf-ao" python=3.10 +conda activate saf-ao +pip3 install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu126 +pip3 install git+https://github.com/pytorch-labs/segment-anything-fast.git +pip3 install tqdm fire pandas +cd ../.. && python setup.py install +``` + +Then download data and models by running +``` +sh setup.sh +``` + +Finally, you can run benchmarks with +``` +sh benchmark.sh +``` + +You can check out the result in results.csv diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/benchmark.sh b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/benchmark.sh new file mode 100644 index 0000000000000000000000000000000000000000..e446f62cbc4c706b033756425c6800bc1b553eb3 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/benchmark.sh @@ -0,0 +1,17 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +# baseline +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 +# int8 dynamic quant (all) +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 +# 2:4 sparsity (all) +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 +# 2:4 sparsity (mlp only) +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 +# int8 dynamic quant + 2:4 sparsity (attn: int8, mlp lin1: int8+2:4 fuse mul, mlp lin2: 2:4 sparse) +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 +# int8 dynamic quant attn + int4 wo + sparse marlin lin 1 + 2:4 sparse lin2 +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 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/data.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/data.py new file mode 100644 index 0000000000000000000000000000000000000000..d228dba18d3902bcb3b80ba32c613b0f4f19459d --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/data.py @@ -0,0 +1,308 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import diskcache +import numpy as np +import skimage.color as color +import skimage.io as io +import torch +from pycocotools.coco import COCO +from scipy import ndimage + + +def _get_center_point(mask, ann_id, cache): + """ + This is a rudimentary version of https://arxiv.org/pdf/2304.02643.pdf, + section D.1.Point Sampling + + From the paper: "The first point is chosen deterministically as the point + farthest from the object boundary." + + The code below is an approximation of this. + + First, we try to calculate the center of mass. If it's inside the mask, we + stop here. + + The centroid may be outside of the mask for some mask shapes. In this case + we do a slow hack, specifically, we check for the + minumum of the maximum distance from the boundary in four directions + (up, right, down, left), and take the point with the maximum of these + minimums. Note: this is not performant for large masks. + + Returns the center point in (x, y) format + """ + if ann_id in cache: + return cache[ann_id] + + # try the center of mass, keep it if it's inside the mask + com_y, com_x = ndimage.center_of_mass(mask) + com_y, com_x = int(round(com_y, 0)), int(round(com_x, 0)) + if mask[com_y][com_x]: + cache[ann_id] = (com_x, com_y) + return (com_x, com_y) + + # if center of mass didn't work, do the slow manual approximation + + # up, right, down, left + # TODO(future): approximate better by adding more directions + distances_to_check_deg = [0, 90, 180, 270] + + global_min_max_distance = float("-inf") + global_coords = None + # For now, terminate early to speed up the calculation as long as + # the point sample is gooe enough. This sacrifices the quality of point + # sampling for speed. In the future we can make this more accurate. + DISTANCE_GOOD_ENOUGH_THRESHOLD = 20 + + # Note: precalculating the bounding box could be somewhat + # helpful, but checked the performance gain and it's not much + # so leaving it out to keep the code simple. + # Note: tried binary search instead of incrementing by one to + # travel up/right/left/down, but that does not handle masks + # with all shapes properly (there could be multiple boundaries). + for row_idx in range(mask.shape[0]): + for col_idx in range(mask.shape[1]): + cur_point = mask[row_idx, col_idx] + + # skip points inside bounding box but outside mask + if not cur_point: + continue + + max_distances = [] + for direction in distances_to_check_deg: + # TODO(future) binary search instead of brute forcing it if we + # need a speedup, with the cache it doesn't really matter though + if direction == 0: + # UP + cur_row_idx = row_idx + + while cur_row_idx >= 0 and mask[cur_row_idx, col_idx]: + cur_row_idx = cur_row_idx - 1 + cur_row_idx += 1 + distance = row_idx - cur_row_idx + max_distances.append(distance) + + elif direction == 90: + # RIGHT + cur_col_idx = col_idx + + while ( + cur_col_idx <= mask.shape[1] - 1 and mask[row_idx, cur_col_idx] + ): + cur_col_idx += 1 + cur_col_idx -= 1 + distance = cur_col_idx - col_idx + max_distances.append(distance) + + elif direction == 180: + # DOWN + cur_row_idx = row_idx + while ( + cur_row_idx <= mask.shape[0] - 1 and mask[cur_row_idx, col_idx] + ): + cur_row_idx = cur_row_idx + 1 + cur_row_idx -= 1 + distance = cur_row_idx - row_idx + max_distances.append(distance) + + elif direction == 270: + # LEFT + cur_col_idx = col_idx + while cur_col_idx >= 0 and mask[row_idx, cur_col_idx]: + cur_col_idx -= 1 + cur_col_idx += 1 + distance = col_idx - cur_col_idx + max_distances.append(distance) + + min_max_distance = min(max_distances) + if min_max_distance > global_min_max_distance: + global_min_max_distance = min_max_distance + global_coords = (col_idx, row_idx) + if global_min_max_distance >= DISTANCE_GOOD_ENOUGH_THRESHOLD: + break + + cache[ann_id] = global_coords + return global_coords + + +def build_datapoint( + imgId, + coco, + pixel_mean, + pixel_std, + coco_root_dir, + coco_slice_name, + catIds, + cache, + predictor, + pad_input_image_batch, +): + img = coco.loadImgs(imgId)[0] + + file_location = f"{coco_root_dir}/{coco_slice_name}/{img['file_name']}" + I = io.imread(file_location) + if len(I.shape) == 2: + # some images, like img_id==61418, are grayscale + # convert to RGB to ensure the rest of the pipeline works + I = color.gray2rgb(I) + + # load and display instance annotations + annIds = coco.getAnnIds(imgIds=img["id"], catIds=catIds, iscrowd=None) + anns = coco.loadAnns(annIds) + + # approximate the center point of each mask + coords_list = [] + gt_masks_list = [] + for ann in anns: + ann_id = ann["id"] + mask = coco.annToMask(ann) + gt_masks_list.append(torch.tensor(mask)) + coords = _get_center_point(mask, ann_id, cache) + coords_list.append(coords) + + image = I + + # predictor_set_image begin + # Transform the image to the form expected by the model + input_image = predictor.transform.apply_image(image) + input_image_torch = torch.as_tensor(input_image) + input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :] + predictor_input_size = input_image_torch.shape[-2:] + + # Preprocess + x = input_image_torch + # Normalize colors + x = (x - pixel_mean) / pixel_std + + if pad_input_image_batch: + # Pad + h, w = x.shape[-2:] + padh = predictor.model.image_encoder.img_size - h + padw = predictor.model.image_encoder.img_size - w + x = torch.nn.functional.pad(x, (0, padw, 0, padh)) + else: + x = x.squeeze(0) + + gt_masks_list = torch.stack(gt_masks_list) if len(gt_masks_list) else None + return image, coords_list, gt_masks_list, anns, x, predictor_input_size + + +def build_data( + coco_img_ids, + coco, + catIds, + coco_root_dir, + coco_slice_name, + point_sampling_cache_dir, + predictor, + use_half, + pad_input_image_batch, +): + cache = diskcache.Cache(point_sampling_cache_dir) + # make sure you clear the cache if you change the point sampling algorithm + # cache.clear() + + pixel_mean = predictor.model.pixel_mean.cpu() + pixel_std = predictor.model.pixel_std.cpu() + + def build_batch(indicies): + batch = [[], [], [], [], [], [], [], [], [], [], []] + batch[3] = [0] + batch[6] = [0] + for img_idx in indicies: + imgId = coco_img_ids[img_idx] + + datapoint = build_datapoint( + imgId, + coco, + pixel_mean, + pixel_std, + coco_root_dir, + coco_slice_name, + catIds, + cache, + predictor, + pad_input_image_batch, + ) + I, coords_list, gt_masks_list, anns, x, predictor_input_size = datapoint + if len(coords_list) == 0: + continue + batch[0].append(x) + # batch[0].append(x[0]) + coords_list = predictor.transform.apply_coords( + np.array(coords_list), I.shape[:2] + ) + coords_list = torch.tensor(coords_list, dtype=torch.float) + + batch[1].append(coords_list.reshape(-1)) + batch[2].append(coords_list.size()) + batch[3].append(coords_list.numel() + batch[3][-1]) + + batch[4].append(gt_masks_list.reshape(-1)) + batch[5].append(gt_masks_list.size()) + batch[6].append(gt_masks_list.numel() + batch[6][-1]) + + batch[7].append(anns) + batch[8].append(I) + batch[9].append(predictor_input_size) + batch[10].append(img_idx) + + def cat_and_cast(b, use_half): + b = torch.cat(b) if len(b) > 0 else None + if use_half is not None and b is not None: + return b.to(use_half) + return b + + def to_nested_tensor(data, sizes=None, use_half=None): + if len(data) == 0: + return None + dtype = use_half if use_half is not None else torch.float32 + + if sizes is not None: + data = [d.view(s) for (d, s) in zip(data, sizes)] + + return torch.nested.nested_tensor(data, dtype=dtype, layout=torch.jagged) + + if pad_input_image_batch: + batch[0] = cat_and_cast(batch[0], use_half) + else: + batch[0] = to_nested_tensor(batch[0], use_half=use_half) + + batch[1] = cat_and_cast(batch[1], use_half) + + batch[4] = cat_and_cast(batch[4], False) + + return batch + + return build_batch + + +def setup_coco_img_ids(coco_root_dir, coco_slice_name, coco_category_names, img_id): + annFile = "{}/annotations/instances_{}.json".format(coco_root_dir, coco_slice_name) + + # initialize COCO api for instance annotations + coco = COCO(annFile) + + # display COCO categories and supercategories + cats = coco.loadCats(coco.getCatIds()) + cat_id_to_cat = {cat["id"]: cat for cat in cats} + # print('COCO categories: \n{}\n'.format(' '.join(nms))) + + # nms = set([cat['supercategory'] for cat in cats]) + # print('COCO supercategories: \n{}'.format(' '.join(nms))) + + if coco_category_names is not None: + catIds = coco.getCatIds(catNms=coco_category_names) + else: + catIds = coco.getCatIds() + + if img_id is not None: + coco_img_ids = [img_id] + elif coco_category_names is None: + coco_img_ids = coco.getImgIds() + else: + coco_img_ids = coco.getImgIds(catIds=catIds) + + return coco_img_ids, cat_id_to_cat, catIds, coco diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/eval_combo.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/eval_combo.py new file mode 100644 index 0000000000000000000000000000000000000000..a0410fb734d83c6eab4c675c102ecc29b0f5dcdb --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/eval_combo.py @@ -0,0 +1,692 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import math +import resource +import time + +import fire +import torch +import tqdm +from data import build_data, setup_coco_img_ids +from metrics import calculate_miou, create_result_entry + +import torchao +from torchao._models.utils import ( + get_arch_name, + write_json_result_local, + write_json_result_ossci, +) +from torchao.dtypes import SemiSparseLayout +from torchao.prototype.quantization.autoquant_v2 import autoquant_v2 +from torchao.quantization import ( + autoquant, + int4_weight_only, + int8_dynamic_activation_int8_weight, + quantize_, +) +from torchao.sparsity import apply_fake_sparsity, semi_sparse_weight, sparsify_ +from torchao.utils import TORCH_VERSION_AT_LEAST_2_5, unwrap_tensor_subclass + +torch._dynamo.config.cache_size_limit = 50000 + + +def unbind_jagged(device, data, sizes, offsets): + if data is None: + return None + data = data.to(device=device, non_blocking=True) + return [ + data[offsets[batch_idx] : offsets[batch_idx + 1]].view(sizes[batch_idx]) + for batch_idx in range(len(sizes)) + ] + + +PADDED_TENSOR = None + + +# Preallocate a "landing" Tensor for incoming data and reuse it across launches. +def pad_to_batch_size(batch, batch_size, device): + assert batch.dim() == 4 + # assert batch.is_pinned() + global PADDED_TENSOR + if PADDED_TENSOR is None: + batch = batch.to(device=device, non_blocking=True) + full_batch_size = (batch_size, batch.size(1), batch.size(2), batch.size(3)) + first_entry = batch[0].unsqueeze(0) + repeat_first_entry = first_entry.expand(full_batch_size) + padded_batch = torch.cat( + [batch, repeat_first_entry[batch.size(0) : batch_size]], dim=0 + ) + assert padded_batch.size() == full_batch_size + PADDED_TENSOR = padded_batch + PADDED_TENSOR[: batch.size(0)].copy_(batch, non_blocking=True) + return PADDED_TENSOR + + +def get_features_batch( + encoder, input_image_batch, pad_input_image_batch, batch_size, device +): + if pad_input_image_batch: + features_batch = encoder( + pad_to_batch_size(input_image_batch, batch_size, device) + ) + return features_batch[: input_image_batch.size(0)] + return encoder(input_image_batch) + + +def build_results_batch(predictor, batch, batch_size, pad_input_image_batch): + encoder = predictor.model.image_encoder + device = predictor.device + + input_image_batch = batch[0] + # The number of valid data points varies slightly per batch + orig_input_image_batch_size = input_image_batch.size(0) + if input_image_batch is None: + return (None, None, None) + + with torch.autograd.profiler.record_function("data transfer"): + coords_lists = unbind_jagged(*([device] + batch[1:4])) + gt_masks_lists = unbind_jagged(*([device] + batch[4:7])) + if coords_lists is None: + return (None, None, None) + datapoints = list(zip(*(batch[7:] + [coords_lists, gt_masks_lists]))) + if pad_input_image_batch: + # Pad to a static shape to avoid recompilation + input_image_batch = pad_to_batch_size(input_image_batch, batch_size, device) + else: + input_image_batch = input_image_batch.to(device=device, non_blocking=True) + + # We explicitly exclude data transfers from the timing to focus + # only on the kernel performance. + # Next we synchronize and set two events to start timing. + if torch.cuda.is_available(): + torch.cuda.synchronize() + start_event = torch.cuda.Event(enable_timing=True) + end_event = torch.cuda.Event(enable_timing=True) + start_event.record() + else: + t0 = time.time() + + with torch.autograd.profiler.record_function("timed region"): + with torch.autograd.profiler.record_function("image encoder"): + features_batch = encoder(input_image_batch) + features_batch = features_batch[:orig_input_image_batch_size] + + with torch.autograd.profiler.record_function("predict_torch"): + result_batch = [] + for batch_idx, ( + anns, + image, + input_size, + idx, + coords, + gt_masks, + ) in enumerate(datapoints): + features = features_batch.narrow(0, batch_idx, 1) + predictor.reset_image() + predictor.original_size = image.shape[:2] + predictor.input_size = input_size + predictor.features = features + predictor.is_image_set = True + coords = coords.unsqueeze(1) + fg_labels = torch.ones( + (coords.size(0), 1), dtype=torch.int, device=device + ) + masks, scores, logits = predictor.predict_torch( + point_coords=coords, + point_labels=fg_labels, + multimask_output=True, + ) + entry = create_result_entry(anns, gt_masks, masks, scores, idx) + result_batch += entry + + # After all kernels have been launched we synchronize again and measure + # the amount of time spent on the GPU. This is a fairly tight measurement + # around the launched GPU kernels and excludes data movement from host + # to device. + if torch.cuda.is_available(): + end_event.record() + torch.cuda.synchronize() + elapsed_time = start_event.elapsed_time(end_event) + else: + elapsed_time = time.time() - t0 + return result_batch, orig_input_image_batch_size, elapsed_time + + +def build_results( + batched_data_iter, + predictor, + mask_debug_out_dir, + batch_size, + use_compile, + use_compile_decoder, + pad_input_image_batch, + compress, + use_fullgraph=False, +): + # TODO: Re-enable this for datapoints + assert not use_compile_decoder + + batch_runner = build_results_batch + + results = [] + batch_idx = 0 + num_images = 0 + num_batches = 0 + elapsed_time = 0 + partial_batch = False + for batch in tqdm.tqdm(batched_data_iter): + with torch.no_grad(): + if batch_idx == 0: + with torch.autograd.profiler.record_function("compilation and warmup"): + if str(use_compile) != "False": + predictor.model.image_encoder = torch.compile( + predictor.model.image_encoder, + mode=use_compile, + fullgraph=use_fullgraph, + ) + # Run first batch a few times for warmup and exclude it from the final timings + for _ in range(5): + _ = batch_runner( + predictor, batch, batch_size, pad_input_image_batch + ) + result_batch, num_datapoints, kernel_time = batch_runner( + predictor, batch, batch_size, pad_input_image_batch + ) + if result_batch is not None: + results += result_batch + # We expect a partial batch to only happens once at the end + assert not partial_batch + # Only measure timing on full batches + if num_datapoints == batch_size: + num_images += num_datapoints + num_batches += 1 + # We consistently exclude the last (512 - filtered) images + # Since batch sizes must be powers of two and less than + # or equal 512 this ensures consistent timing across varying + # batch sizes. + if num_images <= 4488: + elapsed_time += kernel_time + else: + partial_batch = True + batch_idx += 1 + + avg_ms_per_img = None + if num_images > 0: + avg_ms_per_img = elapsed_time + avg_ms_per_img = avg_ms_per_img / num_images + + return results, avg_ms_per_img, num_batches, num_images + + +def identity_runner(fn, *args, **kwargs): + return fn(*args, **kwargs) + + +def profiler_runner(path, fn, *args, **kwargs): + with torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + torch.profiler.ProfilerActivity.CUDA, + ], + record_shapes=True, + ) as prof: + result = fn(*args, **kwargs) + prof.export_chrome_trace(path) + return result + + +def profile_top_runner(fn, *args, **kwargs): + with torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + torch.profiler.ProfilerActivity.CUDA, + ], + record_shapes=True, + ) as prof: + result = fn(*args, **kwargs) + if torch.cuda.is_available(): + print(prof.key_averages().table(sort_by="self_cuda_time_total", row_limit=-1)) + else: + print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=-1)) + return result + + +def memory_runner(path, fn, *args, **kwargs): + print("Start memory recording") + torch.cuda.synchronize() + torch.cuda.memory._record_memory_history( + True, trace_alloc_max_entries=100000, trace_alloc_record_context=True + ) + result = fn(*args, **kwargs) + torch.cuda.synchronize() + snapshot = torch.cuda.memory._snapshot() + print("Finish memory recording") + import pickle + + with open(path, "wb") as f: + pickle.dump(snapshot, f) + # Use to convert pickle file into html + # python torch/cuda/_memory_viz.py trace_plot .pickle -o .html + return result + + +def run( + coco_root_dir, + coco_slice_name, + sam_checkpoint_base_path, + sam_model_type, + point_sampling_cache_dir, + mask_debug_out_dir, + batch_size=1, + print_header=False, + coco_category_names=None, + limit=None, + img_id=None, + use_half=None, + use_compile="False", + use_compile_decoder=False, + compress=None, + min_sqnr=None, + num_workers=0, + use_rel_pos=True, + pad_input_image_batch=True, + profile_path=None, + profile_top=False, + memory_path=None, + device="cuda", + output_json_path=None, + output_json_local=False, +): + from torch._inductor import config as inductorconfig + + inductorconfig.triton.unique_kernel_names = True + inductorconfig.epilogue_fusion = True + inductorconfig.coordinate_descent_tuning = True + inductorconfig.coordinate_descent_check_all_directions = True + inductorconfig.force_fuse_int_mm_with_mul = True + inductorconfig.use_mixed_mm = True + from torch.sparse import SparseSemiStructuredTensor + + SparseSemiStructuredTensor._FORCE_CUTLASS = False + + if use_half is not None: + if use_half == "float16": + use_half = torch.float16 + elif use_half == "bfloat16": + use_half = torch.bfloat16 + else: + raise ValueError( + "Expected one of float16 or bfloat for specified {use_half}" + ) + + # Batch size needs to be a multiple of two and at most 512. + assert math.log2(batch_size).is_integer() + assert batch_size <= 512 + + # https://github.com/facebookresearch/segment-anything/tree/main#model-checkpoints + # largest to smallest: vit_h, vit_l, vit_b + model_type_to_checkpoint = { + "vit_h": f"{sam_checkpoint_base_path}/sam_vit_h_4b8939.pth", + "vit_l": f"{sam_checkpoint_base_path}/sam_vit_l_0b3195.pth", + "vit_b": f"{sam_checkpoint_base_path}/sam_vit_b_01ec64.pth", + } + + from segment_anything_fast import SamPredictor, sam_model_registry + + checkpoint_path = model_type_to_checkpoint[sam_model_type] + sam = sam_model_registry[sam_model_type](checkpoint=checkpoint_path).to( + torch.device(device) + ) + predictor = SamPredictor(sam) + + from segment_anything_fast import tools + + tools.apply_eval_dtype_predictor(predictor, use_half) + + for block in predictor.model.image_encoder.blocks: + block.attn.use_rel_pos = use_rel_pos + + # Helper filter functions + def attn_only(mod, name): + return isinstance(mod, torch.nn.Linear) and "attn" in name + + def mlp_lin1_only(mod, name): + return isinstance(mod, torch.nn.Linear) and "lin1" in name + + def mlp_lin2_only(mod, name): + return isinstance(mod, torch.nn.Linear) and "lin2" in name + + def mlp_only(mod, name): + return isinstance(mod, torch.nn.Linear) and "mlp" in name + + if compress == "int8_dynamic_quant": + quantize_(predictor.model.image_encoder, int8_dynamic_activation_int8_weight()) + if not TORCH_VERSION_AT_LEAST_2_5: + predictor.model.image_encoder = unwrap_tensor_subclass( + predictor.model.image_encoder + ) + elif compress == "sparse_mlp_only": + + def mlp_only(mod, name): + return isinstance(mod, torch.nn.Linear) and "mlp" in name + + apply_fake_sparsity(predictor.model.image_encoder, filter_fn=mlp_only) + sparsify_( + predictor.model.image_encoder, semi_sparse_weight(), filter_fn=mlp_only + ) + elif compress == "sparse": + apply_fake_sparsity(predictor.model.image_encoder) + sparsify_(predictor.model.image_encoder, semi_sparse_weight()) + elif compress == "int8_dynamic_quant_sparse": + # apply sparsify first to set qparams + apply_fake_sparsity(predictor.model.image_encoder, filter_fn=mlp_only) + + quantize_( + predictor.model.image_encoder, + int8_dynamic_activation_int8_weight(), + attn_only, + ) + quantize_( + predictor.model.image_encoder, + int8_dynamic_activation_int8_weight(layout=SemiSparseLayout()), + mlp_lin1_only, + ) + sparsify_(predictor.model.image_encoder, semi_sparse_weight(), mlp_lin2_only) + if not TORCH_VERSION_AT_LEAST_2_5: + predictor.model.image_encoder = unwrap_tensor_subclass( + predictor.model.image_encoder + ) + elif compress == "int4_weight_only_sparse": + # apply sparsify first to set qparams + apply_fake_sparsity(predictor.model.image_encoder, filter_fn=mlp_only) + from torchao.dtypes import MarlinSparseLayout + + quantize_( + predictor.model.image_encoder, + int8_dynamic_activation_int8_weight(), + attn_only, + ) + quantize_( + predictor.model.image_encoder, + int4_weight_only(layout=MarlinSparseLayout()), + mlp_lin1_only, + ) + sparsify_(predictor.model.image_encoder, semi_sparse_weight(), mlp_lin2_only) + if not TORCH_VERSION_AT_LEAST_2_5: + predictor.model.image_encoder = unwrap_tensor_subclass( + predictor.model.image_encoder + ) + + elif compress is not None and "autoquant_v2" in compress: + example_input = torch.randn( + 1, 3, 1024, 1024, dtype=torch.bfloat16, device=device + ) + if "autoquant_v2-int4" == compress: + autoquant_v2( + predictor.model.image_encoder, + example_input=example_input, + manual=True, + qtensor_class_list=torchao.prototype.quantization.autoquant_v2.DEFAULT_INT4_AUTOQUANT_CLASS_LIST, + ) + elif "autoquant_v2-float8" == compress: + autoquant_v2( + predictor.model.image_encoder, + example_input=example_input, + manual=True, + qtensor_class_list=torchao.prototype.quantization.autoquant_v2.OTHER_AUTOQUANT_CLASS_LIST, + ) + elif "autoquant_v2-all" == compress: + autoquant_v2( + predictor.model.image_encoder, + example_input=example_input, + manual=True, + qtensor_class_list=torchao.prototype.quantization.autoquant_v2.ALL_AUTOQUANT_CLASS_LIST, + ) + else: + autoquant_v2( + predictor.model.image_encoder, example_input=example_input, manual=True + ) + + predictor.model.image_encoder(example_input) + predictor.model.image_encoder.finalize_autoquant() + + elif compress is not None and "autoquant" in compress: + example_input = torch.randn( + 1, 3, 1024, 1024, dtype=torch.bfloat16, device=device + ) + if "autoquant-int4" == compress: + autoquant( + predictor.model.image_encoder, + example_input=example_input, + manual=True, + qtensor_class_list=torchao.quantization.DEFAULT_INT4_AUTOQUANT_CLASS_LIST, + min_sqnr=min_sqnr, + ) + elif "autoquant-float8" == compress: + autoquant( + predictor.model.image_encoder, + example_input=example_input, + manual=True, + qtensor_class_list=torchao.quantization.OTHER_AUTOQUANT_CLASS_LIST, + min_sqnr=min_sqnr, + ) + elif "autoquant-sparse" == compress: + autoquant( + predictor.model.image_encoder, + example_input=example_input, + manual=True, + qtensor_class_list=torchao.quantization.DEFAULT_SPARSE_AUTOQUANT_CLASS_LIST, + min_sqnr=min_sqnr, + ) + elif "autoquant-all" == compress: + autoquant( + predictor.model.image_encoder, + example_input=example_input, + manual=True, + qtensor_class_list=torchao.quantization.ALL_AUTOQUANT_CLASS_LIST, + min_sqnr=min_sqnr, + ) + else: + autoquant( + predictor.model.image_encoder, + example_input=example_input, + manual=True, + min_sqnr=min_sqnr, + ) + predictor.model.image_encoder(example_input) + predictor.model.image_encoder.finalize_autoquant() + else: + assert compress is None, f"Unsupported compress mode {compress}" + + coco_img_ids_, cat_id_to_cat, catIds, coco = setup_coco_img_ids( + coco_root_dir, coco_slice_name, coco_category_names, img_id + ) + + coco_img_ids = [] + for imgId in coco_img_ids_: + img = coco.loadImgs(imgId)[0] + annIds = coco.getAnnIds(imgIds=img["id"], catIds=catIds, iscrowd=None) + anns = coco.loadAnns(annIds) + if len(anns) != 0: + coco_img_ids.append(imgId) + + build_batch = build_data( + coco_img_ids, + coco, + catIds, + coco_root_dir, + coco_slice_name, + point_sampling_cache_dir, + predictor, + use_half, + pad_input_image_batch, + ) + + limit = len(coco_img_ids) if limit is None else limit + batched_data_iter = torch.utils.data.DataLoader( + list(range(limit)), + batch_size=batch_size, + collate_fn=build_batch, + num_workers=num_workers, + pin_memory=False, + ) + runner = identity_runner + + if profile_path is not None: + import functools + + runner = functools.partial(profiler_runner, profile_path) + + if profile_top: + runner = profile_top_runner + + if memory_path is not None: + assert use_compile != "max-autotune", ( + f"Memory path does not support {use_compile}" + ) + import functools + + runner = functools.partial(memory_runner, memory_path) + + results, avg_ms_per_img, num_batches, num_images = runner( + build_results, + batched_data_iter, + predictor, + mask_debug_out_dir, + batch_size, + use_compile, + use_compile_decoder, + pad_input_image_batch, + compress, + ) + + results = [[r[0], r[1], r[2], r[3].item()] for r in results] + + img_s, batch_ms_batch_size = None, None + if avg_ms_per_img is not None: + img_s = 1000 / avg_ms_per_img + batch_ms_batch_size = (avg_ms_per_img * num_images) / num_batches / batch_size + + mIoU = calculate_miou(results, mask_debug_out_dir, True, cat_id_to_cat) + if torch.cuda.is_available(): + max_memory_allocated_bytes = torch.cuda.max_memory_allocated() + _, total_memory = torch.cuda.mem_get_info() + max_memory_allocated_percentage = int( + 100 * (max_memory_allocated_bytes / total_memory) + ) + max_memory_allocated_bytes = max_memory_allocated_bytes >> 20 + else: + import psutil + + total_memory = psutil.virtual_memory().total + max_memory_allocated_bytes = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + max_memory_allocated_percentage = int( + 100 * (max_memory_allocated_bytes / (total_memory >> 10)) + ) + max_memory_allocated_bytes = max_memory_allocated_bytes >> 10 + + with open("results.csv", "a") as f: + if print_header: + header = ",".join( + [ + "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", + ] + ) + f.write(header + "\n") + vals = ",".join( + map( + str, + [ + device, + sam_model_type, + batch_size, + max_memory_allocated_bytes, + max_memory_allocated_percentage, + img_s, + batch_ms_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, + ], + ) + ) + f.write(vals + "\n") + + if output_json_path: + headers = [ + "name", + "dtype", + "min_sqnr", + "compile", + "device", + "arch", + "metric", + "actual", + "target", + ] + name = sam_model_type + arch = get_arch_name() + dtype = compress or "noquant" + # boolean flag to indicate whether compile is used + compile = use_compile != "False" + memory_result = [ + name, + dtype, + min_sqnr, + compile, + device, + arch, + "memory(MiB)", + max_memory_allocated_bytes, + None, + ] + performance_result = [ + name, + dtype, + min_sqnr, + compile, + device, + arch, + "img_s(avg)", + img_s, + None, + ] + write_json_result = ( + write_json_result_local if output_json_local else write_json_result_ossci + ) + write_json_result(output_json_path, headers, memory_result) + write_json_result(output_json_path, headers, performance_result) + + +if __name__ == "__main__": + fire.Fire(run) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/flash_4_configs.p b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/flash_4_configs.p new file mode 100644 index 0000000000000000000000000000000000000000..4b6e234d0d8dc9753a04c57ae001b4cedd232e1f Binary files /dev/null and b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/flash_4_configs.p differ diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/metrics.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..6a20a9f036a1b0c30f6931cafaa1599db377b57b --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/metrics.py @@ -0,0 +1,76 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import pandas as pd +import torch + + +def create_result_entry(anns, gt_masks_list, masks, scores, img_idx): + argmax_scores = torch.argmax(scores, dim=1) + inference_masks = masks.gather( + 1, + argmax_scores.unsqueeze(-1) + .unsqueeze(-1) + .unsqueeze(-1) + .expand((masks.size(0), 1, masks.size(2), masks.size(3))), + ).squeeze(1) + + def _iou(mask1, mask2): + assert mask1.dim() == 3 + assert mask2.dim() == 3 + intersection = torch.logical_and(mask1, mask2) + union = torch.logical_or(mask1, mask2) + return intersection.sum(dim=(-1, -2)) / union.sum(dim=(-1, -2)) + + top_score_ious = _iou(inference_masks, gt_masks_list) + + entry = [] + for idx in range(top_score_ious.size(0)): + entry.append( + [img_idx, anns[idx]["id"], anns[idx]["category_id"], top_score_ious[idx]] + ) + return entry + + +def calculate_miou(results, mask_debug_out_dir, silent, cat_id_to_cat): + df = pd.DataFrame(results, columns=["img_id", "ann_id", "cat_id", "iou"]) + df.to_csv(f"{mask_debug_out_dir}/df.csv") + df["supercategory"] = df["cat_id"].map( + lambda cat_id: cat_id_to_cat[cat_id]["supercategory"] + ) + df["category"] = df["cat_id"].map(lambda cat_id: cat_id_to_cat[cat_id]["name"]) + + # TODO: cross reference the specifics of how we calculate mIoU with + # the SAM folks (should it be per dataset, per category, per image, etc) + # currently, just calculate them all + + # TODO: QOL save the summaries to file + + # per category + per_category = pd.pivot_table( + df, + values="iou", + index=["cat_id", "supercategory", "category"], + aggfunc=("mean", "count"), + ) + if not silent: + print("\nmIoU averaged per category") + print(per_category) + + # per super-category + per_supercategory = pd.pivot_table( + df, values="iou", index=["supercategory"], aggfunc=("mean", "count") + ) + if not silent: + print("\nmIoU averaged per supercategory") + print(per_supercategory) + + # per all selected masks + per_all_masks_agg = df["iou"].agg(["mean", "count"]) + if not silent: + print("\nmIoU averaged per all selected masks") + print(per_all_masks_agg) + + return df["iou"].agg(["mean", "count"])["mean"] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/results.csv b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/results.csv new file mode 100644 index 0000000000000000000000000000000000000000..5ae8a6dbd03099bc339af874c03ba3d9ef3a389e --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/results.csv @@ -0,0 +1,7 @@ +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 +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 +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 +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 +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 +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 +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 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/setup.sh b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..3fcfa124625994ee276761430bee5364b7e91ecc --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam/setup.sh @@ -0,0 +1,26 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +SETUP_HOME=$(pwd) + + +mkdir -p checkpoints +mkdir -p datasets + +mkdir -p tmp +mkdir -p tmp/sam_coco_mask_center_cache +mkdir -p tmp/sam_eval_masks_out + +wget -nc -P checkpoints https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth +wget -nc -P checkpoints https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth +wget -nc -P checkpoints https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth + +mkdir -p datasets/coco2017 +wget -nc -P datasets/coco2017 http://images.cocodataset.org/zips/val2017.zip +wget -nc -P datasets/coco2017 http://images.cocodataset.org/annotations/annotations_trainval2017.zip + +cd datasets/coco2017 && unzip -n val2017.zip && cd $SETUP_HOME +cd datasets/coco2017 && unzip -n annotations_trainval2017.zip && cd $SETUP_HOME diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0dc11c2fdec08a17b72087dd50195c899b9d42ff --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/__init__.py @@ -0,0 +1,11 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from hydra import initialize_config_module +from hydra.core.global_hydra import GlobalHydra + +if not GlobalHydra.instance().is_initialized(): + initialize_config_module("torchao._models.sam2", version_base="1.2") diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/automatic_mask_generator.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/automatic_mask_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..c3b72318ba963004ea9fd8f936ce4b8852ba6226 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/automatic_mask_generator.py @@ -0,0 +1,759 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +# Adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/automatic_mask_generator.py +from typing import Any, Dict, List, Optional, Tuple, Union + +import numpy as np +import torch +from torchvision.ops.boxes import batched_nms, box_area # type: ignore + +from torchao._models.sam2.modeling.sam2_base import SAM2Base +from torchao._models.sam2.sam2_image_predictor import SAM2ImagePredictor +from torchao._models.sam2.utils.amg import ( + MaskData, + _mask_to_rle_pytorch_2_0, + _mask_to_rle_pytorch_2_1, + area_from_rle, + batch_iterator, + batched_mask_to_box, + box_xyxy_to_xywh, + build_all_layer_point_grids, + calculate_stability_score, + coco_encode_rle, + generate_crop_boxes, + is_box_near_crop_edge_torch, + mask_to_rle_pytorch, + remove_small_regions, + rle_to_mask, + uncrop_boxes_xyxy, + uncrop_masks, + uncrop_points, +) +from torchao._models.sam2.utils.misc import ( + crop_image, + get_image_size, +) + + +class SAM2AutomaticMaskGenerator(torch.nn.Module): + def __init__( + self, + model: SAM2Base, + points_per_side: Optional[int] = 32, + points_per_batch: int = 64, + pred_iou_thresh: float = 0.8, + stability_score_thresh: float = 0.95, + stability_score_offset: float = 1.0, + mask_threshold: float = 0.0, + box_nms_thresh: float = 0.7, + crop_n_layers: int = 0, + crop_nms_thresh: float = 0.7, + crop_overlap_ratio: float = 512 / 1500, + crop_n_points_downscale_factor: int = 1, + point_grids: Optional[List[np.ndarray]] = None, + min_mask_region_area: int = 0, + output_mode: str = "binary_mask", + use_m2m: bool = False, + multimask_output: bool = True, + **kwargs, + ) -> None: + """ + Using a SAM 2 model, generates masks for the entire image. + Generates a grid of point prompts over the image, then filters + low quality and duplicate masks. The default settings are chosen + for SAM 2 with a HieraL backbone. + + Arguments: + model (Sam): The SAM 2 model to use for mask prediction. + points_per_side (int or None): The number of points to be sampled + along one side of the image. The total number of points is + points_per_side**2. If None, 'point_grids' must provide explicit + point sampling. + points_per_batch (int): Sets the number of points run simultaneously + by the model. Higher numbers may be faster but use more GPU memory. + pred_iou_thresh (float): A filtering threshold in [0,1], using the + model's predicted mask quality. + stability_score_thresh (float): A filtering threshold in [0,1], using + the stability of the mask under changes to the cutoff used to binarize + the model's mask predictions. + stability_score_offset (float): The amount to shift the cutoff when + calculated the stability score. + mask_threshold (float): Threshold for binarizing the mask logits + box_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks. + crop_n_layers (int): If >0, mask prediction will be run again on + crops of the image. Sets the number of layers to run, where each + layer has 2**i_layer number of image crops. + crop_nms_thresh (float): The box IoU cutoff used by non-maximal + suppression to filter duplicate masks between different crops. + crop_overlap_ratio (float): Sets the degree to which crops overlap. + In the first crop layer, crops will overlap by this fraction of + the image length. Later layers with more crops scale down this overlap. + crop_n_points_downscale_factor (int): The number of points-per-side + sampled in layer n is scaled down by crop_n_points_downscale_factor**n. + point_grids (list(np.ndarray) or None): A list over explicit grids + of points used for sampling, normalized to [0,1]. The nth grid in the + list is used in the nth crop layer. Exclusive with points_per_side. + min_mask_region_area (int): If >0, postprocessing will be applied + to remove disconnected regions and holes in masks with area smaller + than min_mask_region_area. Requires opencv. + output_mode (str): The form masks are returned in. Can be 'binary_mask', + 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools. + For large resolutions, 'binary_mask' may consume large amounts of + memory. + use_m2m (bool): Whether to add a one step refinement using previous mask predictions. + multimask_output (bool): Whether to output multimask at each point of the grid. + """ + super().__init__() + assert (points_per_side is None) != (point_grids is None), ( + "Exactly one of points_per_side or point_grid must be provided." + ) + if points_per_side is not None: + self.point_grids = build_all_layer_point_grids( + points_per_side, + crop_n_layers, + crop_n_points_downscale_factor, + ) + elif point_grids is not None: + self.point_grids = point_grids + else: + raise ValueError("Can't have both points_per_side and point_grid be None.") + + assert output_mode in [ + "binary_mask", + "uncompressed_rle", + "coco_rle", + ], f"Unknown output_mode {output_mode}." + if output_mode == "coco_rle": + try: + from pycocotools import mask as mask_utils # type: ignore # noqa: F401 + except ImportError as e: + print("Please install pycocotools") + raise e + + self.predictor = SAM2ImagePredictor( + model, + max_hole_area=min_mask_region_area, + max_sprinkle_area=min_mask_region_area, + ) + self.points_per_batch = points_per_batch + self.pred_iou_thresh = pred_iou_thresh + self.stability_score_thresh = stability_score_thresh + self.stability_score_offset = stability_score_offset + self.mask_threshold = mask_threshold + self.box_nms_thresh = box_nms_thresh + self.crop_n_layers = crop_n_layers + self.crop_nms_thresh = crop_nms_thresh + self.crop_overlap_ratio = crop_overlap_ratio + self.crop_n_points_downscale_factor = crop_n_points_downscale_factor + self.min_mask_region_area = min_mask_region_area + self.output_mode = output_mode + self.use_m2m = use_m2m + self.multimask_output = multimask_output + + # Store a reference to these on the model so I can overwrite them + # with compile annotation if desired + + self.calculate_stability_score = calculate_stability_score + self.batched_mask_to_box = batched_mask_to_box + + @classmethod + def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2AutomaticMaskGenerator": + """ + Load a pretrained model from the Hugging Face hub. + + Arguments: + model_id (str): The Hugging Face repository ID. + **kwargs: Additional arguments to pass to the model constructor. + + Returns: + (SAM2AutomaticMaskGenerator): The loaded model. + """ + from sam2.build_sam import build_sam2_hf + + sam_model = build_sam2_hf(model_id, **kwargs) + return cls(sam_model, **kwargs) + + @torch.no_grad() + def generate(self, image: np.ndarray) -> List[Dict[str, Any]]: + """ + Generates masks for the given image. + + Arguments: + image (np.ndarray): The image to generate masks for, in HWC uint8 format. + + Returns: + list(dict(str, any)): A list over records for masks. Each record is + a dict containing the following keys: + segmentation (dict(str, any) or np.ndarray): The mask. If + output_mode='binary_mask', is an array of shape HW. Otherwise, + is a dictionary containing the RLE. + bbox (list(float)): The box around the mask, in XYWH format. + area (int): The area in pixels of the mask. + predicted_iou (float): The model's own prediction of the mask's + quality. This is filtered by the pred_iou_thresh parameter. + point_coords (list(list(float))): The point coordinates input + to the model to generate this mask. + stability_score (float): A measure of the mask's quality. This + is filtered on using the stability_score_thresh parameter. + crop_box (list(float)): The crop of the image used to generate + the mask, given in XYWH format. + """ + + # Generate masks + mask_data = self._generate_masks(image) + + return self._encode_masks(mask_data) + + def _encode_masks(self, mask_data): + mask_data["rles"] = _mask_to_rle_pytorch_2_1(mask_data["rles"]) + # Encode masks + if self.output_mode == "coco_rle": + mask_data["segmentations"] = [ + coco_encode_rle(rle) for rle in mask_data["rles"] + ] + elif self.output_mode == "binary_mask": + mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]] + else: + mask_data["segmentations"] = mask_data["rles"] + + # Write mask records + curr_anns = [] + for idx in range(len(mask_data["segmentations"])): + ann = { + "segmentation": mask_data["segmentations"][idx], + "area": area_from_rle(mask_data["rles"][idx]), + "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(), + "predicted_iou": mask_data["iou_preds"][idx].item(), + "point_coords": [mask_data["points"][idx].tolist()], + "stability_score": mask_data["stability_score"][idx].item(), + "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(), + } + curr_anns.append(ann) + + return curr_anns + + @torch.no_grad() + def generate_batch(self, images: List[np.ndarray]) -> List[List[Dict[str, Any]]]: + data = self._generate_masks_batch(images) + return [self._encode_masks(d) for d in data] + + def _generate_masks(self, image: Union[np.ndarray, torch.Tensor]) -> MaskData: + orig_size = get_image_size(image) + crop_boxes, layer_idxs = generate_crop_boxes( + orig_size, self.crop_n_layers, self.crop_overlap_ratio + ) + + # Iterate over image crops + data = None + for crop_box, layer_idx in zip(crop_boxes, layer_idxs): + crop_data = self._process_crop(image, crop_box, layer_idx, orig_size) + if data is None: + data = crop_data + else: + data.cat(crop_data) + + return self._deduplicate_masks(crop_boxes, data) + + def _deduplicate_masks(self, crop_boxes, data): + # Remove duplicate masks between crops + if len(crop_boxes) > 1: + # Prefer masks from smaller crops + scores = 1 / box_area(data["crop_boxes"]) + scores = scores.to(data["boxes"].device) + keep_by_nms = batched_nms( + data["boxes"].float(), + scores, + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.crop_nms_thresh, + ) + data.filter(keep_by_nms) + data.to_numpy() + return data + + def _generate_masks_batch(self, images: List[np.ndarray]) -> List[MaskData]: + all_orig_size = [] + all_crop_boxes = [] + all_layer_idxs = [] + for image in images: + orig_size = get_image_size(image) + all_orig_size.append(orig_size) + crop_boxes, layer_idxs = generate_crop_boxes( + orig_size, self.crop_n_layers, self.crop_overlap_ratio + ) + all_crop_boxes.append(crop_boxes) + all_layer_idxs.append(layer_idxs) + + all_data = self._process_crop_batch( + images, all_crop_boxes, all_layer_idxs, all_orig_size + ) + + return [ + self._deduplicate_masks(crop_boxes, data) + for (crop_boxes, data) in zip(all_crop_boxes, all_data) + ] + + def _process_crop( + self, + image: np.ndarray, + crop_box: List[int], + crop_layer_idx: int, + orig_size: Tuple[int, ...], + ) -> MaskData: + # Crop the image and calculate embeddings + cropped_im = crop_image(image, crop_box) + cropped_im_size = get_image_size(cropped_im) + with torch.autograd.profiler.record_function("set_image"): + self.predictor.set_image(cropped_im) + + return self._process_crop_points( + cropped_im_size, crop_layer_idx, crop_box, orig_size + ) + + def _process_crop_points( + self, cropped_im_size, crop_layer_idx, crop_box, orig_size + ): + # Get points for this crop + points_scale = np.array(cropped_im_size)[None, ::-1] + points_for_image = self.point_grids[crop_layer_idx] * points_scale + + # Generate masks for this crop in batches + # data = MaskData() + data = None + points_per_batch = self.points_per_batch + if self.points_per_batch is None: + points_per_batch = len(points_for_image) + for (points,) in batch_iterator(points_per_batch, points_for_image): + batch_data = self._process_batch( + points, cropped_im_size, crop_box, orig_size, normalize=True + ) + with torch.autograd.profiler.record_function("data.cat"): + if data is None: + data = batch_data + else: + data.cat(batch_data) + del batch_data + self.predictor.reset_predictor() + return self._process_crop_points_dedup(data, crop_box) + + def _process_crop_points_dedup(self, data, crop_box): + with torch.autograd.profiler.record_function("batched_nms"): + # Remove duplicates within this crop. + keep_by_nms = batched_nms( + data["boxes"].float(), + data["iou_preds"], + torch.zeros_like(data["boxes"][:, 0]), # categories + iou_threshold=self.box_nms_thresh, + ) + + with torch.autograd.profiler.record_function("filter"): + data.filter(keep_by_nms) + + with torch.autograd.profiler.record_function("uncrop_boxes_xyxy"): + # Return to the original image frame + data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box) + with torch.autograd.profiler.record_function("uncrop_points"): + data["points"] = uncrop_points(data["points"], crop_box) + with torch.autograd.profiler.record_function("crop_boxes"): + data["crop_boxes"] = torch.tensor( + [crop_box for _ in range(len(data["rles"]))] + ) + + return data + + def _process_crop_batch( + self, + images: List[np.ndarray], + all_crop_boxes: List[List[int]], + all_layer_idxs: List[int], + all_orig_size_compact: List[Tuple[int, ...]], + ) -> List[MaskData]: + all_image = [] + all_crop_box = [] + all_layer_idx = [] + all_orig_size = [] + for image, orig_size, crop_boxes, layer_idxs in zip( + images, all_orig_size_compact, all_crop_boxes, all_layer_idxs + ): + # Iterate over image crops + for crop_box, layer_idx in zip(crop_boxes, layer_idxs): + all_image.append(image) + all_crop_box.append(crop_box) + all_layer_idx.append(layer_idx) + all_orig_size.append(orig_size) + + # # TODO: NOTE: Calling process_crop in a loop like this might be an issue, because the predictor is stateful + + all_cropped_im = [ + crop_image(image, crop_box) + for image, crop_box in zip(all_image, all_crop_box) + ] + + with torch.autograd.profiler.record_function("set_batch_image"): + self.predictor.set_image_batch(all_cropped_im) + + i = 0 + batch_features = self.predictor._features + all_crop_data = [] + for cropped_im, crop_box, layer_idx, orig_size in zip( + all_cropped_im, all_crop_box, all_layer_idx, all_orig_size + ): + cropped_im_size = get_image_size(cropped_im) + self.predictor._orig_hw = [get_image_size(cropped_im)] + self.predictor._features = { + "image_embed": batch_features["image_embed"][i].unsqueeze(0), + "high_res_feats": [ + b[i].unsqueeze(0) for b in batch_features["high_res_feats"] + ], + } + i += 1 + self.predictor._is_image_set = True + + # TODO: Batch mask_to_rle_pytorch_2 calls + # TODO: Specialize for rle-only return (specify which keys you want in data) + + # all_crop_data.append(self._process_crop_points(cropped_im_size, layer_idx, crop_box, orig_size)) + + crop_layer_idx = layer_idx + + # Get points for this crop + points_scale = np.array(cropped_im_size)[None, ::-1] + points_for_image = self.point_grids[crop_layer_idx] * points_scale + + # Generate masks for this crop in batches + points_per_batch = self.points_per_batch + if self.points_per_batch is None: + points_per_batch = len(points_for_image) + + all_batch_iterator_data = [] + with torch.autograd.profiler.record_function("all _process_batch"): + for (points,) in batch_iterator(points_per_batch, points_for_image): + # batch_data = self._process_batch( + # points, cropped_im_size, crop_box, orig_size, normalize=True + # ) + + im_size = cropped_im_size + normalize = True + + orig_h, orig_w = orig_size + + orig_box = [0, 0, orig_w, orig_h] + orig_box_torch = torch.as_tensor( + orig_box, dtype=torch.float, device=self.predictor.device + ) + crop_box_torch = torch.as_tensor( + crop_box, dtype=torch.float, device=self.predictor.device + ) + data = self._process_batch_fullgraph( + points, + im_size, + crop_box, + crop_box_torch, + orig_size, + normalize, + orig_box_torch, + ) + all_batch_iterator_data.append(data) + self.predictor.reset_predictor() + + result_data = None + with torch.autograd.profiler.record_function("all mask_to_rle_pytorch_2"): + for data in all_batch_iterator_data: + # Compress to RLE + data["masks"] = uncrop_masks( + data["masks"], crop_box, orig_h, orig_w + ) + # TODO: Capture all these masks in a single NT for mask_to_rle_pytorch_2 + # or at a minimum create a mask_to_rle_pytorch_2_list and use loops + # to cause a single DtoH sync + data["rles"] = _mask_to_rle_pytorch_2_0(data["masks"]) + del data["masks"] + + batch_data = data + with torch.autograd.profiler.record_function("data.cat"): + if result_data is None: + result_data = batch_data + else: + result_data.cat(batch_data) + del batch_data + self.predictor.reset_predictor() + + all_crop_data.append(self._process_crop_points_dedup(result_data, crop_box)) + + i = 0 + all_data = [] + for _, _, crop_boxes, layer_idxs in zip( + images, all_orig_size, all_crop_boxes, all_layer_idxs + ): + data = None + for _, _ in zip(crop_boxes, layer_idxs): + if data is None: + data = all_crop_data[i] + else: + data.cat(all_crop_data[i]) + i += 1 + all_data.append(data) + return all_data + + def _process_batch_fullgraph( + self, + points: np.ndarray, + im_size: Tuple[int, ...], + crop_box: List[int], + crop_box_torch: torch.Tensor, + orig_size: Tuple[int, ...], + normalize: bool, + orig_box_torch: torch.Tensor, + ) -> MaskData: + orig_h, orig_w = orig_size + + # Run model on this batch + points = torch.as_tensor(points, dtype=torch.float32).pin_memory() + points = points.to(device=self.predictor.device, non_blocking=True) + in_points = self.predictor._transforms.transform_coords( + points, normalize=normalize, orig_hw=im_size + ) + in_labels = torch.ones( + in_points.shape[0], dtype=torch.int, device=in_points.device + ) + with torch.autograd.profiler.record_function("_predict"): + # NOTE: Just leaving this for reference. predict was split to + # allow earlier filtering by predicted iou + # masks, iou_preds, low_res_masks = self.predictor._predict( + masks = None + high_res_feats = self.predictor._features["high_res_feats"] + image_embed = self.predictor._features["image_embed"] + image_pe = self.predictor.model.sam_prompt_encoder.get_dense_pe().clone() + assert self.multimask_output, ( + "Currently require multimask_output set to True" + ) + high_res_feats_input = [ + feat_level[-1].unsqueeze(0).clone() + # for feat_level in self._features["high_res_feats"] + for feat_level in high_res_feats + ] + image_embed_input = image_embed[-1].unsqueeze(0).clone() + low_res_masks, iou_preds = self.predictor._predict_masks( + [t.contiguous() for t in high_res_feats_input], + image_embed_input.contiguous(), + image_pe.contiguous(), + in_points[:, None, :].contiguous(), + in_labels[:, None].contiguous(), + boxes=None, + mask_input=None, + multimask_output=self.multimask_output, + # img_idx=-1, + ) + + x0, y0, _, _ = crop_box + points = points.repeat_interleave(3 if masks is None else masks.shape[1], dim=0) + + if not self.use_m2m: + with torch.autograd.profiler.record_function("thresh and filter"): + # Filter by predicted IoU + if self.pred_iou_thresh > 0.0: + keep_mask = iou_preds.flatten(0, 1) > self.pred_iou_thresh + keep_index = keep_mask.nonzero(as_tuple=True)[0] + low_res_masks = low_res_masks.flatten(0, 1).unsqueeze(1) + low_res_masks = low_res_masks[keep_index] + iou_preds = iou_preds.flatten(0, 1).unsqueeze(1)[keep_index] + points = points[keep_index] + if masks is None: + masks, low_res_mask = self.predictor._predict_masks_postprocess( + low_res_masks, -1, True, channel_1=low_res_masks.size(1) == 1 + ) + + # Serialize predictions and store in MaskData + with torch.autograd.profiler.record_function("MaskData"): + data = MaskData( + masks=masks.flatten(0, 1), + iou_preds=iou_preds.flatten(0, 1), + points=points, + low_res_masks=low_res_masks.flatten(0, 1), + ) + del masks + + keep_mask = None + + if not self.use_m2m: + # NOTE: This is left just for reference. We filter earlier for this case to save + # on compute within the expensive _predict_masks_postprocess + # with torch.autograd.profiler.record_function("thresh and filter"): + # # Filter by predicted IoU + # if self.pred_iou_thresh > 0.0: + # keep_mask = data["iou_preds"] > self.pred_iou_thresh + # # TODO: Might need this for correctness due to calculate_stability_score IoU? + # data.filter(keep_mask) + + with torch.autograd.profiler.record_function("calculate_stability_score"): + # Calculate and filter by stability score + data["stability_score"] = self.calculate_stability_score( + data["masks"], self.mask_threshold, self.stability_score_offset + ) + with torch.autograd.profiler.record_function("stability_score_thresh"): + if self.stability_score_thresh > 0.0: + keep_mask = data["stability_score"] >= self.stability_score_thresh + keep_index = keep_mask.nonzero(as_tuple=True)[0] + data.filter(keep_index) + else: + # One step refinement using previous mask predictions + in_points = self.predictor._transforms.transform_coords( + data["points"], normalize=normalize, orig_hw=im_size + ) + labels = torch.ones( + in_points.shape[0], dtype=torch.int, device=in_points.device + ) + masks, ious = self.refine_with_m2m( + in_points, labels, data["low_res_masks"], self.points_per_batch + ) + data["masks"] = masks.squeeze(1) + data["iou_preds"] = ious.squeeze(1) + + if self.pred_iou_thresh > 0.0: + keep_mask = data["iou_preds"] > self.pred_iou_thresh + data.filter(keep_mask) + + data["stability_score"] = self.calculate_stability_score( + data["masks"], self.mask_threshold, self.stability_score_offset + ) + if self.stability_score_thresh > 0.0: + keep_mask = data["stability_score"] >= self.stability_score_thresh + data.filter(keep_mask) + + with torch.autograd.profiler.record_function( + "Threshold masks and calculate boxes" + ): + # Threshold masks and calculate boxes + data["masks"] = data["masks"] > self.mask_threshold + data["boxes"] = self.batched_mask_to_box(data["masks"]) + + with torch.autograd.profiler.record_function("is_box_near_crop_edge"): + # Filter boxes that touch crop boundaries + keep_mask = ~is_box_near_crop_edge_torch( + data["boxes"], + crop_box, + crop_box_torch, + orig_box_torch, + ) + + with torch.autograd.profiler.record_function("filter(keep_mask)"): + keep_index = keep_mask.nonzero(as_tuple=True)[0] + data.filter(keep_index) + + return data + + def _process_batch( + self, + points: np.ndarray, + im_size: Tuple[int, ...], + crop_box: List[int], + orig_size: Tuple[int, ...], + normalize=False, + ) -> MaskData: + orig_h, orig_w = orig_size + + orig_box = [0, 0, orig_w, orig_h] + orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float) + orig_box_torch = orig_box_torch.pin_memory() + orig_box_torch = orig_box_torch.to( + device=self.predictor.device, non_blocking=True + ) + + crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float) + crop_box_torch = crop_box_torch.pin_memory() + crop_box_torch = crop_box_torch.to( + device=self.predictor.device, non_blocking=True + ) + + data = self._process_batch_fullgraph( + points, + im_size, + crop_box, + crop_box_torch, + orig_size, + normalize, + orig_box_torch, + ) + + with torch.autograd.profiler.record_function("uncrop_masks"): + # Compress to RLE + data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w) + data["rles"] = _mask_to_rle_pytorch_2_0(data["masks"]) + del data["masks"] + + return data + + @staticmethod + def postprocess_small_regions( + mask_data: MaskData, min_area: int, nms_thresh: float + ) -> MaskData: + """ + Removes small disconnected regions and holes in masks, then reruns + box NMS to remove any new duplicates. + + Edits mask_data in place. + + Requires open-cv as a dependency. + """ + if len(mask_data["rles"]) == 0: + return mask_data + + # Filter small disconnected regions and holes + new_masks = [] + scores = [] + for rle in mask_data["rles"]: + mask = rle_to_mask(rle) + + mask, changed = remove_small_regions(mask, min_area, mode="holes") + unchanged = not changed + mask, changed = remove_small_regions(mask, min_area, mode="islands") + unchanged = unchanged and not changed + + new_masks.append(torch.as_tensor(mask).unsqueeze(0)) + # Give score=0 to changed masks and score=1 to unchanged masks + # so NMS will prefer ones that didn't need postprocessing + scores.append(float(unchanged)) + + # Recalculate boxes and remove any new duplicates + masks = torch.cat(new_masks, dim=0) + # TODO: This doesn't use the possibly compiled self.batched_mask_to_box + boxes = batched_mask_to_box(masks) + keep_by_nms = batched_nms( + boxes.float(), + torch.as_tensor(scores), + torch.zeros_like(boxes[:, 0]), # categories + iou_threshold=nms_thresh, + ) + + # Only recalculate RLEs for masks that have changed + for i_mask in keep_by_nms: + if scores[i_mask] == 0.0: + mask_torch = masks[i_mask].unsqueeze(0) + mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0] + mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly + mask_data.filter(keep_by_nms) + + return mask_data + + def refine_with_m2m(self, points, point_labels, low_res_masks, points_per_batch): + new_masks = [] + new_iou_preds = [] + + for cur_points, cur_point_labels, low_res_mask in batch_iterator( + points_per_batch, points, point_labels, low_res_masks + ): + best_masks, best_iou_preds, _ = self.predictor._predict( + cur_points[:, None, :], + cur_point_labels[:, None], + mask_input=low_res_mask[:, None, :], + multimask_output=False, + return_logits=True, + ) + new_masks.append(best_masks) + new_iou_preds.append(best_iou_preds) + masks = torch.cat(new_masks, dim=0) + return masks, torch.cat(new_iou_preds, dim=0) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/build_sam.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/build_sam.py new file mode 100644 index 0000000000000000000000000000000000000000..ad0d1fe41cf58a905e69ea19b8f6e21f0933c4cd --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/build_sam.py @@ -0,0 +1,166 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging +import os + +import torch +from hydra import compose +from hydra.utils import instantiate +from omegaconf import OmegaConf + +from torchao._models import sam2 + +# Check if the user is running Python from the parent directory of the sam2 repo +# (i.e. the directory where this repo is cloned into) -- this is not supported since +# it could shadow the sam2 package and cause issues. +if os.path.isdir(os.path.join(sam2.__path__[0], "sam2")): + # If the user has "sam2/sam2" in their path, they are likey importing the repo itself + # as "sam2" rather than importing the "sam2" python package (i.e. "sam2/sam2" directory). + # This typically happens because the user is running Python from the parent directory + # that contains the sam2 repo they cloned. + raise RuntimeError( + "You're likely running Python from the parent directory of the sam2 repository " + "(i.e. the directory where https://github.com/facebookresearch/sam2 is cloned into). " + "This is not supported since the `sam2` Python package could be shadowed by the " + "repository name (the repository is also named `sam2` and contains the Python package " + "in `sam2/sam2`). Please run Python from another directory (e.g. from the repo dir " + "rather than its parent dir, or from your home directory) after installing SAM 2." + ) + + +HF_MODEL_ID_TO_FILENAMES = { + "facebook/sam2-hiera-tiny": ( + "configs/sam2/sam2_hiera_t.yaml", + "sam2_hiera_tiny.pt", + ), + "facebook/sam2-hiera-small": ( + "configs/sam2/sam2_hiera_s.yaml", + "sam2_hiera_small.pt", + ), + "facebook/sam2-hiera-base-plus": ( + "configs/sam2/sam2_hiera_b+.yaml", + "sam2_hiera_base_plus.pt", + ), + "facebook/sam2-hiera-large": ( + "configs/sam2/sam2_hiera_l.yaml", + "sam2_hiera_large.pt", + ), + "facebook/sam2.1-hiera-tiny": ( + "configs/sam2.1/sam2.1_hiera_t.yaml", + "sam2.1_hiera_tiny.pt", + ), + "facebook/sam2.1-hiera-small": ( + "configs/sam2.1/sam2.1_hiera_s.yaml", + "sam2.1_hiera_small.pt", + ), + "facebook/sam2.1-hiera-base-plus": ( + "configs/sam2.1/sam2.1_hiera_b+.yaml", + "sam2.1_hiera_base_plus.pt", + ), + "facebook/sam2.1-hiera-large": ( + "configs/sam2.1/sam2.1_hiera_l.yaml", + "sam2.1_hiera_large.pt", + ), +} + + +def build_sam2( + config_file, + ckpt_path=None, + device="cuda", + mode="eval", + hydra_overrides_extra=[], + apply_postprocessing=True, + **kwargs, +): + if apply_postprocessing: + hydra_overrides_extra = hydra_overrides_extra.copy() + hydra_overrides_extra += [ + # dynamically fall back to multi-mask if the single mask is not stable + "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true", + "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05", + "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98", + ] + # Read config and init model + cfg = compose(config_name=config_file, overrides=hydra_overrides_extra) + OmegaConf.resolve(cfg) + model = instantiate(cfg.model, _recursive_=True) + _load_checkpoint(model, ckpt_path) + model = model.to(device) + if mode == "eval": + model.eval() + return model + + +def build_sam2_video_predictor( + config_file, + ckpt_path=None, + device="cuda", + mode="eval", + hydra_overrides_extra=[], + apply_postprocessing=True, + **kwargs, +): + hydra_overrides = [ + "++model._target_=torchao._models.sam2.sam2_video_predictor.SAM2VideoPredictor", + ] + if apply_postprocessing: + hydra_overrides_extra = hydra_overrides_extra.copy() + hydra_overrides_extra += [ + # dynamically fall back to multi-mask if the single mask is not stable + "++model.sam_mask_decoder_extra_args.dynamic_multimask_via_stability=true", + "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_delta=0.05", + "++model.sam_mask_decoder_extra_args.dynamic_multimask_stability_thresh=0.98", + # 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 + "++model.binarize_mask_from_pts_for_mem_enc=true", + # fill small holes in the low-res masks up to `fill_hole_area` (before resizing them to the original video resolution) + "++model.fill_hole_area=8", + ] + hydra_overrides.extend(hydra_overrides_extra) + + # Read config and init model + cfg = compose(config_name=config_file, overrides=hydra_overrides) + OmegaConf.resolve(cfg) + model = instantiate(cfg.model, _recursive_=True) + _load_checkpoint(model, ckpt_path) + model = model.to(device) + if mode == "eval": + model.eval() + return model + + +def _hf_download(model_id): + from huggingface_hub import hf_hub_download + + config_name, checkpoint_name = HF_MODEL_ID_TO_FILENAMES[model_id] + ckpt_path = hf_hub_download(repo_id=model_id, filename=checkpoint_name) + return config_name, ckpt_path + + +def build_sam2_hf(model_id, **kwargs): + config_name, ckpt_path = _hf_download(model_id) + return build_sam2(config_file=config_name, ckpt_path=ckpt_path, **kwargs) + + +def build_sam2_video_predictor_hf(model_id, **kwargs): + config_name, ckpt_path = _hf_download(model_id) + return build_sam2_video_predictor( + config_file=config_name, ckpt_path=ckpt_path, **kwargs + ) + + +def _load_checkpoint(model, ckpt_path): + if ckpt_path is not None: + sd = torch.load(ckpt_path, map_location="cpu", weights_only=True)["model"] + missing_keys, unexpected_keys = model.load_state_dict(sd) + if missing_keys: + logging.error(missing_keys) + raise RuntimeError() + if unexpected_keys: + logging.error(unexpected_keys) + raise RuntimeError() + logging.info("Loaded checkpoint sucessfully") diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1/sam2.1_hiera_l.yaml b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1/sam2.1_hiera_l.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ba9dafd489ac69fbb45d58b2670c7adabe6f7bd7 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1/sam2.1_hiera_l.yaml @@ -0,0 +1,120 @@ +# @package _global_ + +# Model +model: + _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera + embed_dim: 144 + num_heads: 2 + stages: [2, 6, 36, 4] + global_att_blocks: [23, 33, 43] + window_pos_embed_bkg_spatial_size: [7, 7] + window_spec: [8, 4, 16, 8] + neck: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [1152, 576, 288, 144] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: torchao._models.sam2.modeling.memory_encoder.Fuser + layer: + _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: true + proj_tpos_enc_in_obj_ptrs: true + use_signed_tpos_enc_to_obj_ptrs: true + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1/sam2.1_hiera_t.yaml b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1/sam2.1_hiera_t.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c6318f843b2b9452389b36c42e8bd43a6efc1ee1 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/configs/sam2.1/sam2.1_hiera_t.yaml @@ -0,0 +1,121 @@ +# @package _global_ + +# Model +model: + _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera + embed_dim: 96 + num_heads: 1 + stages: [1, 2, 7, 2] + global_att_blocks: [5, 7, 9] + window_pos_embed_bkg_spatial_size: [7, 7] + neck: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [768, 384, 192, 96] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: torchao._models.sam2.modeling.memory_encoder.Fuser + layer: + _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + # SAM decoder + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: true + proj_tpos_enc_in_obj_ptrs: true + use_signed_tpos_enc_to_obj_ptrs: true + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + # HieraT does not currently support compilation, should always be set to False + compile_image_encoder: False diff --git a/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 b/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 new file mode 100644 index 0000000000000000000000000000000000000000..204679146854110ce8a59e9adc462a6688e56d30 --- /dev/null +++ b/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 @@ -0,0 +1,339 @@ +# @package _global_ + +scratch: + resolution: 1024 + train_batch_size: 1 + num_train_workers: 10 + num_frames: 8 + max_num_objects: 3 + base_lr: 5.0e-6 + vision_lr: 3.0e-06 + phases_per_epoch: 1 + num_epochs: 40 + +dataset: + # PATHS to Dataset + img_folder: null # PATH to MOSE JPEGImages folder + gt_folder: null # PATH to MOSE Annotations folder + file_list_txt: training/assets/MOSE_sample_train_list.txt # Optional PATH to filelist containing a subset of videos to be used for training + multiplier: 2 + +# Video transforms +vos: + train_transforms: + - _target_: training.dataset.transforms.ComposeAPI + transforms: + - _target_: training.dataset.transforms.RandomHorizontalFlip + consistent_transform: True + - _target_: training.dataset.transforms.RandomAffine + degrees: 25 + shear: 20 + image_interpolation: bilinear + consistent_transform: True + - _target_: training.dataset.transforms.RandomResizeAPI + sizes: ${scratch.resolution} + square: true + consistent_transform: True + - _target_: training.dataset.transforms.ColorJitter + consistent_transform: True + brightness: 0.1 + contrast: 0.03 + saturation: 0.03 + hue: null + - _target_: training.dataset.transforms.RandomGrayscale + p: 0.05 + consistent_transform: True + - _target_: training.dataset.transforms.ColorJitter + consistent_transform: False + brightness: 0.1 + contrast: 0.05 + saturation: 0.05 + hue: null + - _target_: training.dataset.transforms.ToTensorAPI + - _target_: training.dataset.transforms.NormalizeAPI + mean: [0.485, 0.456, 0.406] + std: [0.229, 0.224, 0.225] + +trainer: + _target_: training.trainer.Trainer + mode: train_only + max_epochs: ${times:${scratch.num_epochs},${scratch.phases_per_epoch}} + accelerator: cuda + seed_value: 123 + + model: + _target_: training.model.sam2.SAM2Train + image_encoder: + _target_: sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: sam2.modeling.backbones.hieradet.Hiera + embed_dim: 112 + num_heads: 2 + drop_path_rate: 0.1 + neck: + _target_: sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [896, 448, 224, 112] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: sam2.modeling.memory_encoder.Fuser + layer: + _target_: sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: ${scratch.resolution} + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + no_obj_embed_spatial: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: true + proj_tpos_enc_in_obj_ptrs: true + use_signed_tpos_enc_to_obj_ptrs: true + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + # compile_image_encoder: False + + ####### Training specific params ####### + # box/point input and corrections + prob_to_use_pt_input_for_train: 0.5 + prob_to_use_pt_input_for_eval: 0.0 + prob_to_use_box_input_for_train: 0.5 # 0.5*0.5 = 0.25 prob to use box instead of points + prob_to_use_box_input_for_eval: 0.0 + prob_to_sample_from_gt_for_train: 0.1 # with a small prob, sampling correction points from GT mask instead of prediction errors + num_frames_to_correct_for_train: 2 # iteratively sample on random 1~2 frames (always include the first frame) + num_frames_to_correct_for_eval: 1 # only iteratively sample on first frame + rand_frames_to_correct_for_train: True # random #init-cond-frame ~ 2 + 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) + # maximum 2 initial conditioning frames + num_init_cond_frames_for_train: 2 + rand_init_cond_frames_for_train: True # random 1~2 + num_correction_pt_per_frame: 7 + use_act_ckpt_iterative_pt_sampling: false + + + + num_init_cond_frames_for_eval: 1 # only mask on the first frame + forward_backbone_per_frame_for_eval: True + + + data: + train: + _target_: training.dataset.sam2_datasets.TorchTrainMixedDataset + phases_per_epoch: ${scratch.phases_per_epoch} + batch_sizes: + - ${scratch.train_batch_size} + + datasets: + - _target_: training.dataset.utils.RepeatFactorWrapper + dataset: + _target_: training.dataset.utils.ConcatDataset + datasets: + - _target_: training.dataset.vos_dataset.VOSDataset + transforms: ${vos.train_transforms} + training: true + video_dataset: + _target_: training.dataset.vos_raw_dataset.PNGRawDataset + img_folder: ${dataset.img_folder} + gt_folder: ${dataset.gt_folder} + file_list_txt: ${dataset.file_list_txt} + sampler: + _target_: training.dataset.vos_sampler.RandomUniformSampler + num_frames: ${scratch.num_frames} + max_num_objects: ${scratch.max_num_objects} + multiplier: ${dataset.multiplier} + shuffle: True + num_workers: ${scratch.num_train_workers} + pin_memory: True + drop_last: True + collate_fn: + _target_: training.utils.data_utils.collate_fn + _partial_: true + dict_key: all + + optim: + amp: + enabled: True + amp_dtype: bfloat16 + + optimizer: + _target_: torch.optim.AdamW + + gradient_clip: + _target_: training.optimizer.GradientClipper + max_norm: 0.1 + norm_type: 2 + + param_group_modifiers: + - _target_: training.optimizer.layer_decay_param_modifier + _partial_: True + layer_decay_value: 0.9 + apply_to: 'image_encoder.trunk' + overrides: + - pattern: '*pos_embed*' + value: 1.0 + + options: + lr: + - scheduler: + _target_: fvcore.common.param_scheduler.CosineParamScheduler + start_value: ${scratch.base_lr} + end_value: ${divide:${scratch.base_lr},10} + - scheduler: + _target_: fvcore.common.param_scheduler.CosineParamScheduler + start_value: ${scratch.vision_lr} + end_value: ${divide:${scratch.vision_lr},10} + param_names: + - 'image_encoder.*' + weight_decay: + - scheduler: + _target_: fvcore.common.param_scheduler.ConstantParamScheduler + value: 0.1 + - scheduler: + _target_: fvcore.common.param_scheduler.ConstantParamScheduler + value: 0.0 + param_names: + - '*bias*' + module_cls_names: ['torch.nn.LayerNorm'] + + loss: + all: + _target_: training.loss_fns.MultiStepMultiMasksAndIous + weight_dict: + loss_mask: 20 + loss_dice: 1 + loss_iou: 1 + loss_class: 1 + supervise_all_iou: true + iou_use_l1_loss: true + pred_obj_scores: true + focal_gamma_obj_score: 0.0 + focal_alpha_obj_score: -1.0 + + distributed: + backend: nccl + find_unused_parameters: True + + logging: + tensorboard_writer: + _target_: training.utils.logger.make_tensorboard_logger + log_dir: ${launcher.experiment_log_dir}/tensorboard + flush_secs: 120 + should_log: True + log_dir: ${launcher.experiment_log_dir}/logs + log_freq: 10 + + # initialize from a SAM 2 checkpoint + checkpoint: + save_dir: ${launcher.experiment_log_dir}/checkpoints + save_freq: 0 # 0 only last checkpoint is saved. + model_weight_initializer: + _partial_: True + _target_: training.utils.checkpoint_utils.load_state_dict_into_model + strict: True + ignore_unexpected_keys: null + ignore_missing_keys: null + + state_dict: + _target_: training.utils.checkpoint_utils.load_checkpoint_and_apply_kernels + checkpoint_path: ./checkpoints/sam2.1_hiera_base_plus.pt # PATH to SAM 2.1 checkpoint + ckpt_state_dict_keys: ['model'] + +launcher: + num_nodes: 1 + gpus_per_node: 8 + experiment_log_dir: null # Path to log directory, defaults to ./sam2_logs/${config_name} + +# SLURM args if running on a cluster +submitit: + partition: null + account: null + qos: null + cpus_per_task: 10 + use_cluster: false + timeout_hour: 24 + name: null + port_range: [10000, 65000] + diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/csrc/connected_components.cu b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/csrc/connected_components.cu new file mode 100644 index 0000000000000000000000000000000000000000..ced21eb32eaaadb818d441c1322b99d1bf068f45 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/csrc/connected_components.cu @@ -0,0 +1,289 @@ +// Copyright (c) Meta Platforms, Inc. and affiliates. +// All rights reserved. + +// This source code is licensed under the license found in the +// LICENSE file in the root directory of this source tree. + +// adapted from https://github.com/zsef123/Connected_components_PyTorch +// with license found in the LICENSE_cctorch file in the root directory. +#include +#include +#include +#include +#include +#include + +// 2d +#define BLOCK_ROWS 16 +#define BLOCK_COLS 16 + +namespace cc2d { + +template +__device__ __forceinline__ unsigned char hasBit(T bitmap, unsigned char pos) { + return (bitmap >> pos) & 1; +} + +__device__ int32_t find(const int32_t* s_buf, int32_t n) { + while (s_buf[n] != n) + n = s_buf[n]; + return n; +} + +__device__ int32_t find_n_compress(int32_t* s_buf, int32_t n) { + const int32_t id = n; + while (s_buf[n] != n) { + n = s_buf[n]; + s_buf[id] = n; + } + return n; +} + +__device__ void union_(int32_t* s_buf, int32_t a, int32_t b) { + bool done; + do { + a = find(s_buf, a); + b = find(s_buf, b); + + if (a < b) { + int32_t old = atomicMin(s_buf + b, a); + done = (old == b); + b = old; + } else if (b < a) { + int32_t old = atomicMin(s_buf + a, b); + done = (old == a); + a = old; + } else + done = true; + + } while (!done); +} + +__global__ void +init_labeling(int32_t* label, const uint32_t W, const uint32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2; + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2; + const uint32_t idx = row * W + col; + + if (row < H && col < W) + label[idx] = idx; +} + +__global__ void +merge(uint8_t* img, int32_t* label, const uint32_t W, const uint32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2; + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2; + const uint32_t idx = row * W + col; + + if (row >= H || col >= W) + return; + + uint32_t P = 0; + + if (img[idx]) + P |= 0x777; + if (row + 1 < H && img[idx + W]) + P |= 0x777 << 4; + if (col + 1 < W && img[idx + 1]) + P |= 0x777 << 1; + + if (col == 0) + P &= 0xEEEE; + if (col + 1 >= W) + P &= 0x3333; + else if (col + 2 >= W) + P &= 0x7777; + + if (row == 0) + P &= 0xFFF0; + if (row + 1 >= H) + P &= 0xFF; + + if (P > 0) { + // If need check about top-left pixel(if flag the first bit) and hit the + // top-left pixel + if (hasBit(P, 0) && img[idx - W - 1]) { + union_(label, idx, idx - 2 * W - 2); // top left block + } + + if ((hasBit(P, 1) && img[idx - W]) || (hasBit(P, 2) && img[idx - W + 1])) + union_(label, idx, idx - 2 * W); // top bottom block + + if (hasBit(P, 3) && img[idx + 2 - W]) + union_(label, idx, idx - 2 * W + 2); // top right block + + if ((hasBit(P, 4) && img[idx - 1]) || (hasBit(P, 8) && img[idx + W - 1])) + union_(label, idx, idx - 2); // just left block + } +} + +__global__ void compression(int32_t* label, const int32_t W, const int32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2; + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2; + const uint32_t idx = row * W + col; + + if (row < H && col < W) + find_n_compress(label, idx); +} + +__global__ void final_labeling( + const uint8_t* img, + int32_t* label, + const int32_t W, + const int32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y) * 2; + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x) * 2; + const uint32_t idx = row * W + col; + + if (row >= H || col >= W) + return; + + int32_t y = label[idx] + 1; + + if (img[idx]) + label[idx] = y; + else + label[idx] = 0; + + if (col + 1 < W) { + if (img[idx + 1]) + label[idx + 1] = y; + else + label[idx + 1] = 0; + + if (row + 1 < H) { + if (img[idx + W + 1]) + label[idx + W + 1] = y; + else + label[idx + W + 1] = 0; + } + } + + if (row + 1 < H) { + if (img[idx + W]) + label[idx + W] = y; + else + label[idx + W] = 0; + } +} + +__global__ void init_counting( + const int32_t* label, + int32_t* count_init, + const int32_t W, + const int32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y); + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x); + const uint32_t idx = row * W + col; + + if (row >= H || col >= W) + return; + + int32_t y = label[idx]; + if (y > 0) { + int32_t count_idx = y - 1; + atomicAdd(count_init + count_idx, 1); + } +} + +__global__ void final_counting( + const int32_t* label, + const int32_t* count_init, + int32_t* count_final, + const int32_t W, + const int32_t H) { + const uint32_t row = (blockIdx.y * blockDim.y + threadIdx.y); + const uint32_t col = (blockIdx.x * blockDim.x + threadIdx.x); + const uint32_t idx = row * W + col; + + if (row >= H || col >= W) + return; + + int32_t y = label[idx]; + if (y > 0) { + int32_t count_idx = y - 1; + count_final[idx] = count_init[count_idx]; + } else { + count_final[idx] = 0; + } +} + +} // namespace cc2d + +std::vector get_connected_componnets( + const torch::Tensor& inputs) { + AT_ASSERTM(inputs.is_cuda(), "inputs must be a CUDA tensor"); + AT_ASSERTM(inputs.ndimension() == 4, "inputs must be [N, 1, H, W] shape"); + AT_ASSERTM( + inputs.scalar_type() == torch::kUInt8, "inputs must be a uint8 type"); + + const uint32_t N = inputs.size(0); + const uint32_t C = inputs.size(1); + const uint32_t H = inputs.size(2); + const uint32_t W = inputs.size(3); + + AT_ASSERTM(C == 1, "inputs must be [N, 1, H, W] shape"); + AT_ASSERTM((H % 2) == 0, "height must be an even number"); + AT_ASSERTM((W % 2) == 0, "width must be an even number"); + + // label must be uint32_t + auto label_options = + torch::TensorOptions().dtype(torch::kInt32).device(inputs.device()); + torch::Tensor labels = torch::zeros({N, C, H, W}, label_options); + torch::Tensor counts_init = torch::zeros({N, C, H, W}, label_options); + torch::Tensor counts_final = torch::zeros({N, C, H, W}, label_options); + + dim3 grid = dim3( + ((W + 1) / 2 + BLOCK_COLS - 1) / BLOCK_COLS, + ((H + 1) / 2 + BLOCK_ROWS - 1) / BLOCK_ROWS); + dim3 block = dim3(BLOCK_COLS, BLOCK_ROWS); + dim3 grid_count = + dim3((W + BLOCK_COLS) / BLOCK_COLS, (H + BLOCK_ROWS) / BLOCK_ROWS); + dim3 block_count = dim3(BLOCK_COLS, BLOCK_ROWS); + cudaStream_t stream = at::cuda::getCurrentCUDAStream(); + + for (int n = 0; n < N; n++) { + uint32_t offset = n * H * W; + + cc2d::init_labeling<<>>( + labels.data_ptr() + offset, W, H); + cc2d::merge<<>>( + inputs.data_ptr() + offset, + labels.data_ptr() + offset, + W, + H); + cc2d::compression<<>>( + labels.data_ptr() + offset, W, H); + cc2d::final_labeling<<>>( + inputs.data_ptr() + offset, + labels.data_ptr() + offset, + W, + H); + + // get the counting of each pixel + cc2d::init_counting<<>>( + labels.data_ptr() + offset, + counts_init.data_ptr() + offset, + W, + H); + cc2d::final_counting<<>>( + labels.data_ptr() + offset, + counts_init.data_ptr() + offset, + counts_final.data_ptr() + offset, + W, + H); + } + + // returned values are [labels, counts] + std::vector outputs; + outputs.push_back(labels); + outputs.push_back(counts_final); + return outputs; +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def( + "get_connected_componnets", + &get_connected_componnets, + "get_connected_componnets"); +} diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/map_tensor.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/map_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..0310e7f8b64bf7122f6a6e9b92d71f2bf1906d81 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/map_tensor.py @@ -0,0 +1,781 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import contextlib +import functools +from typing import Dict + +import torch +from torch.nested._internal.nested_tensor import nested_view_from_values_offsets +from torch.utils._pytree import tree_map + +MAP_TENSOR_ATEN_OP_TABLE = {} + + +def implements(aten_ops_or_torch_fns): + if not isinstance(aten_ops_or_torch_fns, (list, tuple)): + aten_ops_or_torch_fns = [aten_ops_or_torch_fns] + + def decorator(func): + for op in aten_ops_or_torch_fns: + + @functools.wraps(op) + def wrapper(f, types, args, kwargs): + return func(f, types, args, kwargs) + + MAP_TENSOR_ATEN_OP_TABLE[op] = wrapper + return func + + return decorator + + +@contextlib.contextmanager +def no_dispatch(): + guard = torch._C._DisableTorchDispatch() + try: + yield + finally: + del guard + + +def wrap_dim(i, dim): + if i < 0: + return dim + i + return i + + +def unwrap(t): + if isinstance(t, MapTensor): + with no_dispatch(): + return t.elems + else: + return t + + +def unwrap_i(t, i): + if isinstance(t, MapTensor): + with no_dispatch(): + return t.elems[i] + else: + return t + + +def unwrap_fn(t, fn): + if isinstance(t, MapTensor): + with no_dispatch(): + return fn(t.elems) + else: + return None + + +def wrap(t): + if isinstance(t, torch.Tensor): + return MapTensor(t) + else: + return t + + +@implements(torch.ops.aten.native_layer_norm.default) +def layer_norm_impl(func, types, args, kwargs=None): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 5, f"args: {unwrapped_args}" + norm_res = func(*unwrapped_args) + assert len(norm_res) == 3 + return tuple(wrap(a) for a in norm_res) + + +@implements(torch.ops.aten.add.Tensor) +def add_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 2, f"args: {unwrapped_args}" + if not isinstance(args[0], MapTensor) and isinstance(args[1], MapTensor): + if args[0].dim() == (args[1].dim() + 1): + return NotImplemented + return NotImplemented + return wrap(func(*unwrapped_args, **unwrapped_kwargs)) + + +@implements([torch.ops.aten.cat.default, torch.ops.aten.stack.default]) +def cat_ops_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) <= 2, f"args: {unwrapped_args}" + # TODO: Use MapTensor type for filter + # First argument's dim + dim = unwrapped_args[0][0].dim() + size = unwrapped_args[0][0].size() + for a in unwrapped_args[0]: + if a.dim() > dim: + dim = a.dim() + size = a.size() + new_args = [] + for a in unwrapped_args[0]: + if a.dim() == dim: + new_args.append(a) + else: + assert a.dim() + 1 == dim + new_args.append(a.unsqueeze(0).expand((size[0],) + a.size())) + orig_dim = unwrapped_args[1] if len(unwrapped_args) == 2 else 0 + return wrap(func(new_args, wrap_dim(orig_dim, dim - 1) + 1)) + + +@implements(torch.ops.aten.select.int) +def select_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 3, f"args: {unwrapped_args}" + return wrap(func(unwrapped_args[0], unwrapped_args[1] + 1, unwrapped_args[2])) + + +@implements(torch.ops.aten.slice.Tensor) +def slice_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 4, f"args: {unwrapped_args}" + dim = unwrapped_args[0].dim() + return wrap( + func( + unwrapped_args[0], + wrap_dim(unwrapped_args[1], dim - 1) + 1, + unwrapped_args[2], + unwrapped_args[3], + ) + ) + + +@implements( + [ + torch.ops.aten.mean.dim, + torch.ops.aten.max.dim, + torch.ops.aten.argmax.default, + torch.ops.aten.min.dim, + torch.ops.aten.any.dim, + torch.ops.aten.amax.default, + torch.ops.aten.amin.default, + torch.ops.aten.all.default, + torch.ops.aten.sum.dim_IntList, + ] +) +def reductions_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + # TODO: THIS MIGHT BE WRONG + if len(unwrapped_args) == 3 and len(unwrapped_kwargs) == 0: + assert len(unwrapped_args[1]) == 1 + dim = unwrapped_args[0].dim() + return wrap( + func( + unwrapped_args[0], + [wrap_dim(u, dim - 1) + 1 for u in unwrapped_args[1]], + unwrapped_args[2], + ) + ) + if len(unwrapped_args) == 2 and len(unwrapped_kwargs) == 1: + assert len(unwrapped_args[1]) == 1 + dim = unwrapped_args[0].dim() + return wrap( + func( + unwrapped_args[0], + [wrap_dim(u, dim - 1) + 1 for u in unwrapped_args[1]], + **unwrapped_kwargs, + ) + ) + if ( + len(unwrapped_args) == 2 + and len(unwrapped_kwargs) == 0 + and type(unwrapped_args[1]) == list + ): + assert len(unwrapped_args[1]) == 1 + dim = unwrapped_args[0].dim() + return wrap( + func( + unwrapped_args[0], [wrap_dim(u, dim - 1) + 1 for u in unwrapped_args[1]] + ) + ) + if ( + len(unwrapped_args) == 2 + and len(unwrapped_kwargs) == 0 + and type(unwrapped_args[1]) == int + ): + dim = unwrapped_args[0].dim() + return wrap(func(unwrapped_args[0], wrap_dim(unwrapped_args[1], dim - 1) + 1)) + if len(args) == 1 and len(kwargs) == 0: + return wrap(func(unwrapped_args[0])) + return NotImplemented + + +@implements([torch.ops.aten._unsafe_view.default, torch.ops.aten.expand.default]) +def view_ops_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 2, f"args: {unwrapped_args}" + input_size = unwrapped_args[0].size() + bigger_size = list(input_size[:1]) + unwrapped_args[1] + return wrap(func(unwrapped_args[0], bigger_size)) + + +@implements(torch.ops.aten.view.default) +def view_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 2, f"args: {unwrapped_args}" + input_size = unwrapped_args[0].size() + bigger_size = list(input_size[:1]) + unwrapped_args[1] + if unwrapped_args[0].size() == tuple(bigger_size): + return wrap(args[0].elems) + return wrap(unwrapped_args[0].reshape(bigger_size)) + + +@implements([torch.ops.aten.mm.default, torch.ops.aten.bmm.default]) +def mm_ops_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 2, f"args: {unwrapped_args}" + return wrap(torch.matmul(*unwrapped_args)) + + +@implements(torch.ops.aten.unsqueeze.default) +def unsqueeze_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 2, f"args: {unwrapped_args}" + new_i = unwrapped_args[1] + if new_i >= 0: + new_i += 1 + return wrap(func(unwrapped_args[0], new_i)) + + +@implements(torch.ops.aten.squeeze.dim) +def squeeze_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 2, f"args: {unwrapped_args}" + new_i = unwrapped_args[1] + if new_i >= 0: + new_i += 1 + return wrap(func(unwrapped_args[0], new_i)) + + +@implements(torch.ops.aten.addmm.default) +def addmm_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 3, f"args: {unwrapped_args}" + return wrap(torch.matmul(unwrapped_args[1], unwrapped_args[2]) + unwrapped_args[0]) + + +@implements(torch.ops.aten.convolution.default) +def convolution_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 9, f"args: {unwrapped_args}" + a = unwrapped_args[0] + a = unwrapped_args[0].flatten(0, 1) + # TODO: It's scary that this .contiguous seems necessary, but I we're below composite conv + # which might expected contiguous output + resa = func(*((a,) + unwrapped_args[1:])).contiguous() + resb = resa.view( + (unwrapped_args[0].size(0), unwrapped_args[0].size(1)) + resa.size()[1:] + ) + return wrap(resb) + + +@implements(torch.ops.aten.upsample_bilinear2d.default) +def upsample_bilinear2d_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 3, f"args: {unwrapped_args}" + a = unwrapped_args[0] + a = unwrapped_args[0].flatten(0, 1) + # NOTE: It's scary that this .contiguous seems necessary, but we're below composite upsample + # which might expected contiguous output + resa = func(*((a,) + unwrapped_args[1:])).contiguous() + resb = resa.view( + (unwrapped_args[0].size(0), unwrapped_args[0].size(1)) + resa.size()[1:] + ) + return wrap(resb) + + +@implements(torch.ops.aten.transpose.int) +def transpose_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 3, f"args: {unwrapped_args}" + dim = unwrapped_args[0].dim() + return wrap( + func( + unwrapped_args[0], + wrap_dim(unwrapped_args[1], dim - 1) + 1, + wrap_dim(unwrapped_args[2], dim - 1) + 1, + ) + ) + + +@implements(torch.ops.aten.unbind.int) +def unbind_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 2, f"args: {unwrapped_args}" + dim = unwrapped_args[0].dim() + return wrap(func(unwrapped_args[0], wrap_dim(unwrapped_args[1], dim - 1) + 1)) + + +@implements(torch.ops.aten.permute.default) +def permute_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 2, f"args: {unwrapped_args}" + dim = unwrapped_args[0].dim() + return wrap( + func( + unwrapped_args[0], + ([0] + [wrap_dim(u, dim - 1) + 1 for u in unwrapped_args[1]]), + ) + ) + + +@implements(torch.ops.aten._scaled_dot_product_efficient_attention.default) +def _scaled_dot_product_efficient_attention_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(args) == 5 + if all(isinstance(a, MapTensor) for a in args[:3]): + # assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 5, f"args: {unwrapped_args}" + assert unwrapped_args[0].dim() == 5 + assert unwrapped_args[1].dim() == 5 + assert unwrapped_args[2].dim() == 5 + sdpa_res = wrap( + func( + unwrapped_args[0].flatten(0, 1), + unwrapped_args[1].flatten(0, 1), + unwrapped_args[2].flatten(0, 1), + unwrapped_args[3], + unwrapped_args[4], + **unwrapped_kwargs, + ) + ) + return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:] + if isinstance(args[0], MapTensor) and not any( + isinstance(a, MapTensor) for a in args[1:] + ): + # assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 5, f"args: {unwrapped_args}" + assert unwrapped_args[0].dim() == 5 + assert unwrapped_args[1].dim() == 4 + assert unwrapped_args[2].dim() == 4 + a0 = unwrapped_args[0] + a1_size = unwrapped_args[1].size() + a1 = unwrapped_args[1].unsqueeze(0).expand((a0.size(0),) + a1_size) + a2 = unwrapped_args[2].unsqueeze(0).expand((a0.size(0),) + a1_size) + sdpa_res = wrap( + func( + a0.flatten(0, 1), + a1.flatten(0, 1), + a2.flatten(0, 1), + unwrapped_args[3], + unwrapped_args[4], + **unwrapped_kwargs, + ) + ) + return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:] + if ( + (not isinstance(args[0], MapTensor)) + and isinstance(args[1], MapTensor) + and (not isinstance(args[2], MapTensor)) + ): + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 5, f"args: {unwrapped_args}" + assert unwrapped_args[0].dim() == 4 + assert unwrapped_args[1].dim() == 5 + assert unwrapped_args[2].dim() == 4 + a1_size = unwrapped_args[1].size() + a0 = ( + unwrapped_args[0] + .unsqueeze(0) + .expand((a1_size[0],) + unwrapped_args[0].size()[1:]) + ) + a2 = ( + unwrapped_args[2] + .unsqueeze(0) + .expand((a1_size[0],) + unwrapped_args[2].size()[1:]) + ) + sdpa_res = wrap( + func( + a0.flatten(0, 1), + a1.flatten(0, 1), + a2.flatten(0, 1), + unwrapped_args[3], + unwrapped_args[4], + ) + ) + return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:] + if ( + (not isinstance(args[0], MapTensor)) + and isinstance(args[1], MapTensor) + and isinstance(args[2], MapTensor) + ): + # assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 5, f"args: {unwrapped_args}" + assert unwrapped_args[0].dim() == 4 + assert unwrapped_args[1].dim() == 5 + assert unwrapped_args[2].dim() == 5 + a0_size = unwrapped_args[0].size() + a1_size = unwrapped_args[1].size() + a0 = unwrapped_args[0].unsqueeze(0).expand((a1_size[0],) + a0_size) + a1 = unwrapped_args[1] + a2 = unwrapped_args[2] + sdpa_res = wrap( + func( + a0.flatten(0, 1), + a1.flatten(0, 1), + a2.flatten(0, 1), + unwrapped_args[3], + unwrapped_args[4], + **unwrapped_kwargs, + ) + ) + return (wrap(sdpa_res[0].view((a1_size[0],) + a0_size)),) + sdpa_res[1:] + return NotImplemented + + +@implements(torch.ops.aten._scaled_dot_product_flash_attention.default) +def _scaled_dot_product_flash_attention_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(args) == 3 + assert len(unwrapped_kwargs) == 1 + assert len(unwrapped_args) == 3, f"args: {unwrapped_args}" + if all(isinstance(a, MapTensor) for a in args[:3]): + assert unwrapped_args[0].dim() == 5 + assert unwrapped_args[1].dim() == 5 + assert unwrapped_args[2].dim() == 5 + sdpa_res = wrap( + func( + unwrapped_args[0].flatten(0, 1), + unwrapped_args[1].flatten(0, 1), + unwrapped_args[2].flatten(0, 1), + **unwrapped_kwargs, + ) + ) + return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:] + if isinstance(args[0], MapTensor) and not any( + isinstance(a, MapTensor) for a in args[1:] + ): + assert unwrapped_args[0].dim() == 5 + assert unwrapped_args[1].dim() == 4 + assert unwrapped_args[2].dim() == 4 + a0 = unwrapped_args[0] + a1_size = unwrapped_args[1].size() + a1 = unwrapped_args[1].unsqueeze(0).expand((a0.size(0),) + a1_size) + a2 = unwrapped_args[2].unsqueeze(0).expand((a0.size(0),) + a1_size) + sdpa_res = wrap( + func( + a0.flatten(0, 1), a1.flatten(0, 1), a2.flatten(0, 1), **unwrapped_kwargs + ) + ) + return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:] + if ( + (not isinstance(args[0], MapTensor)) + and isinstance(args[1], MapTensor) + and (not isinstance(args[2], MapTensor)) + ): + assert unwrapped_args[0].dim() == 4 + assert unwrapped_args[1].dim() == 5 + assert unwrapped_args[2].dim() == 4 + a1_size = unwrapped_args[1].size() + a0 = ( + unwrapped_args[0] + .unsqueeze(0) + .expand((a1_size[0],) + unwrapped_args[0].size()[1:]) + ) + a2 = ( + unwrapped_args[2] + .unsqueeze(0) + .expand((a1_size[0],) + unwrapped_args[2].size()[1:]) + ) + sdpa_res = wrap( + func( + a0.flatten(0, 1), a1.flatten(0, 1), a2.flatten(0, 1), **unwrapped_kwargs + ) + ) + return (wrap(sdpa_res[0].view(unwrapped_args[0].size())),) + sdpa_res[1:] + if ( + (not isinstance(args[0], MapTensor)) + and isinstance(args[1], MapTensor) + and isinstance(args[2], MapTensor) + ): + assert unwrapped_args[0].dim() == 4 + assert unwrapped_args[1].dim() == 5 + assert unwrapped_args[2].dim() == 5 + a0_size = unwrapped_args[0].size() + a1_size = unwrapped_args[1].size() + a0 = unwrapped_args[0].unsqueeze(0).expand((a1_size[0],) + a0_size) + a1 = unwrapped_args[1] + a2 = unwrapped_args[2] + sdpa_res = wrap( + func( + a0.flatten(0, 1), a1.flatten(0, 1), a2.flatten(0, 1), **unwrapped_kwargs + ) + ) + return (wrap(sdpa_res[0].view((a1_size[0],) + a0_size)),) + sdpa_res[1:] + return NotImplemented + + +# torch.ops.aten._unsafe_index.Tensor is only needed by inductor for compile +@implements([torch.ops.aten._unsafe_index.Tensor, torch.ops.aten.index.Tensor]) +def index_ops_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + assert len(unwrapped_kwargs) == 0 + assert len(unwrapped_args) == 2, f"args: {unwrapped_args}" + # if len(args[1]) == 1 and isinstance(args[1][0], MapTensor) and isinstance(args[0], MapTensor): + # return wrap(func(*unwrapped_args)) + if ( + len(args[1]) == 1 + and isinstance(args[1][0], MapTensor) + and not isinstance(args[0], MapTensor) + ): + tensors = [ + func(args[0], [args[1][0].elems[i]]) for i in range(len(args[1][0].elems)) + ] + values = torch.cat(tensors) + lengths = torch.tensor([0] + [t.size(0) for t in tensors], pin_memory=True).to( + values.device, non_blocking=True + ) + offsets = torch.cumsum(lengths, dim=0) + nt = nested_view_from_values_offsets(values, offsets) + assert nt.layout == torch.jagged + return wrap(nt) + if ( + isinstance(args[0], MapTensor) + and not isinstance(args[1][0], MapTensor) + and len(args[1]) == 1 + ): + return wrap(func(args[0].elems, [args[1][0].unsqueeze(0)])) + if ( + isinstance(args[0], MapTensor) + and not isinstance(args[1][0], MapTensor) + and isinstance(args[1][1], MapTensor) + and len(args[1]) == 2 + ): + res = [] + for a0, a11 in zip(args[0].elems.unbind(), args[1][1].elems.unbind()): + res.append(func(a0, [args[1][0], a11])) + return wrap(torch.stack(res)) + if ( + isinstance(args[0], MapTensor) + and isinstance(args[1][0], MapTensor) + and len(args[1]) == 1 + ): + tensors = [ + func(args[0].elems[i], [args[1][0].elems[i]]) + for i in range(len(args[0].elems)) + ] + values = torch.cat(tensors) + lengths = torch.tensor([0] + [t.size(0) for t in tensors], pin_memory=True).to( + values.device, non_blocking=True + ) + offsets = torch.cumsum(lengths, dim=0) + nt = nested_view_from_values_offsets(values, offsets) + assert nt.layout == torch.jagged + return wrap(nt) + a = unwrapped_args[0] + a = unwrapped_args[0].flatten(0, 1) + resa = func(a, args[1]) + resb = resa.view( + (unwrapped_args[0].size(0), unwrapped_args[0].size(1)) + resa.size()[1:] + ) + return wrap(resb) + + +# Prims +@implements(torch.ops.aten.dim.default) +def dim_impl(func, types, args, kwargs): + assert len(args) == 1 + assert len(kwargs) == 0 + ret_dim = func(args[0].elems) - 1 + assert ret_dim >= 0 + return ret_dim + + +@implements(torch.ops.aten.sym_size.default) +def sym_impl(func, types, args, kwargs): + assert len(args) == 1 + assert len(kwargs) == 0 + elems_size = func(args[0].elems) + assert len(elems_size) > 0 + return elems_size[1:] + + +@implements(torch.ops.aten.is_contiguous.default) +def is_contiguous_impl(func, types, args, kwargs): + assert len(args) == 1 + assert len(kwargs) == 0 + return func(args[0].elems) + + +@implements( + [ + torch.ops.aten.clamp.default, + torch.ops.aten.clone.default, + torch.ops.aten.cos.default, + torch.ops.aten.div.Tensor, + torch.ops.aten.eq.Scalar, + torch.ops.aten.gelu.default, + torch.ops.aten.mul.Tensor, + torch.ops.aten.pow.Tensor_Scalar, + torch.ops.aten.relu.default, + torch.ops.aten.sigmoid.default, + torch.ops.aten.sin.default, + torch.ops.aten.sqrt.default, + torch.ops.aten.sub.Tensor, + torch.ops.aten.unbind.int, + torch.ops.aten.where.self, + torch.ops.aten.zeros_like.default, + torch.ops.aten._to_copy.default, + torch.ops.aten.gt.Scalar, + torch.ops.aten.ge.Scalar, + torch.ops.aten.bitwise_not.default, + torch.ops.aten.lt.Tensor, + torch.ops.aten.bitwise_or.Tensor, + torch.ops.aten.eq.Tensor, + torch.ops.aten.abs.default, + torch.ops.aten.ne.Scalar, + torch.ops.aten.le.Tensor, + torch.ops.aten.view_as_complex.default, + torch.ops.aten.view_as_real.default, + torch.ops.aten.neg.default, + torch.ops.aten.le.Scalar, + torch.ops.aten.rsub.Scalar, + # Sketchy new in place ops + torch.ops.aten.bitwise_and_.Tensor, + torch.ops.aten.bitwise_or_.Tensor, + torch.ops.aten.le.Tensor, + torch.ops.aten.logical_and.default, + # in place ops + torch.ops.aten.add_.Tensor, + torch.ops.aten.copy_.default, + # Prims + torch.ops.prim.layout.default, + ] +) +def forwardables_impl(func, types, args, kwargs): + unwrapped_args = tree_map(unwrap, args) + unwrapped_kwargs = tree_map(unwrap, kwargs) + return wrap(func(*unwrapped_args, **unwrapped_kwargs)) + + +def run_invariant_test(res, func, args, kwargs): + # Compares 0th element of list of results with + # func applied to 0th arg and kwarg. + # Rough test to maintain per-op accuracy. + if isinstance(res, torch.Tensor): + unwrapped_args_0 = tree_map(lambda x: unwrap_i(x, 0), args) + unwrapped_kwargs_0 = tree_map(lambda x: unwrap_i(x, 0), kwargs) + if func == torch.ops.aten.view.default: + res_0 = torch.ops.aten.reshape.default( + *unwrapped_args_0, **unwrapped_kwargs_0 + ) + else: + res_0 = func(*unwrapped_args_0, **unwrapped_kwargs_0) + # TODO: Extend this all elems not just elems[0] + if res.elems[0].size() != res_0.size(): + import pdb + + pdb.set_trace() + if not torch.allclose(res.elems[0], res_0, atol=1e-3, rtol=1e-3): + import pdb + + pdb.set_trace() + else: + pass + # print("res got type: ", type(res)) + # import pdb; pdb.set_trace() + return res + + +class MapTensor(torch.Tensor): + @staticmethod + def __new__(cls, elems): + # print("elems.layout: ", elems.layout) + return torch.Tensor._make_wrapper_subclass( + cls, + elems.shape[1:], + dtype=elems.dtype, + device=elems.device, + layout=elems.layout, + dispatch_layout=True, + dispatch_sizes_strides_policy=( + "sizes" if elems.layout == torch.jagged else None + ), + storage_size=( + elems._values.untyped_storage().size() + if elems.layout == torch.jagged + else None + ), + ) + + def __init__(self, elems): + self.elems = elems + + @classmethod + def __torch_dispatch__(cls, func, types, args, kwargs=None): + if func in MAP_TENSOR_ATEN_OP_TABLE: + res = MAP_TENSOR_ATEN_OP_TABLE[func](func, types, args, kwargs) + # run_invariant_test(res, func, args, kwargs) + return res + return NotImplemented + + @classmethod + def __torch_function__(cls, func, types, args=(), kwargs=None): + if kwargs is None: + kwargs = {} + with torch._C.DisableTorchFunctionSubclass(): + return func(*args, **kwargs) + + # flatten/unflatten is needed for compile + def __tensor_flatten__(self): + ctx = {} + inner_tensors = ["elems"] + return inner_tensors, ctx + + @staticmethod + def __tensor_unflatten__(inner_tensors: Dict, meta, outer_size, outer_stride): + # inner tensors: _values, _offsets, [_lengths], [_min_seqlen], [_max_seqlen] + assert len(inner_tensors) == 1, f"{inner_tensors}" + elems = inner_tensors["elems"] + + return MapTensor(elems) + + def __repr__(self): + return f"MapTensor({self.elems.size()})" + + def pin_memory(self): + elems = self.elems.pin_memory() + return wrap(elems) + + +# ts is a higher dim Tensor +def to_map_tensor(ts: torch.Tensor): + return MapTensor(ts) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/hieradet.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/hieradet.py new file mode 100644 index 0000000000000000000000000000000000000000..91e98f795edf1efceacd9cbc0f2886bb05c0662e --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/hieradet.py @@ -0,0 +1,332 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging +from functools import partial +from typing import List, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from iopath.common.file_io import g_pathmgr + +from torchao._models.sam2.modeling.backbones.utils import ( + PatchEmbed, + window_partition, + window_unpartition, +) +from torchao._models.sam2.modeling.sam2_utils import MLP, DropPath + + +def do_pool(x: torch.Tensor, pool: nn.Module, norm: nn.Module = None) -> torch.Tensor: + if pool is None: + return x + # (B, H, W, C) -> (B, C, H, W) + x = x.permute(0, 3, 1, 2) + x = pool(x) + # (B, C, H', W') -> (B, H', W', C) + x = x.permute(0, 2, 3, 1) + if norm: + x = norm(x) + + return x + + +class MultiScaleAttention(nn.Module): + def __init__( + self, + dim: int, + dim_out: int, + num_heads: int, + q_pool: nn.Module = None, + ): + super().__init__() + + self.dim = dim + self.dim_out = dim_out + self.num_heads = num_heads + self.q_pool = q_pool + self.qkv = nn.Linear(dim, dim_out * 3) + self.proj = nn.Linear(dim_out, dim_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + B, H, W, _ = x.shape + # qkv with shape (B, H * W, 3, nHead, C) + qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1) + # q, k, v with shape (B, H * W, nheads, C) + q, k, v = torch.unbind(qkv, 2) + + # Q pooling (for downsample at stage changes) + if self.q_pool: + q = do_pool(q.reshape(B, H, W, -1), self.q_pool) + H, W = q.shape[1:3] # downsampled shape + q = q.reshape(B, H * W, self.num_heads, -1) + + # TODO: This fails on batch sizes bigger than 2^16 - 1 + # Torch's SDPA expects [B, nheads, H*W, C] so we transpose + if q.size(0) > 65535: + num_chunks = (q.size(0) + 65535) // 65535 + q_chunks = q.chunk(num_chunks) + k_chunks = k.chunk(num_chunks) + v_chunks = v.chunk(num_chunks) + x_chunks = [] + for qi, ki, vi in zip(q_chunks, k_chunks, v_chunks): + xi = F.scaled_dot_product_attention( + qi.transpose(1, 2), + ki.transpose(1, 2), + vi.transpose(1, 2), + ) + x_chunks.append(xi) + x = torch.cat(x_chunks) + else: + x = F.scaled_dot_product_attention( + q.transpose(1, 2), + k.transpose(1, 2), + v.transpose(1, 2), + ) + # Transpose back + x = x.transpose(1, 2) + x = x.reshape(B, H, W, -1) + + x = self.proj(x) + + return x + + +class MultiScaleBlock(nn.Module): + def __init__( + self, + dim: int, + dim_out: int, + num_heads: int, + mlp_ratio: float = 4.0, + drop_path: float = 0.0, + norm_layer: Union[nn.Module, str] = "LayerNorm", + q_stride: Tuple[int, int] = None, + act_layer: nn.Module = nn.GELU, + window_size: int = 0, + ): + super().__init__() + + if isinstance(norm_layer, str): + norm_layer = partial(getattr(nn, norm_layer), eps=1e-6) + + self.dim = dim + self.dim_out = dim_out + self.norm1 = norm_layer(dim) + + self.window_size = window_size + + self.pool, self.q_stride = None, q_stride + if self.q_stride: + self.pool = nn.MaxPool2d( + kernel_size=q_stride, stride=q_stride, ceil_mode=False + ) + + self.attn = MultiScaleAttention( + dim, + dim_out, + num_heads=num_heads, + q_pool=self.pool, + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + self.norm2 = norm_layer(dim_out) + self.mlp = MLP( + dim_out, + int(dim_out * mlp_ratio), + dim_out, + num_layers=2, + activation=act_layer, + ) + + if dim != dim_out: + self.proj = nn.Linear(dim, dim_out) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + shortcut = x # B, H, W, C + x = self.norm1(x) + + # Skip connection + if self.dim != self.dim_out: + shortcut = do_pool(self.proj(x), self.pool) + + # Window partition + window_size = self.window_size + if window_size > 0: + H, W = x.shape[1], x.shape[2] + x, pad_hw = window_partition(x, window_size) + + # Window Attention + Q Pooling (if stage change) + x = self.attn(x) + if self.q_stride: + # Shapes have changed due to Q pooling + window_size = self.window_size // self.q_stride[0] + H, W = shortcut.shape[1:3] + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + pad_hw = (H + pad_h, W + pad_w) + + # Reverse window partition + if self.window_size > 0: + x = window_unpartition(x, window_size, pad_hw, (H, W)) + + x = shortcut + self.drop_path(x) + # MLP + x = x + self.drop_path(self.mlp(self.norm2(x))) + return x + + +class Hiera(nn.Module): + """ + Reference: https://arxiv.org/abs/2306.00989 + """ + + def __init__( + self, + embed_dim: int = 96, # initial embed dim + num_heads: int = 1, # initial number of heads + drop_path_rate: float = 0.0, # stochastic depth + q_pool: int = 3, # number of q_pool stages + q_stride: Tuple[int, int] = (2, 2), # downsample stride bet. stages + stages: Tuple[int, ...] = (2, 3, 16, 3), # blocks per stage + dim_mul: float = 2.0, # dim_mul factor at stage shift + head_mul: float = 2.0, # head_mul factor at stage shift + window_pos_embed_bkg_spatial_size: Tuple[int, int] = (14, 14), + # window size per stage, when not using global att. + window_spec: Tuple[int, ...] = ( + 8, + 4, + 14, + 7, + ), + # global attn in these blocks + global_att_blocks: Tuple[int, ...] = ( + 12, + 16, + 20, + ), + weights_path=None, + return_interm_layers=True, # return feats from every stage + ): + super().__init__() + + assert len(stages) == len(window_spec) + self.window_spec = window_spec + + depth = sum(stages) + self.q_stride = q_stride + self.stage_ends = [sum(stages[:i]) - 1 for i in range(1, len(stages) + 1)] + assert 0 <= q_pool <= len(self.stage_ends[:-1]) + self.q_pool_blocks = [x + 1 for x in self.stage_ends[:-1]][:q_pool] + self.return_interm_layers = return_interm_layers + + self.patch_embed = PatchEmbed( + embed_dim=embed_dim, + ) + # Which blocks have global att? + self.global_att_blocks = global_att_blocks + + # Windowed positional embedding (https://arxiv.org/abs/2311.05613) + self.window_pos_embed_bkg_spatial_size = window_pos_embed_bkg_spatial_size + self.pos_embed = nn.Parameter( + torch.zeros(1, embed_dim, *self.window_pos_embed_bkg_spatial_size) + ) + self.pos_embed_window = nn.Parameter( + torch.zeros(1, embed_dim, self.window_spec[0], self.window_spec[0]) + ) + + dpr = [ + x.item() for x in torch.linspace(0, drop_path_rate, depth) + ] # stochastic depth decay rule + + cur_stage = 1 + self.blocks = nn.ModuleList() + + for i in range(depth): + dim_out = embed_dim + # lags by a block, so first block of + # next stage uses an initial window size + # of previous stage and final window size of current stage + window_size = self.window_spec[cur_stage - 1] + + if self.global_att_blocks is not None: + window_size = 0 if i in self.global_att_blocks else window_size + + if i - 1 in self.stage_ends: + dim_out = int(embed_dim * dim_mul) + num_heads = int(num_heads * head_mul) + cur_stage += 1 + + block = MultiScaleBlock( + dim=embed_dim, + dim_out=dim_out, + num_heads=num_heads, + drop_path=dpr[i], + q_stride=self.q_stride if i in self.q_pool_blocks else None, + window_size=window_size, + ) + + embed_dim = dim_out + self.blocks.append(block) + + self.channel_list = ( + [self.blocks[i].dim_out for i in self.stage_ends[::-1]] + if return_interm_layers + else [self.blocks[-1].dim_out] + ) + + if weights_path is not None: + with g_pathmgr.open(weights_path, "rb") as f: + chkpt = torch.load(f, map_location="cpu") + logging.info("loading Hiera", self.load_state_dict(chkpt, strict=False)) + + def _get_pos_embed(self, hw: Tuple[int, int]) -> torch.Tensor: + h, w = hw + window_embed = self.pos_embed_window + pos_embed = F.interpolate(self.pos_embed, size=(h, w), mode="bicubic") + pos_embed = pos_embed + window_embed.tile( + [x // y for x, y in zip(pos_embed.shape, window_embed.shape)] + ) + pos_embed = pos_embed.permute(0, 2, 3, 1) + return pos_embed + + def forward(self, x: torch.Tensor) -> List[torch.Tensor]: + x = self.patch_embed(x) + # x: (B, H, W, C) + + # Add pos embed + x = x + self._get_pos_embed(x.shape[1:3]) + + outputs = [] + for i, blk in enumerate(self.blocks): + x = blk(x) + if (i == self.stage_ends[-1]) or ( + i in self.stage_ends and self.return_interm_layers + ): + feats = x.permute(0, 3, 1, 2) + outputs.append(feats) + + return outputs + + def get_layer_id(self, layer_name): + # https://github.com/microsoft/unilm/blob/master/beit/optim_factory.py#L33 + num_layers = self.get_num_layers() + + if layer_name.find("rel_pos") != -1: + return num_layers + 1 + elif layer_name.find("pos_embed") != -1: + return 0 + elif layer_name.find("patch_embed") != -1: + return 0 + elif layer_name.find("blocks") != -1: + return int(layer_name.split("blocks")[1].split(".")[1]) + 1 + else: + return num_layers + 1 + + def get_num_layers(self) -> int: + return len(self.blocks) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/image_encoder.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/image_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..2370c02182a8f570126fd4055fd9006e2e2e9f95 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/image_encoder.py @@ -0,0 +1,141 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +class ImageEncoder(nn.Module): + def __init__( + self, + trunk: nn.Module, + neck: nn.Module, + scalp: int = 0, + ): + super().__init__() + self.trunk = trunk + self.neck = neck + self.scalp = scalp + assert self.trunk.channel_list == self.neck.backbone_channel_list, ( + f"Channel dims of trunk and neck do not match. Trunk: {self.trunk.channel_list}, neck: {self.neck.backbone_channel_list}" + ) + + def forward(self, sample: torch.Tensor): + # Forward through backbone + with torch.autograd.profiler.record_function("self.neck(self.trunk(sample))"): + from torchao._models.sam2.map_tensor import MapTensor, to_map_tensor + + if isinstance(sample, MapTensor): + features, pos = self.neck(self.trunk(sample.elems.flatten(0, 1))) + features = [to_map_tensor(t.unsqueeze(1)) for t in features] + pos = [to_map_tensor(t.unsqueeze(1)) for t in pos] + else: + features, pos = self.neck(self.trunk(sample)) + if self.scalp > 0: + # Discard the lowest resolution features + features, pos = features[: -self.scalp], pos[: -self.scalp] + + src = features[-1] + output = { + "vision_features": src, + "vision_pos_enc": pos, + "backbone_fpn": features, + } + return output + + +class FpnNeck(nn.Module): + """ + A modified variant of Feature Pyramid Network (FPN) neck + (we remove output conv and also do bicubic interpolation similar to ViT + pos embed interpolation) + """ + + def __init__( + self, + position_encoding: nn.Module, + d_model: int, + backbone_channel_list: List[int], + kernel_size: int = 1, + stride: int = 1, + padding: int = 0, + fpn_interp_model: str = "bilinear", + fuse_type: str = "sum", + fpn_top_down_levels: Optional[List[int]] = None, + ): + """Initialize the neck + :param trunk: the backbone + :param position_encoding: the positional encoding to use + :param d_model: the dimension of the model + :param neck_norm: the normalization to use + """ + super().__init__() + self.position_encoding = position_encoding + self.convs = nn.ModuleList() + self.backbone_channel_list = backbone_channel_list + self.d_model = d_model + for dim in backbone_channel_list: + current = nn.Sequential() + current.add_module( + "conv", + nn.Conv2d( + in_channels=dim, + out_channels=d_model, + kernel_size=kernel_size, + stride=stride, + padding=padding, + ), + ) + + self.convs.append(current) + self.fpn_interp_model = fpn_interp_model + assert fuse_type in ["sum", "avg"] + self.fuse_type = fuse_type + + # levels to have top-down features in its outputs + # e.g. if fpn_top_down_levels is [2, 3], then only outputs of level 2 and 3 + # have top-down propagation, while outputs of level 0 and level 1 have only + # lateral features from the same backbone level. + if fpn_top_down_levels is None: + # default is to have top-down features on all levels + fpn_top_down_levels = range(len(self.convs)) + self.fpn_top_down_levels = list(fpn_top_down_levels) + + def forward(self, xs: List[torch.Tensor]): + out = [None] * len(self.convs) + pos = [None] * len(self.convs) + assert len(xs) == len(self.convs) + # fpn forward pass + # see https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/fpn.py + prev_features = None + # forward in top-down order (from low to high resolution) + n = len(self.convs) - 1 + for i in range(n, -1, -1): + x = xs[i] + lateral_features = self.convs[n - i](x) + if i in self.fpn_top_down_levels and prev_features is not None: + top_down_features = F.interpolate( + prev_features.to(dtype=torch.float32), + scale_factor=2.0, + mode=self.fpn_interp_model, + align_corners=( + None if self.fpn_interp_model == "nearest" else False + ), + antialias=False, + ) + prev_features = lateral_features + top_down_features + if self.fuse_type == "avg": + prev_features /= 2 + else: + prev_features = lateral_features + x_out = prev_features + out[i] = x_out + pos[i] = self.position_encoding(x_out).to(x_out.dtype) + + return out, pos diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..32d55c7545f064de133a5ff0200ba1ece9b504b7 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/backbones/utils.py @@ -0,0 +1,95 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +"""Some utilities for backbones, in particular for windowing""" + +from typing import Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F + + +def window_partition(x, window_size): + """ + Partition into non-overlapping windows with padding if needed. + Args: + x (tensor): input tokens with [B, H, W, C]. + window_size (int): window size. + Returns: + windows: windows after partition with [B * num_windows, window_size, window_size, C]. + (Hp, Wp): padded height and width before partition + """ + B, H, W, C = x.shape + + pad_h = (window_size - H % window_size) % window_size + pad_w = (window_size - W % window_size) % window_size + if pad_h > 0 or pad_w > 0: + x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h)) + Hp, Wp = H + pad_h, W + pad_w + + x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C) + windows = ( + x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) + ) + return windows, (Hp, Wp) + + +def window_unpartition(windows, window_size, pad_hw, hw): + """ + Window unpartition into original sequences and removing padding. + Args: + x (tensor): input tokens with [B * num_windows, window_size, window_size, C]. + window_size (int): window size. + pad_hw (Tuple): padded height and width (Hp, Wp). + hw (Tuple): original height and width (H, W) before padding. + Returns: + x: unpartitioned sequences with [B, H, W, C]. + """ + Hp, Wp = pad_hw + H, W = hw + B = windows.shape[0] // (Hp * Wp // window_size // window_size) + x = windows.view( + B, Hp // window_size, Wp // window_size, window_size, window_size, -1 + ) + x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1) + + if Hp > H or Wp > W: + x = x[:, :H, :W, :].contiguous() + return x + + +class PatchEmbed(nn.Module): + """ + Image to Patch Embedding. + """ + + def __init__( + self, + kernel_size: Tuple[int, ...] = (7, 7), + stride: Tuple[int, ...] = (4, 4), + padding: Tuple[int, ...] = (3, 3), + in_chans: int = 3, + embed_dim: int = 768, + ): + """ + Args: + kernel_size (Tuple): kernel size of the projection layer. + stride (Tuple): stride of the projection layer. + padding (Tuple): padding size of the projection layer. + in_chans (int): Number of input image channels. + embed_dim (int): embed_dim (int): Patch embedding dimension. + """ + super().__init__() + self.proj = nn.Conv2d( + in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.proj(x) + # B C H W -> B H W C + x = x.permute(0, 2, 3, 1) + return x diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/memory_attention.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/memory_attention.py new file mode 100644 index 0000000000000000000000000000000000000000..5d007c703a2ab76623fe828536b695ef65f4dc5a --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/memory_attention.py @@ -0,0 +1,166 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional + +import torch +from torch import Tensor, nn + +from torchao._models.sam2.modeling.sam.transformer import RoPEAttention +from torchao._models.sam2.modeling.sam2_utils import get_activation_fn, get_clones + + +class MemoryAttentionLayer(nn.Module): + def __init__( + self, + activation: str, + cross_attention: nn.Module, + d_model: int, + dim_feedforward: int, + dropout: float, + pos_enc_at_attn: bool, + pos_enc_at_cross_attn_keys: bool, + pos_enc_at_cross_attn_queries: bool, + self_attention: nn.Module, + ): + super().__init__() + self.d_model = d_model + self.dim_feedforward = dim_feedforward + self.dropout_value = dropout + self.self_attn = self_attention + self.cross_attn_image = cross_attention + + # Implementation of Feedforward model + self.linear1 = nn.Linear(d_model, dim_feedforward) + self.dropout = nn.Dropout(dropout) + self.linear2 = nn.Linear(dim_feedforward, d_model) + + self.norm1 = nn.LayerNorm(d_model) + self.norm2 = nn.LayerNorm(d_model) + self.norm3 = nn.LayerNorm(d_model) + self.dropout1 = nn.Dropout(dropout) + self.dropout2 = nn.Dropout(dropout) + self.dropout3 = nn.Dropout(dropout) + + self.activation_str = activation + self.activation = get_activation_fn(activation) + + # Where to add pos enc + self.pos_enc_at_attn = pos_enc_at_attn + self.pos_enc_at_cross_attn_queries = pos_enc_at_cross_attn_queries + self.pos_enc_at_cross_attn_keys = pos_enc_at_cross_attn_keys + + def _forward_sa(self, tgt, query_pos): + # Self-Attention + tgt2 = self.norm1(tgt) + q = k = tgt2 + query_pos if self.pos_enc_at_attn else tgt2 + tgt2 = self.self_attn(q, k, v=tgt2) + tgt = tgt + self.dropout1(tgt2) + return tgt + + def _forward_ca(self, tgt, memory, query_pos, pos, num_k_exclude_rope=0): + kwds = {} + if num_k_exclude_rope > 0: + assert isinstance(self.cross_attn_image, RoPEAttention) + kwds = {"num_k_exclude_rope": num_k_exclude_rope} + + # Cross-Attention + tgt2 = self.norm2(tgt) + tgt2 = self.cross_attn_image( + q=tgt2 + query_pos if self.pos_enc_at_cross_attn_queries else tgt2, + k=memory + pos if self.pos_enc_at_cross_attn_keys else memory, + v=memory, + **kwds, + ) + tgt = tgt + self.dropout2(tgt2) + return tgt + + def forward( + self, + tgt, + memory, + pos: Optional[Tensor] = None, + query_pos: Optional[Tensor] = None, + num_k_exclude_rope: int = 0, + ) -> torch.Tensor: + # Self-Attn, Cross-Attn + tgt = self._forward_sa(tgt, query_pos) + tgt = self._forward_ca(tgt, memory, query_pos, pos, num_k_exclude_rope) + # MLP + tgt2 = self.norm3(tgt) + tgt2 = self.linear2(self.dropout(self.activation(self.linear1(tgt2)))) + tgt = tgt + self.dropout3(tgt2) + return tgt + + +class MemoryAttention(nn.Module): + def __init__( + self, + d_model: int, + pos_enc_at_input: bool, + layer: nn.Module, + num_layers: int, + batch_first: bool = True, # Do layers expect batch first input? + ): + super().__init__() + self.d_model = d_model + self.layers = get_clones(layer, num_layers) + self.num_layers = num_layers + self.norm = nn.LayerNorm(d_model) + self.pos_enc_at_input = pos_enc_at_input + self.batch_first = batch_first + + def forward( + self, + curr: torch.Tensor, # self-attention inputs + memory: torch.Tensor, # cross-attention inputs + curr_pos: Optional[Tensor] = None, # pos_enc for self-attention inputs + memory_pos: Optional[Tensor] = None, # pos_enc for cross-attention inputs + num_obj_ptr_tokens: int = 0, # number of object pointer *tokens* + ): + if isinstance(curr, list): + assert isinstance(curr_pos, list) + assert len(curr) == len(curr_pos) == 1 + curr, curr_pos = ( + curr[0], + curr_pos[0], + ) + + assert curr.shape[1] == memory.shape[1], ( + "Batch size must be the same for curr and memory" + ) + + output = curr + if self.pos_enc_at_input and curr_pos is not None: + output = output + 0.1 * curr_pos + + if self.batch_first: + # Convert to batch first + output = output.transpose(0, 1) + curr_pos = curr_pos.transpose(0, 1) + memory = memory.transpose(0, 1) + memory_pos = memory_pos.transpose(0, 1) + + for layer in self.layers: + kwds = {} + if isinstance(layer.cross_attn_image, RoPEAttention): + kwds = {"num_k_exclude_rope": num_obj_ptr_tokens} + + output = layer( + tgt=output, + memory=memory, + pos=memory_pos, + query_pos=curr_pos, + **kwds, + ) + normed_output = self.norm(output) + + if self.batch_first: + # Convert back to seq first + normed_output = normed_output.transpose(0, 1) + curr_pos = curr_pos.transpose(0, 1) + + return normed_output diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/memory_encoder.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/memory_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..3796cefd0000b3f98ec5f390dad821b4f9e2217e --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/memory_encoder.py @@ -0,0 +1,181 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import Tuple + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from torchao._models.sam2.modeling.sam2_utils import DropPath, LayerNorm2d, get_clones + + +class MaskDownSampler(nn.Module): + """ + Progressively downsample a mask by total_stride, each time by stride. + Note that LayerNorm is applied per *token*, like in ViT. + + With each downsample (by a factor stride**2), channel capacity increases by the same factor. + In the end, we linearly project to embed_dim channels. + """ + + def __init__( + self, + embed_dim=256, + kernel_size=4, + stride=4, + padding=0, + total_stride=16, + activation=nn.GELU, + ): + super().__init__() + num_layers = int(math.log2(total_stride) // math.log2(stride)) + assert stride**num_layers == total_stride + self.encoder = nn.Sequential() + mask_in_chans, mask_out_chans = 1, 1 + for _ in range(num_layers): + mask_out_chans = mask_in_chans * (stride**2) + self.encoder.append( + nn.Conv2d( + mask_in_chans, + mask_out_chans, + kernel_size=kernel_size, + stride=stride, + padding=padding, + ) + ) + self.encoder.append(LayerNorm2d(mask_out_chans)) + self.encoder.append(activation()) + mask_in_chans = mask_out_chans + + self.encoder.append(nn.Conv2d(mask_out_chans, embed_dim, kernel_size=1)) + + def forward(self, x): + return self.encoder(x) + + +# Lightly adapted from ConvNext (https://github.com/facebookresearch/ConvNeXt) +class CXBlock(nn.Module): + r"""ConvNeXt Block. There are two equivalent implementations: + (1) DwConv -> LayerNorm (channels_first) -> 1x1 Conv -> GELU -> 1x1 Conv; all in (N, C, H, W) + (2) DwConv -> Permute to (N, H, W, C); LayerNorm (channels_last) -> Linear -> GELU -> Linear; Permute back + We use (2) as we find it slightly faster in PyTorch + + Args: + dim (int): Number of input channels. + drop_path (float): Stochastic depth rate. Default: 0.0 + layer_scale_init_value (float): Init value for Layer Scale. Default: 1e-6. + """ + + def __init__( + self, + dim, + kernel_size=7, + padding=3, + drop_path=0.0, + layer_scale_init_value=1e-6, + use_dwconv=True, + ): + super().__init__() + self.dwconv = nn.Conv2d( + dim, + dim, + kernel_size=kernel_size, + padding=padding, + groups=dim if use_dwconv else 1, + ) # depthwise conv + self.norm = LayerNorm2d(dim, eps=1e-6) + self.pwconv1 = nn.Linear( + dim, 4 * dim + ) # pointwise/1x1 convs, implemented with linear layers + self.act = nn.GELU() + self.pwconv2 = nn.Linear(4 * dim, dim) + self.gamma = ( + nn.Parameter(layer_scale_init_value * torch.ones((dim)), requires_grad=True) + if layer_scale_init_value > 0 + else None + ) + self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity() + + def forward(self, x): + input = x + x = self.dwconv(x) + x = self.norm(x) + x = x.permute(0, 2, 3, 1) # (N, C, H, W) -> (N, H, W, C) + x = self.pwconv1(x) + x = self.act(x) + x = self.pwconv2(x) + if self.gamma is not None: + x = self.gamma * x + x = x.permute(0, 3, 1, 2) # (N, H, W, C) -> (N, C, H, W) + + x = input + self.drop_path(x) + return x + + +class Fuser(nn.Module): + def __init__(self, layer, num_layers, dim=None, input_projection=False): + super().__init__() + self.proj = nn.Identity() + self.layers = get_clones(layer, num_layers) + + if input_projection: + assert dim is not None + self.proj = nn.Conv2d(dim, dim, kernel_size=1) + + def forward(self, x): + # normally x: (N, C, H, W) + x = self.proj(x) + for layer in self.layers: + x = layer(x) + return x + + +class MemoryEncoder(nn.Module): + def __init__( + self, + out_dim, + mask_downsampler, + fuser, + position_encoding, + in_dim=256, # in_dim of pix_feats + ): + super().__init__() + + self.mask_downsampler = mask_downsampler + + self.pix_feat_proj = nn.Conv2d(in_dim, in_dim, kernel_size=1) + self.fuser = fuser + self.position_encoding = position_encoding + self.out_proj = nn.Identity() + if out_dim != in_dim: + self.out_proj = nn.Conv2d(in_dim, out_dim, kernel_size=1) + + def forward( + self, + pix_feat: torch.Tensor, + masks: torch.Tensor, + skip_mask_sigmoid: bool = False, + ) -> Tuple[torch.Tensor, torch.Tensor]: + ## Process masks + # sigmoid, so that less domain shift from gt masks which are bool + if not skip_mask_sigmoid: + masks = F.sigmoid(masks) + masks = self.mask_downsampler(masks) + + ## Fuse pix_feats and downsampled masks + # in case the visual features are on CPU, cast them to CUDA + pix_feat = pix_feat.to(masks.device) + + x = self.pix_feat_proj(pix_feat) + x = x + masks + x = self.fuser(x) + x = self.out_proj(x) + + pos = self.position_encoding(x).to(x.dtype) + + return {"vision_features": x, "vision_pos_enc": [pos]} diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/position_encoding.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/position_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..00c3c93732e7f50f51698511b94836cc7682c766 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/position_encoding.py @@ -0,0 +1,226 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from typing import Any, Optional, Tuple + +import numpy as np +import torch +from torch import nn + + +class PositionEmbeddingSine(nn.Module): + """ + This is a more standard version of the position embedding, very similar to the one + used by the Attention Is All You Need paper, generalized to work on images. + """ + + def __init__( + self, + num_pos_feats, + temperature: int = 10000, + normalize: bool = True, + scale: Optional[float] = None, + ): + super().__init__() + assert num_pos_feats % 2 == 0, "Expecting even model width" + self.num_pos_feats = num_pos_feats // 2 + self.temperature = temperature + self.normalize = normalize + if scale is not None and normalize is False: + raise ValueError("normalize should be True if scale is passed") + if scale is None: + scale = 2 * math.pi + self.scale = scale + + # self.cache = {} + + def _encode_xy(self, x, y): + # The positions are expected to be normalized + assert len(x) == len(y) and x.ndim == y.ndim == 1 + x_embed = x * self.scale + y_embed = y * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) + + pos_x = x_embed[:, None] / dim_t + pos_y = y_embed[:, None] / dim_t + pos_x = torch.stack( + (pos_x[:, 0::2].sin(), pos_x[:, 1::2].cos()), dim=2 + ).flatten(1) + pos_y = torch.stack( + (pos_y[:, 0::2].sin(), pos_y[:, 1::2].cos()), dim=2 + ).flatten(1) + return pos_x, pos_y + + @torch.no_grad() + def encode_boxes(self, x, y, w, h): + pos_x, pos_y = self._encode_xy(x, y) + pos = torch.cat((pos_y, pos_x, h[:, None], w[:, None]), dim=1) + return pos + + encode = encode_boxes # Backwards compatibility + + @torch.no_grad() + def encode_points(self, x, y, labels): + (bx, nx), (by, ny), (bl, nl) = x.shape, y.shape, labels.shape + assert bx == by and nx == ny and bx == bl and nx == nl + pos_x, pos_y = self._encode_xy(x.flatten(), y.flatten()) + pos_x, pos_y = pos_x.reshape(bx, nx, -1), pos_y.reshape(by, ny, -1) + pos = torch.cat((pos_y, pos_x, labels[:, :, None]), dim=2) + return pos + + @torch.no_grad() + def forward(self, x: torch.Tensor): + # cache_key = (x.shape[-2], x.shape[-1]) + # if cache_key in self.cache: + # return self.cache[cache_key][None].repeat(x.shape[0], 1, 1, 1) + y_embed = ( + torch.arange(1, x.shape[-2] + 1, dtype=torch.float32, device=x.device) + .view(1, -1, 1) + .repeat(x.shape[0], 1, x.shape[-1]) + ) + x_embed = ( + torch.arange(1, x.shape[-1] + 1, dtype=torch.float32, device=x.device) + .view(1, 1, -1) + .repeat(x.shape[0], x.shape[-2], 1) + ) + + if self.normalize: + eps = 1e-6 + y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale + x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) + + pos_x = x_embed[:, :, :, None] / dim_t + pos_y = y_embed[:, :, :, None] / dim_t + pos_x = torch.stack( + (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos_y = torch.stack( + (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4 + ).flatten(3) + pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) + # self.cache[cache_key] = pos[0] + return pos + + +class PositionEmbeddingRandom(nn.Module): + """ + Positional encoding using random spatial frequencies. + """ + + def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None: + super().__init__() + if scale is None or scale <= 0.0: + scale = 1.0 + self.register_buffer( + "positional_encoding_gaussian_matrix", + scale * torch.randn((2, num_pos_feats)), + ) + + def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor: + """Positionally encode points that are normalized to [0,1].""" + # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape + coords = 2 * coords - 1 + coords = coords @ self.positional_encoding_gaussian_matrix + coords = 2 * np.pi * coords + # outputs d_1 x ... x d_n x C shape + return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1) + + def forward(self, size: Tuple[int, int]) -> torch.Tensor: + """Generate positional encoding for a grid of the specified size.""" + h, w = size + device: Any = self.positional_encoding_gaussian_matrix.device + grid = torch.ones((h, w), device=device, dtype=torch.float32) + y_embed = grid.cumsum(dim=0) - 0.5 + x_embed = grid.cumsum(dim=1) - 0.5 + y_embed = y_embed / h + x_embed = x_embed / w + + pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1)) + return pe.permute(2, 0, 1) # C x H x W + + def forward_with_coords( + self, coords_input: torch.Tensor, image_size: Tuple[int, int] + ) -> torch.Tensor: + """Positionally encode points that are not normalized to [0,1].""" + coords = coords_input.clone() + coords[:, :, 0] = coords[:, :, 0] / image_size[1] + coords[:, :, 1] = coords[:, :, 1] / image_size[0] + return self._pe_encoding(coords.to(torch.float)) # B x N x C + + +# Rotary Positional Encoding, adapted from: +# 1. https://github.com/meta-llama/codellama/blob/main/llama/model.py +# 2. https://github.com/naver-ai/rope-vit +# 3. https://github.com/lucidrains/rotary-embedding-torch + + +def init_t_xy(end_x: int, end_y: int, device=None): + t = torch.arange(end_x * end_y, dtype=torch.float32, device=device) + t_x = (t % end_x).float() + t_y = torch.div(t, end_x, rounding_mode="floor").float() + return t_x, t_y + + +def compute_axial_cis( + dim: int, end_x: int, end_y: int, theta: float = 10000.0, device=None +): + freqs_x = 1.0 / ( + theta ** (torch.arange(0, dim, 4, device=device)[: (dim // 4)].float() / dim) + ) + freqs_y = 1.0 / ( + theta ** (torch.arange(0, dim, 4, device=device)[: (dim // 4)].float() / dim) + ) + + t_x, t_y = init_t_xy(end_x, end_y, device=device) + freqs_x = torch.outer(t_x, freqs_x) + freqs_y = torch.outer(t_y, freqs_y) + freqs_cis_x = torch.polar(torch.ones_like(freqs_x), freqs_x) + freqs_cis_y = torch.polar(torch.ones_like(freqs_y), freqs_y) + return torch.cat([freqs_cis_x, freqs_cis_y], dim=-1) + + +def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor): + ndim = x.ndim + assert 0 <= 1 < ndim + assert freqs_cis.shape == (x.shape[-2], x.shape[-1]) + shape = [d if i >= ndim - 2 else 1 for i, d in enumerate(x.shape)] + return freqs_cis.view(*shape) + + +def apply_rotary_enc( + xq: torch.Tensor, + xk: torch.Tensor, + freqs_cis: torch.Tensor, + repeat_freqs_k: bool = False, +): + xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2)) + xk_ = ( + torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2)) + if xk.shape[-2] != 0 + else None + ) + freqs_cis = reshape_for_broadcast(freqs_cis, xq_) + xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3) + if xk_ is None: + # no keys to rotate, due to dropout + return xq_out.type_as(xq).to(xq.device), xk + # repeat freqs along seq_len dim to match k seq_len + if repeat_freqs_k: + r = xk_.shape[-2] // xq_.shape[-2] + if freqs_cis.is_cuda: + freqs_cis = freqs_cis.repeat(*([1] * (freqs_cis.ndim - 2)), r, 1) + else: + # torch.repeat on complex numbers may not be supported on non-CUDA devices + # (freqs_cis has 4 dims and we repeat on dim 2) so we use expand + flatten + freqs_cis = freqs_cis.unsqueeze(2).expand(-1, -1, r, -1, -1).flatten(2, 3) + xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3) + return xq_out.type_as(xq).to(xq.device), xk_out.type_as(xk).to(xk.device) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/mask_decoder.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/mask_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..7bec0affa53bf8ed93d97409adba9c2ef78384e8 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/mask_decoder.py @@ -0,0 +1,317 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Optional, Tuple, Type + +import torch +from torch import nn + +from torchao._models.sam2.modeling.sam2_utils import MLP, LayerNorm2d + + +class MaskDecoder(nn.Module): + def __init__( + self, + *, + transformer_dim: int, + transformer: nn.Module, + num_multimask_outputs: int = 3, + activation: Type[nn.Module] = nn.GELU, + iou_head_depth: int = 3, + iou_head_hidden_dim: int = 256, + use_high_res_features: bool = False, + iou_prediction_use_sigmoid=False, + dynamic_multimask_via_stability=False, + dynamic_multimask_stability_delta=0.05, + dynamic_multimask_stability_thresh=0.98, + pred_obj_scores: bool = False, + pred_obj_scores_mlp: bool = False, + use_multimask_token_for_obj_ptr: bool = False, + ) -> None: + """ + Predicts masks given an image and prompt embeddings, using a + transformer architecture. + + Arguments: + transformer_dim (int): the channel dimension of the transformer + transformer (nn.Module): the transformer used to predict masks + num_multimask_outputs (int): the number of masks to predict + when disambiguating masks + activation (nn.Module): the type of activation to use when + upscaling masks + iou_head_depth (int): the depth of the MLP used to predict + mask quality + iou_head_hidden_dim (int): the hidden dimension of the MLP + used to predict mask quality + """ + super().__init__() + self.transformer_dim = transformer_dim + self.transformer = transformer + + self.num_multimask_outputs = num_multimask_outputs + + self.iou_token = nn.Embedding(1, transformer_dim) + self.num_mask_tokens = num_multimask_outputs + 1 + self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim) + + self.pred_obj_scores = pred_obj_scores + if self.pred_obj_scores: + self.obj_score_token = nn.Embedding(1, transformer_dim) + self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr + + self.output_upscaling = nn.Sequential( + nn.ConvTranspose2d( + transformer_dim, transformer_dim // 4, kernel_size=2, stride=2 + ), + LayerNorm2d(transformer_dim // 4), + activation(), + nn.ConvTranspose2d( + transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2 + ), + activation(), + ) + self.use_high_res_features = use_high_res_features + if use_high_res_features: + self.conv_s0 = nn.Conv2d( + transformer_dim, transformer_dim // 8, kernel_size=1, stride=1 + ) + self.conv_s1 = nn.Conv2d( + transformer_dim, transformer_dim // 4, kernel_size=1, stride=1 + ) + + self.output_hypernetworks_mlps = nn.ModuleList( + [ + MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3) + for i in range(self.num_mask_tokens) + ] + ) + + self.iou_prediction_head = MLP( + transformer_dim, + iou_head_hidden_dim, + self.num_mask_tokens, + iou_head_depth, + sigmoid_output=iou_prediction_use_sigmoid, + ) + if self.pred_obj_scores: + self.pred_obj_score_head = nn.Linear(transformer_dim, 1) + if pred_obj_scores_mlp: + self.pred_obj_score_head = MLP(transformer_dim, transformer_dim, 1, 3) + + # When outputting a single mask, optionally we can dynamically fall back to the best + # multimask output token if the single mask output token gives low stability scores. + self.dynamic_multimask_via_stability = dynamic_multimask_via_stability + self.dynamic_multimask_stability_delta = dynamic_multimask_stability_delta + self.dynamic_multimask_stability_thresh = dynamic_multimask_stability_thresh + self._src_dtype = torch.float32 + + def forward( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + multimask_output: bool, + repeat_image: bool, + high_res_features: Optional[List[torch.Tensor]] = None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Predict masks given image and prompt embeddings. + + Arguments: + image_embeddings (torch.Tensor): the embeddings from the image encoder + image_pe (torch.Tensor): positional encoding with the shape of image_embeddings + sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes + dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs + multimask_output (bool): Whether to return multiple masks or a single + mask. + + Returns: + torch.Tensor: batched predicted masks + torch.Tensor: batched predictions of mask quality + torch.Tensor: batched SAM token for mask output + """ + masks, iou_pred, mask_tokens_out, object_score_logits = self.predict_masks( + image_embeddings=image_embeddings, + image_pe=image_pe, + sparse_prompt_embeddings=sparse_prompt_embeddings, + dense_prompt_embeddings=dense_prompt_embeddings, + repeat_image=repeat_image, + high_res_features=high_res_features, + ) + + # Select the correct mask or masks for output + if multimask_output: + masks = masks[:, 1:, :, :] + iou_pred = iou_pred[:, 1:] + elif self.dynamic_multimask_via_stability and not self.training: + masks, iou_pred = self._dynamic_multimask_via_stability(masks, iou_pred) + else: + masks = masks[:, 0:1, :, :] + iou_pred = iou_pred[:, 0:1] + + if multimask_output and self.use_multimask_token_for_obj_ptr: + sam_tokens_out = mask_tokens_out[:, 1:] # [b, 3, c] shape + else: + # Take the mask output token. Here we *always* use the token for single mask output. + # At test time, even if we track after 1-click (and using multimask_output=True), + # we still take the single mask token here. The rationale is that we always track + # after multiple clicks during training, so the past tokens seen during training + # are always the single mask token (and we'll let it be the object-memory token). + sam_tokens_out = mask_tokens_out[:, 0:1] # [b, 1, c] shape + + # Prepare output + return masks, iou_pred, sam_tokens_out, object_score_logits + + def predict_masks( + self, + image_embeddings: torch.Tensor, + image_pe: torch.Tensor, + sparse_prompt_embeddings: torch.Tensor, + dense_prompt_embeddings: torch.Tensor, + repeat_image: bool, + high_res_features: Optional[List[torch.Tensor]] = None, + ) -> Tuple[torch.Tensor, torch.Tensor]: + """Predicts masks. See 'forward' for more details.""" + # Concatenate output tokens + s = 0 + if self.pred_obj_scores: + output_tokens = torch.cat( + [ + self.obj_score_token.weight, + self.iou_token.weight, + self.mask_tokens.weight, + ], + dim=0, + ) + s = 1 + else: + output_tokens = torch.cat( + [self.iou_token.weight, self.mask_tokens.weight], dim=0 + ) + output_tokens = output_tokens.unsqueeze(0).expand( + sparse_prompt_embeddings.size(0), -1, -1 + ) + tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1) + + # Expand per-image data in batch direction to be per-mask + if repeat_image: + src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0) + else: + assert image_embeddings.shape[0] == tokens.shape[0] + src = image_embeddings + src = src + dense_prompt_embeddings + assert image_pe.size(0) == 1, ( + "image_pe should have size 1 in batch dim (from `get_dense_pe()`)" + ) + pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0) + b, c, h, w = src.shape + + with torch.autograd.profiler.record_function("self.transformer"): + # # Run the transformer + src = src.to(self._src_dtype) + pos_src = pos_src.to(self._src_dtype) + tokens = tokens.to(self._src_dtype) + hs, new_src = self.transformer(src, pos_src, tokens) + # TODO: Not specifying scale kwarg in SDPA will cause NaN here + # print("hs.isnan().any(): ", hs.isnan().any().item()) + + # TODO: These outputs are being immediately indexed. + # Is there something to remove? + # TODO: The fact that there's a crop box and we try to find stuff at the + # boundary later and there's generally cropping going on smells of padding. + iou_token_out = hs[:, s, :] + mask_tokens_out = hs[:, s + 1 : (s + 1 + self.num_mask_tokens), :] + + # Upscale mask embeddings and predict masks using the mask tokens + src = new_src.transpose(1, 2).view(b, c, h, w) + if not self.use_high_res_features: + upscaled_embedding = self.output_upscaling(src) + else: + with torch.autograd.profiler.record_function("upscale mask embeddings"): + dc1, ln1, act1, dc2, act2 = self.output_upscaling + feat_s0, feat_s1 = high_res_features + upscaled_embedding = act1(ln1(dc1(src) + feat_s1)) + upscaled_embedding = act2(dc2(upscaled_embedding) + feat_s0) + # upscaled_embedding = act2(torch.cat([dc2(upscaled_embedding[:512]), dc2(upscaled_embedding[-512:])]) + feat_s0) + + hyper_in_list: List[torch.Tensor] = [] + for i in range(self.num_mask_tokens): + hyper_in_list.append( + self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]) + ) + hyper_in = torch.stack(hyper_in_list, dim=1) + b, c, h, w = upscaled_embedding.shape + # masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w) + masks = ( + torch.matmul( + upscaled_embedding.view(b, c, h * w).transpose(-1, -2), + hyper_in.transpose(-1, -2), + ) + .transpose(-1, -2) + .reshape(b, -1, h, w) + ) + + # Generate mask quality predictions + iou_pred = self.iou_prediction_head(iou_token_out) + if self.pred_obj_scores: + assert s == 1 + object_score_logits = self.pred_obj_score_head(hs[:, 0, :]) + else: + # Obj scores logits - default to 10.0, i.e. assuming the object is present, sigmoid(10)=1 + object_score_logits = 10.0 * iou_pred.new_ones(iou_pred.shape[0], 1) + + return masks, iou_pred, mask_tokens_out, object_score_logits + + def _get_stability_scores(self, mask_logits): + """ + Compute stability scores of the mask logits based on the IoU between upper and + lower thresholds. + """ + mask_logits = mask_logits.flatten(-2) + stability_delta = self.dynamic_multimask_stability_delta + area_i = torch.sum(mask_logits > stability_delta, dim=-1).float() + area_u = torch.sum(mask_logits > -stability_delta, dim=-1).float() + stability_scores = torch.where(area_u > 0, area_i / area_u, 1.0) + return stability_scores + + def _dynamic_multimask_via_stability(self, all_mask_logits, all_iou_scores): + """ + When outputting a single mask, if the stability score from the current single-mask + output (based on output token 0) falls below a threshold, we instead select from + multi-mask outputs (based on output token 1~3) the mask with the highest predicted + IoU score. This is intended to ensure a valid mask for both clicking and tracking. + """ + # The best mask from multimask output tokens (1~3) + multimask_logits = all_mask_logits[:, 1:, :, :] + multimask_iou_scores = all_iou_scores[:, 1:] + best_scores_inds = torch.argmax(multimask_iou_scores, dim=-1) + batch_inds = torch.arange( + multimask_iou_scores.size(0), device=all_iou_scores.device + ) + best_multimask_logits = multimask_logits[batch_inds, best_scores_inds] + best_multimask_logits = best_multimask_logits.unsqueeze(1) + best_multimask_iou_scores = multimask_iou_scores[batch_inds, best_scores_inds] + best_multimask_iou_scores = best_multimask_iou_scores.unsqueeze(1) + + # The mask from singlemask output token 0 and its stability score + singlemask_logits = all_mask_logits[:, 0:1, :, :] + singlemask_iou_scores = all_iou_scores[:, 0:1] + stability_scores = self._get_stability_scores(singlemask_logits) + is_stable = stability_scores >= self.dynamic_multimask_stability_thresh + + # Dynamically fall back to best multimask output upon low stability scores. + mask_logits_out = torch.where( + is_stable[..., None, None].expand_as(singlemask_logits), + singlemask_logits, + best_multimask_logits, + ) + iou_scores_out = torch.where( + is_stable.expand_as(singlemask_iou_scores), + singlemask_iou_scores, + best_multimask_iou_scores, + ) + return mask_logits_out, iou_scores_out diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/prompt_encoder.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/prompt_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..94b7fda8b28e09d20cd948226231dbe205576fce --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/prompt_encoder.py @@ -0,0 +1,214 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from typing import Optional, Tuple, Type + +import torch +from torch import nn + +from torchao._models.sam2.modeling.position_encoding import PositionEmbeddingRandom +from torchao._models.sam2.modeling.sam2_utils import LayerNorm2d + + +class PromptEncoder(nn.Module): + def __init__( + self, + embed_dim: int, + image_embedding_size: Tuple[int, int], + input_image_size: Tuple[int, int], + mask_in_chans: int, + activation: Type[nn.Module] = nn.GELU, + ) -> None: + """ + Encodes prompts for input to SAM's mask decoder. + + Arguments: + embed_dim (int): The prompts' embedding dimension + image_embedding_size (tuple(int, int)): The spatial size of the + image embedding, as (H, W). + input_image_size (int): The padded size of the image as input + to the image encoder, as (H, W). + mask_in_chans (int): The number of hidden channels used for + encoding input masks. + activation (nn.Module): The activation to use when encoding + input masks. + """ + super().__init__() + self.embed_dim = embed_dim + self.input_image_size = input_image_size + self.image_embedding_size = image_embedding_size + self.pe_layer = PositionEmbeddingRandom(embed_dim // 2) + + self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners + point_embeddings = [ + nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings) + ] + self.point_embeddings = nn.ModuleList(point_embeddings) + self.not_a_point_embed = nn.Embedding(1, embed_dim) + + self.mask_input_size = ( + 4 * image_embedding_size[0], + 4 * image_embedding_size[1], + ) + self.mask_downscaling = nn.Sequential( + nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans // 4), + activation(), + nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2), + LayerNorm2d(mask_in_chans), + activation(), + nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1), + ) + self.no_mask_embed = nn.Embedding(1, embed_dim) + + def get_dense_pe(self) -> torch.Tensor: + """ + Returns the positional encoding used to encode point prompts, + applied to a dense set of points the shape of the image encoding. + + Returns: + torch.Tensor: Positional encoding with shape + 1x(embed_dim)x(embedding_h)x(embedding_w) + """ + return self.pe_layer(self.image_embedding_size).unsqueeze(0) + + def _embed_points( + self, + points: torch.Tensor, + labels: torch.Tensor, + pad: bool, + ) -> torch.Tensor: + """Embeds point prompts.""" + points = points + 0.5 # Shift to center of pixel + if pad: + padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device) + padding_label = -torch.ones((labels.shape[0], 1), device=labels.device) + points = torch.cat([points, padding_point], dim=1) + labels = torch.cat([labels, padding_label], dim=1) + point_embedding = self.pe_layer.forward_with_coords( + points, self.input_image_size + ) + # point_embedding[labels == -1] = 0.0 + # point_embedding[labels == -1] += self.not_a_point_embed.weight + # point_embedding[labels == 0] += self.point_embeddings[0].weight + # point_embedding[labels == 1] += self.point_embeddings[1].weight + # point_embedding[labels == 2] += self.point_embeddings[2].weight + # point_embedding[labels == 3] += self.point_embeddings[3].weight + + point_embedding = torch.where( + (labels == -1).unsqueeze(-1).expand_as(point_embedding), + torch.zeros_like(point_embedding) + self.not_a_point_embed.weight, + point_embedding, + ) + point_embedding = torch.where( + (labels == 0).unsqueeze(-1).expand_as(point_embedding), + point_embedding + self.point_embeddings[0].weight, + point_embedding, + ) + point_embedding = torch.where( + (labels == 1).unsqueeze(-1).expand_as(point_embedding), + point_embedding + self.point_embeddings[1].weight, + point_embedding, + ) + point_embedding = torch.where( + (labels == 2).unsqueeze(-1).expand_as(point_embedding), + point_embedding + self.point_embeddings[2].weight, + point_embedding, + ) + point_embedding = torch.where( + (labels == 3).unsqueeze(-1).expand_as(point_embedding), + point_embedding + self.point_embeddings[3].weight, + point_embedding, + ) + + return point_embedding + + def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor: + """Embeds box prompts.""" + boxes = boxes + 0.5 # Shift to center of pixel + coords = boxes.reshape(-1, 2, 2) + corner_embedding = self.pe_layer.forward_with_coords( + coords, self.input_image_size + ) + corner_embedding[:, 0, :] += self.point_embeddings[2].weight + corner_embedding[:, 1, :] += self.point_embeddings[3].weight + return corner_embedding + + def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor: + """Embeds mask inputs.""" + mask_embedding = self.mask_downscaling(masks) + return mask_embedding + + def _get_batch_size( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> int: + """ + Gets the batch size of the output given the batch size of the input prompts. + """ + if points is not None: + return points[0].shape[0] + elif boxes is not None: + return boxes.shape[0] + elif masks is not None: + return masks.shape[0] + else: + return 1 + + def _get_device(self) -> torch.device: + return self.point_embeddings[0].weight.device + + def forward( + self, + points: Optional[Tuple[torch.Tensor, torch.Tensor]], + boxes: Optional[torch.Tensor], + masks: Optional[torch.Tensor], + ) -> Tuple[torch.Tensor, torch.Tensor]: + """ + Embeds different types of prompts, returning both sparse and dense + embeddings. + + Arguments: + points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates + and labels to embed. + boxes (torch.Tensor or none): boxes to embed + masks (torch.Tensor or none): masks to embed + + Returns: + torch.Tensor: sparse embeddings for the points and boxes, with shape + BxNx(embed_dim), where N is determined by the number of input points + and boxes. + torch.Tensor: dense embeddings for the masks, in the shape + Bx(embed_dim)x(embed_H)x(embed_W) + """ + # if boxes is not None: + # raise ValueError("Currently do not support boxes. " + # "Please create an issue on pytorch/ao.") + # if masks is not None: + # raise ValueError("Currently do not support masks. " + # "Please create an issue on pytorch/ao.") + bs = self._get_batch_size(points, boxes, masks) + sparse_embeddings = torch.empty( + (bs, 0, self.embed_dim), device=self._get_device() + ) + if points is not None: + coords, labels = points + point_embeddings = self._embed_points(coords, labels, pad=(boxes is None)) + sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1) + if boxes is not None: + box_embeddings = self._embed_boxes(boxes) + sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1) + + if masks is not None: + dense_embeddings = self._embed_masks(masks) + else: + dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand( + bs, -1, self.image_embedding_size[0], self.image_embedding_size[1] + ) + + return sparse_embeddings, dense_embeddings diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/transformer.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..634bb52278b03d89b30887042b98f2185dd2908d --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam/transformer.py @@ -0,0 +1,373 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import contextlib +import math +import warnings +from functools import partial +from typing import Tuple, Type + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +from torchao._models.sam2.modeling.position_encoding import ( + apply_rotary_enc, + compute_axial_cis, +) +from torchao._models.sam2.modeling.sam2_utils import MLP +from torchao._models.sam2.utils.misc import get_sdpa_settings + +warnings.simplefilter(action="ignore", category=FutureWarning) +# Check whether Flash Attention is available (and use it by default) +OLD_GPU, USE_FLASH_ATTN, MATH_KERNEL_ON = get_sdpa_settings() +# A fallback setting to allow all available kernels if Flash Attention fails +ALLOW_ALL_KERNELS = False + + +def sdp_kernel_context(dropout_p): + """ + Get the context for the attention scaled dot-product kernel. We use Flash Attention + by default, but fall back to all available kernels if Flash Attention fails. + """ + if ALLOW_ALL_KERNELS: + return contextlib.nullcontext() + + return torch.backends.cuda.sdp_kernel( + enable_flash=USE_FLASH_ATTN, + # if Flash attention kernel is off, then math kernel needs to be enabled + enable_math=(OLD_GPU and dropout_p > 0.0) or MATH_KERNEL_ON, + enable_mem_efficient=OLD_GPU, + ) + + +class TwoWayTransformer(nn.Module): + def __init__( + self, + depth: int, + embedding_dim: int, + num_heads: int, + mlp_dim: int, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + ) -> None: + """ + A transformer decoder that attends to an input image using + queries whose positional embedding is supplied. + + Args: + depth (int): number of layers in the transformer + embedding_dim (int): the channel dimension for the input embeddings + num_heads (int): the number of heads for multihead attention. Must + divide embedding_dim + mlp_dim (int): the channel dimension internal to the MLP block + activation (nn.Module): the activation to use in the MLP block + """ + super().__init__() + self.depth = depth + self.embedding_dim = embedding_dim + self.num_heads = num_heads + self.mlp_dim = mlp_dim + self.layers = nn.ModuleList() + + for i in range(depth): + self.layers.append( + TwoWayAttentionBlock( + embedding_dim=embedding_dim, + num_heads=num_heads, + mlp_dim=mlp_dim, + activation=activation, + attention_downsample_rate=attention_downsample_rate, + skip_first_layer_pe=(i == 0), + ) + ) + + self.final_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm_final_attn = nn.LayerNorm(embedding_dim) + + def forward( + self, + image_embedding: Tensor, + image_pe: Tensor, + point_embedding: Tensor, + ) -> Tuple[Tensor, Tensor]: + """ + Args: + image_embedding (torch.Tensor): image to attend to. Should be shape + B x embedding_dim x h x w for any h and w. + image_pe (torch.Tensor): the positional encoding to add to the image. Must + have the same shape as image_embedding. + point_embedding (torch.Tensor): the embedding to add to the query points. + Must have shape B x N_points x embedding_dim for any N_points. + + Returns: + torch.Tensor: the processed point_embedding + torch.Tensor: the processed image_embedding + """ + # BxCxHxW -> BxHWxC == B x N_image_tokens x C + bs, c, h, w = image_embedding.shape + image_embedding = image_embedding.flatten(2).permute(0, 2, 1) + image_pe = image_pe.flatten(2).permute(0, 2, 1) + + # Prepare queries + queries = point_embedding + keys = image_embedding + + # Apply transformer blocks and final layernorm + for layer in self.layers: + queries, keys = layer( + queries=queries, + keys=keys, + query_pe=point_embedding, + key_pe=image_pe, + ) + + # Apply the final attention layer from the points to the image + q = queries + point_embedding + k = keys + image_pe + attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm_final_attn(queries) + + return queries, keys + + +class TwoWayAttentionBlock(nn.Module): + def __init__( + self, + embedding_dim: int, + num_heads: int, + mlp_dim: int = 2048, + activation: Type[nn.Module] = nn.ReLU, + attention_downsample_rate: int = 2, + skip_first_layer_pe: bool = False, + ) -> None: + """ + A transformer block with four layers: (1) self-attention of sparse + inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp + block on sparse inputs, and (4) cross attention of dense inputs to sparse + inputs. + + Arguments: + embedding_dim (int): the channel dimension of the embeddings + num_heads (int): the number of heads in the attention layers + mlp_dim (int): the hidden dimension of the mlp block + activation (nn.Module): the activation of the mlp block + skip_first_layer_pe (bool): skip the PE on the first layer + """ + super().__init__() + self.self_attn = Attention(embedding_dim, num_heads) + self.norm1 = nn.LayerNorm(embedding_dim) + + self.cross_attn_token_to_image = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + self.norm2 = nn.LayerNorm(embedding_dim) + + self.mlp = MLP( + embedding_dim, mlp_dim, embedding_dim, num_layers=2, activation=activation + ) + self.norm3 = nn.LayerNorm(embedding_dim) + + self.norm4 = nn.LayerNorm(embedding_dim) + self.cross_attn_image_to_token = Attention( + embedding_dim, num_heads, downsample_rate=attention_downsample_rate + ) + + self.skip_first_layer_pe = skip_first_layer_pe + + def forward( + self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor + ) -> Tuple[Tensor, Tensor]: + # Self attention block + if self.skip_first_layer_pe: + queries = self.self_attn(q=queries, k=queries, v=queries) + else: + q = queries + query_pe + attn_out = self.self_attn(q=q, k=q, v=queries) + queries = queries + attn_out + queries = self.norm1(queries) + + # Cross attention block, tokens attending to image embedding + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys) + queries = queries + attn_out + queries = self.norm2(queries) + + # MLP block + mlp_out = self.mlp(queries) + queries = queries + mlp_out + queries = self.norm3(queries) + + # Cross attention block, image embedding attending to tokens + q = queries + query_pe + k = keys + key_pe + attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries) + keys = keys + attn_out + keys = self.norm4(keys) + + return queries, keys + + +class Attention(nn.Module): + """ + An attention layer that allows for downscaling the size of the embedding + after projection to queries, keys, and values. + """ + + def __init__( + self, + embedding_dim: int, + num_heads: int, + downsample_rate: int = 1, + dropout: float = 0.0, + kv_in_dim: int = None, + ) -> None: + super().__init__() + self.embedding_dim = embedding_dim + self.kv_in_dim = kv_in_dim if kv_in_dim is not None else embedding_dim + self.internal_dim = embedding_dim // downsample_rate + self.num_heads = num_heads + assert self.internal_dim % num_heads == 0, ( + "num_heads must divide embedding_dim." + ) + + self.q_proj = nn.Linear(embedding_dim, self.internal_dim) + self.k_proj = nn.Linear(self.kv_in_dim, self.internal_dim) + self.v_proj = nn.Linear(self.kv_in_dim, self.internal_dim) + self.out_proj = nn.Linear(self.internal_dim, embedding_dim) + + self.dropout_p = dropout + + def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor: + b, n, c = x.shape + x = x.reshape(b, n, num_heads, c // num_heads) + return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head + + def _recombine_heads(self, x: Tensor) -> Tensor: + b, n_heads, n_tokens, c_per_head = x.shape + x = x.transpose(1, 2) + return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C + + def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + dropout_p = self.dropout_p if self.training else 0.0 + # # Attention + # try: + # with sdp_kernel_context(dropout_p): + # out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p) + # except Exception as e: + # # Fall back to all kernels if the Flash attention kernel fails + # warnings.warn( + # f"Flash Attention kernel failed due to: {e}\nFalling back to all available " + # f"kernels for scaled_dot_product_attention (which may have a slower speed).", + # category=UserWarning, + # stacklevel=2, + # ) + # global ALLOW_ALL_KERNELS + # ALLOW_ALL_KERNELS = True + # out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p) + # TODO: This scale should not be needed. But without it compile causes a NaN. + out = F.scaled_dot_product_attention( + q, k, v, dropout_p=dropout_p, scale=(1.0 / math.sqrt(q.size(-1))) + ) + + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out + + +class RoPEAttention(Attention): + """Attention with rotary position encoding.""" + + def __init__( + self, + *args, + rope_theta=10000.0, + # whether to repeat q rope to match k length + # this is needed for cross-attention to memories + rope_k_repeat=False, + feat_sizes=(32, 32), # [w, h] for stride 16 feats at 512 resolution + **kwargs, + ): + super().__init__(*args, **kwargs) + + self.compute_cis = partial( + compute_axial_cis, dim=self.internal_dim // self.num_heads, theta=rope_theta + ) + freqs_cis = self.compute_cis(end_x=feat_sizes[0], end_y=feat_sizes[1]) + self.freqs_cis = freqs_cis + self.rope_k_repeat = rope_k_repeat + + def forward( + self, q: Tensor, k: Tensor, v: Tensor, num_k_exclude_rope: int = 0 + ) -> Tensor: + # Input projections + q = self.q_proj(q) + k = self.k_proj(k) + v = self.v_proj(v) + + # Separate into heads + q = self._separate_heads(q, self.num_heads) + k = self._separate_heads(k, self.num_heads) + v = self._separate_heads(v, self.num_heads) + + # Apply rotary position encoding + w = h = math.sqrt(q.shape[-2]) + # NOTE: Disabling this. + # self.freqs_cis = self.freqs_cis.to(q.device) + if self.freqs_cis.shape[0] != q.shape[-2]: + self.freqs_cis = self.compute_cis( + end_x=w, end_y=h, device=q.device + ) # .to(q.device) + if q.shape[-2] != k.shape[-2]: + assert self.rope_k_repeat + + num_k_rope = k.size(-2) - num_k_exclude_rope + q, k[:, :, :num_k_rope] = apply_rotary_enc( + q, + k[:, :, :num_k_rope], + freqs_cis=self.freqs_cis, + repeat_freqs_k=self.rope_k_repeat, + ) + + dropout_p = self.dropout_p if self.training else 0.0 + # # Attention + # try: + # with sdp_kernel_context(dropout_p): + # out = F.scaled_dot_product_attention(q, k, v, dropout_p=dropout_p) + # except Exception as e: + # # Fall back to all kernels if the Flash attention kernel fails + # warnings.warn( + # f"Flash Attention kernel failed due to: {e}\nFalling back to all available " + # f"kernels for scaled_dot_product_attention (which may have a slower speed).", + # category=UserWarning, + # stacklevel=2, + # ) + # global ALLOW_ALL_KERNELS + # ALLOW_ALL_KERNELS = True + # TODO: This scale should not be needed. But without it compile causes a NaN. + out = F.scaled_dot_product_attention( + q, k, v, dropout_p=dropout_p, scale=(1.0 / math.sqrt(q.size(-1))) + ) + + out = self._recombine_heads(out) + out = self.out_proj(out) + + return out diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam2_base.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam2_base.py new file mode 100644 index 0000000000000000000000000000000000000000..a16fe8dd616c227544577e9c2ebbc65d592d5af2 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam2_base.py @@ -0,0 +1,929 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import torch +import torch.distributed +import torch.nn.functional as F +from torch.nn.init import trunc_normal_ + +from torchao._models.sam2.modeling.sam.mask_decoder import MaskDecoder +from torchao._models.sam2.modeling.sam.prompt_encoder import PromptEncoder +from torchao._models.sam2.modeling.sam.transformer import TwoWayTransformer +from torchao._models.sam2.modeling.sam2_utils import ( + MLP, + get_1d_sine_pe, + select_closest_cond_frames, +) + +# a large negative value as a placeholder score for missing objects +NO_OBJ_SCORE = -1024.0 + + +class SAM2Base(torch.nn.Module): + def __init__( + self, + image_encoder, + memory_attention, + memory_encoder, + num_maskmem=7, # default 1 input frame + 6 previous frames + image_size=512, + backbone_stride=16, # stride of the image backbone output + sigmoid_scale_for_mem_enc=1.0, # scale factor for mask sigmoid prob + sigmoid_bias_for_mem_enc=0.0, # bias factor for mask sigmoid prob + # During evaluation, whether to binarize the sigmoid mask logits on interacted frames with clicks + binarize_mask_from_pts_for_mem_enc=False, + 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 + # 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, + # 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 + # a temporal locality when handling a large number of annotated frames (since closer frames should be more important) and also avoids GPU OOM. + max_cond_frames_in_attn=-1, + # on the first frame, whether to directly add the no-memory embedding to the image feature + # (instead of using the transformer encoder) + directly_add_no_mem_embed=False, + # whether to use high-resolution feature maps in the SAM mask decoder + use_high_res_features_in_sam=False, + # whether to output multiple (3) masks for the first click on initial conditioning frames + multimask_output_in_sam=False, + # the minimum and maximum number of clicks to use multimask_output_in_sam (only relevant when `multimask_output_in_sam=True`; + # default is 1 for both, meaning that only the first click gives multimask output; also note that a box counts as two points) + multimask_min_pt_num=1, + multimask_max_pt_num=1, + # 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`) + multimask_output_for_tracking=False, + # Whether to use multimask tokens for obj ptr; Only relevant when both + # use_obj_ptrs_in_encoder=True and multimask_output_for_tracking=True + use_multimask_token_for_obj_ptr: bool = False, + # whether to use sigmoid to restrict ious prediction to [0-1] + iou_prediction_use_sigmoid=False, + # The memory bank's temporal stride during evaluation (i.e. the `r` parameter in XMem and Cutie; XMem and Cutie use r=5). + # For r>1, the (self.num_maskmem - 1) non-conditioning memory frames consist of + # (self.num_maskmem - 2) nearest frames from every r-th frames, plus the last frame. + memory_temporal_stride_for_eval=1, + # whether to apply non-overlapping constraints on the object masks in the memory encoder during evaluation (to avoid/alleviate superposing masks) + non_overlap_masks_for_mem_enc=False, + # whether to cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder=False, + # the maximum number of object pointers from other frames in encoder cross attention (only relevant when `use_obj_ptrs_in_encoder=True`) + max_obj_ptrs_in_encoder=16, + # whether to add temporal positional encoding to the object pointers in the encoder (only relevant when `use_obj_ptrs_in_encoder=True`) + add_tpos_enc_to_obj_ptrs=True, + # whether to add an extra linear projection layer for the temporal positional encoding in the object pointers to avoid potential interference + # with spatial positional encoding (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`) + proj_tpos_enc_in_obj_ptrs=False, + # whether to use signed distance (instead of unsigned absolute distance) in the temporal positional encoding in the object pointers + # (only relevant when both `use_obj_ptrs_in_encoder=True` and `add_tpos_enc_to_obj_ptrs=True`) + use_signed_tpos_enc_to_obj_ptrs=False, + # whether to only attend to object pointers in the past (before the current frame) in the encoder during evaluation + # (only relevant when `use_obj_ptrs_in_encoder=True`; this might avoid pointer information too far in the future to distract the initial tracking) + only_obj_ptrs_in_the_past_for_eval=False, + # Whether to predict if there is an object in the frame + pred_obj_scores: bool = False, + # Whether to use an MLP to predict object scores + pred_obj_scores_mlp: bool = False, + # Only relevant if pred_obj_scores=True and use_obj_ptrs_in_encoder=True; + # Whether to have a fixed no obj pointer when there is no object present + # or to use it as an additive embedding with obj_ptr produced by decoder + fixed_no_obj_ptr: bool = False, + # Soft no object, i.e. mix in no_obj_ptr softly, + # hope to make recovery easier if there is a mistake and mitigate accumulation of errors + soft_no_obj_ptr: bool = False, + use_mlp_for_obj_ptr_proj: bool = False, + # add no obj embedding to spatial frames + no_obj_embed_spatial: bool = False, + # 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. + sam_mask_decoder_extra_args=None, + compile_image_encoder: bool = False, + ): + super().__init__() + + # Part 1: the image backbone + self.image_encoder = image_encoder + # Use level 0, 1, 2 for high-res setting, or just level 2 for the default setting + self.use_high_res_features_in_sam = use_high_res_features_in_sam + self.num_feature_levels = 3 if use_high_res_features_in_sam else 1 + self.use_obj_ptrs_in_encoder = use_obj_ptrs_in_encoder + self.max_obj_ptrs_in_encoder = max_obj_ptrs_in_encoder + if use_obj_ptrs_in_encoder: + # A conv layer to downsample the mask prompt to stride 4 (the same stride as + # low-res SAM mask logits) and to change its scales from 0~1 to SAM logit scale, + # so that it can be fed into the SAM mask decoder to generate a pointer. + self.mask_downsample = torch.nn.Conv2d(1, 1, kernel_size=4, stride=4) + self.add_tpos_enc_to_obj_ptrs = add_tpos_enc_to_obj_ptrs + if proj_tpos_enc_in_obj_ptrs: + assert add_tpos_enc_to_obj_ptrs # these options need to be used together + self.proj_tpos_enc_in_obj_ptrs = proj_tpos_enc_in_obj_ptrs + self.use_signed_tpos_enc_to_obj_ptrs = use_signed_tpos_enc_to_obj_ptrs + self.only_obj_ptrs_in_the_past_for_eval = only_obj_ptrs_in_the_past_for_eval + + # Part 2: memory attention to condition current frame's visual features + # with memories (and obj ptrs) from past frames + self.memory_attention = memory_attention + self.hidden_dim = image_encoder.neck.d_model + + # Part 3: memory encoder for the previous frame's outputs + self.memory_encoder = memory_encoder + self.mem_dim = self.hidden_dim + if hasattr(self.memory_encoder, "out_proj") and hasattr( + self.memory_encoder.out_proj, "weight" + ): + # if there is compression of memories along channel dim + self.mem_dim = self.memory_encoder.out_proj.weight.shape[0] + self.num_maskmem = num_maskmem # Number of memories accessible + # Temporal encoding of the memories + self.maskmem_tpos_enc = torch.nn.Parameter( + torch.zeros(num_maskmem, 1, 1, self.mem_dim) + ) + trunc_normal_(self.maskmem_tpos_enc, std=0.02) + # a single token to indicate no memory embedding from previous frames + self.no_mem_embed = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) + self.no_mem_pos_enc = torch.nn.Parameter(torch.zeros(1, 1, self.hidden_dim)) + trunc_normal_(self.no_mem_embed, std=0.02) + trunc_normal_(self.no_mem_pos_enc, std=0.02) + self.directly_add_no_mem_embed = directly_add_no_mem_embed + # Apply sigmoid to the output raw mask logits (to turn them from + # range (-inf, +inf) to range (0, 1)) before feeding them into the memory encoder + self.sigmoid_scale_for_mem_enc = sigmoid_scale_for_mem_enc + self.sigmoid_bias_for_mem_enc = sigmoid_bias_for_mem_enc + self.binarize_mask_from_pts_for_mem_enc = binarize_mask_from_pts_for_mem_enc + self.non_overlap_masks_for_mem_enc = non_overlap_masks_for_mem_enc + self.memory_temporal_stride_for_eval = memory_temporal_stride_for_eval + # On frames with mask input, whether to directly output the input mask without + # using a SAM prompt encoder + mask decoder + self.use_mask_input_as_output_without_sam = use_mask_input_as_output_without_sam + self.multimask_output_in_sam = multimask_output_in_sam + self.multimask_min_pt_num = multimask_min_pt_num + self.multimask_max_pt_num = multimask_max_pt_num + self.multimask_output_for_tracking = multimask_output_for_tracking + self.use_multimask_token_for_obj_ptr = use_multimask_token_for_obj_ptr + self.iou_prediction_use_sigmoid = iou_prediction_use_sigmoid + + # Part 4: SAM-style prompt encoder (for both mask and point inputs) + # and SAM-style mask decoder for the final mask output + self.image_size = image_size + self.backbone_stride = backbone_stride + self.sam_mask_decoder_extra_args = sam_mask_decoder_extra_args + self.pred_obj_scores = pred_obj_scores + self.pred_obj_scores_mlp = pred_obj_scores_mlp + self.fixed_no_obj_ptr = fixed_no_obj_ptr + self.soft_no_obj_ptr = soft_no_obj_ptr + if self.fixed_no_obj_ptr: + assert self.pred_obj_scores + assert self.use_obj_ptrs_in_encoder + if self.pred_obj_scores and self.use_obj_ptrs_in_encoder: + self.no_obj_ptr = torch.nn.Parameter(torch.zeros(1, self.hidden_dim)) + trunc_normal_(self.no_obj_ptr, std=0.02) + self.use_mlp_for_obj_ptr_proj = use_mlp_for_obj_ptr_proj + self.no_obj_embed_spatial = None + if no_obj_embed_spatial: + self.no_obj_embed_spatial = torch.nn.Parameter(torch.zeros(1, self.mem_dim)) + trunc_normal_(self.no_obj_embed_spatial, std=0.02) + + self._build_sam_heads() + self.max_cond_frames_in_attn = max_cond_frames_in_attn + + # Model compilation + if compile_image_encoder: + # Compile the forward function (not the full module) to allow loading checkpoints. + print( + "Image encoder compilation is enabled. First forward pass will be slow." + ) + self.image_encoder.forward = torch.compile( + self.image_encoder.forward, + mode="max-autotune", + fullgraph=True, + dynamic=False, + ) + + @property + def device(self): + return next(self.parameters()).device + + def forward(self, *args, **kwargs): + raise NotImplementedError( + "Please use the corresponding methods in SAM2VideoPredictor for inference or SAM2Train for training/fine-tuning" + "See notebooks/video_predictor_example.ipynb for an inference example." + ) + + def _build_sam_heads(self): + """Build SAM-style prompt encoder and mask decoder.""" + self.sam_prompt_embed_dim = self.hidden_dim + self.sam_image_embedding_size = self.image_size // self.backbone_stride + + # build PromptEncoder and MaskDecoder from SAM + # (their hyperparameters like `mask_in_chans=16` are from SAM code) + self.sam_prompt_encoder = PromptEncoder( + embed_dim=self.sam_prompt_embed_dim, + image_embedding_size=( + self.sam_image_embedding_size, + self.sam_image_embedding_size, + ), + input_image_size=(self.image_size, self.image_size), + mask_in_chans=16, + ) + self.sam_mask_decoder = MaskDecoder( + num_multimask_outputs=3, + transformer=TwoWayTransformer( + depth=2, + embedding_dim=self.sam_prompt_embed_dim, + mlp_dim=2048, + num_heads=8, + ), + transformer_dim=self.sam_prompt_embed_dim, + iou_head_depth=3, + iou_head_hidden_dim=256, + use_high_res_features=self.use_high_res_features_in_sam, + iou_prediction_use_sigmoid=self.iou_prediction_use_sigmoid, + pred_obj_scores=self.pred_obj_scores, + pred_obj_scores_mlp=self.pred_obj_scores_mlp, + use_multimask_token_for_obj_ptr=self.use_multimask_token_for_obj_ptr, + **(self.sam_mask_decoder_extra_args or {}), + ) + if self.use_obj_ptrs_in_encoder: + # a linear projection on SAM output tokens to turn them into object pointers + self.obj_ptr_proj = torch.nn.Linear(self.hidden_dim, self.hidden_dim) + if self.use_mlp_for_obj_ptr_proj: + self.obj_ptr_proj = MLP( + self.hidden_dim, self.hidden_dim, self.hidden_dim, 3 + ) + else: + self.obj_ptr_proj = torch.nn.Identity() + if self.proj_tpos_enc_in_obj_ptrs: + # a linear projection on temporal positional encoding in object pointers to + # avoid potential interference with spatial positional encoding + self.obj_ptr_tpos_proj = torch.nn.Linear(self.hidden_dim, self.mem_dim) + else: + self.obj_ptr_tpos_proj = torch.nn.Identity() + + def _forward_sam_heads( + self, + backbone_features, + point_inputs=None, + mask_inputs=None, + high_res_features=None, + multimask_output=False, + ): + """ + Forward SAM prompt encoders and mask heads. + + Inputs: + - backbone_features: image features of [B, C, H, W] shape + - point_inputs: a dictionary with "point_coords" and "point_labels", where + 1) "point_coords" has [B, P, 2] shape and float32 dtype and contains the + absolute pixel-unit coordinate in (x, y) format of the P input points + 2) "point_labels" has shape [B, P] and int32 dtype, where 1 means + positive clicks, 0 means negative clicks, and -1 means padding + - mask_inputs: a mask of [B, 1, H*16, W*16] shape, float or bool, with the + same spatial size as the image. + - high_res_features: either 1) None or 2) or a list of length 2 containing + two feature maps of [B, C, 4*H, 4*W] and [B, C, 2*H, 2*W] shapes respectively, + which will be used as high-resolution feature maps for SAM decoder. + - multimask_output: if it's True, we output 3 candidate masks and their 3 + corresponding IoU estimates, and if it's False, we output only 1 mask and + its corresponding IoU estimate. + + Outputs: + - low_res_multimasks: [B, M, H*4, W*4] shape (where M = 3 if + `multimask_output=True` and M = 1 if `multimask_output=False`), the SAM + output mask logits (before sigmoid) for the low-resolution masks, with 4x + the resolution (1/4 stride) of the input backbone_features. + - high_res_multimasks: [B, M, H*16, W*16] shape (where M = 3 + if `multimask_output=True` and M = 1 if `multimask_output=False`), + upsampled from the low-resolution masks, with shape size as the image + (stride is 1 pixel). + - ious, [B, M] shape, where (where M = 3 if `multimask_output=True` and M = 1 + if `multimask_output=False`), the estimated IoU of each output mask. + - low_res_masks: [B, 1, H*4, W*4] shape, the best mask in `low_res_multimasks`. + If `multimask_output=True`, it's the mask with the highest IoU estimate. + If `multimask_output=False`, it's the same as `low_res_multimasks`. + - high_res_masks: [B, 1, H*16, W*16] shape, the best mask in `high_res_multimasks`. + If `multimask_output=True`, it's the mask with the highest IoU estimate. + If `multimask_output=False`, it's the same as `high_res_multimasks`. + - obj_ptr: [B, C] shape, the object pointer vector for the output mask, extracted + based on the output token from the SAM mask decoder. + """ + B = backbone_features.size(0) + device = backbone_features.device + assert backbone_features.size(1) == self.sam_prompt_embed_dim + assert backbone_features.size(2) == self.sam_image_embedding_size + assert backbone_features.size(3) == self.sam_image_embedding_size + + # a) Handle point prompts + if point_inputs is not None: + sam_point_coords = point_inputs["point_coords"] + sam_point_labels = point_inputs["point_labels"] + assert sam_point_coords.size(0) == B and sam_point_labels.size(0) == B + else: + # If no points are provide, pad with an empty point (with label -1) + sam_point_coords = torch.zeros(B, 1, 2, device=device) + sam_point_labels = -torch.ones(B, 1, dtype=torch.int32, device=device) + + # b) Handle mask prompts + if mask_inputs is not None: + # If mask_inputs is provided, downsize it into low-res mask input if needed + # and feed it as a dense mask prompt into the SAM mask encoder + assert len(mask_inputs.shape) == 4 and mask_inputs.shape[:2] == (B, 1) + if mask_inputs.shape[-2:] != self.sam_prompt_encoder.mask_input_size: + sam_mask_prompt = F.interpolate( + mask_inputs.float(), + size=self.sam_prompt_encoder.mask_input_size, + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + else: + sam_mask_prompt = mask_inputs + else: + # Otherwise, simply feed None (and SAM's prompt encoder will add + # a learned `no_mask_embed` to indicate no mask input in this case). + sam_mask_prompt = None + + sparse_embeddings, dense_embeddings = self.sam_prompt_encoder( + points=(sam_point_coords, sam_point_labels), + boxes=None, + masks=sam_mask_prompt, + ) + ( + low_res_multimasks, + ious, + sam_output_tokens, + object_score_logits, + ) = self.sam_mask_decoder( + image_embeddings=backbone_features, + image_pe=self.sam_prompt_encoder.get_dense_pe(), + sparse_prompt_embeddings=sparse_embeddings, + dense_prompt_embeddings=dense_embeddings, + multimask_output=multimask_output, + repeat_image=False, # the image is already batched + high_res_features=high_res_features, + ) + if self.pred_obj_scores: + is_obj_appearing = object_score_logits > 0 + + # Mask used for spatial memories is always a *hard* choice between obj and no obj, + # consistent with the actual mask prediction + low_res_multimasks = torch.where( + is_obj_appearing[:, None, None], + low_res_multimasks, + NO_OBJ_SCORE, + ) + + # convert masks from possibly bfloat16 (or float16) to float32 + # (older PyTorch versions before 2.1 don't support `interpolate` on bf16) + low_res_multimasks = low_res_multimasks.float() + high_res_multimasks = F.interpolate( + low_res_multimasks, + size=(self.image_size, self.image_size), + mode="bilinear", + align_corners=False, + ) + + sam_output_token = sam_output_tokens[:, 0] + if multimask_output: + # take the best mask prediction (with the highest IoU estimation) + best_iou_inds = torch.argmax(ious, dim=-1) + batch_inds = torch.arange(B, device=device) + low_res_masks = low_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1) + high_res_masks = high_res_multimasks[batch_inds, best_iou_inds].unsqueeze(1) + if sam_output_tokens.size(1) > 1: + sam_output_token = sam_output_tokens[batch_inds, best_iou_inds] + else: + low_res_masks, high_res_masks = low_res_multimasks, high_res_multimasks + + # Extract object pointer from the SAM output token (with occlusion handling) + obj_ptr = self.obj_ptr_proj(sam_output_token) + if self.pred_obj_scores: + # Allow *soft* no obj ptr, unlike for masks + if self.soft_no_obj_ptr: + lambda_is_obj_appearing = object_score_logits.sigmoid() + else: + lambda_is_obj_appearing = is_obj_appearing.float() + + if self.fixed_no_obj_ptr: + obj_ptr = lambda_is_obj_appearing * obj_ptr + obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr + + return ( + low_res_multimasks, + high_res_multimasks, + ious, + low_res_masks, + high_res_masks, + obj_ptr, + object_score_logits, + ) + + def _use_mask_as_output(self, backbone_features, high_res_features, mask_inputs): + """ + Directly turn binary `mask_inputs` into a output mask logits without using SAM. + (same input and output shapes as in _forward_sam_heads above). + """ + # Use -10/+10 as logits for neg/pos pixels (very close to 0/1 in prob after sigmoid). + out_scale, out_bias = 20.0, -10.0 # sigmoid(-10.0)=4.5398e-05 + mask_inputs_float = mask_inputs.float() + high_res_masks = mask_inputs_float * out_scale + out_bias + low_res_masks = F.interpolate( + high_res_masks, + size=(high_res_masks.size(-2) // 4, high_res_masks.size(-1) // 4), + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + # a dummy IoU prediction of all 1's under mask input + ious = mask_inputs.new_ones(mask_inputs.size(0), 1).float() + if not self.use_obj_ptrs_in_encoder: + # all zeros as a dummy object pointer (of shape [B, C]) + obj_ptr = torch.zeros( + mask_inputs.size(0), self.hidden_dim, device=mask_inputs.device + ) + else: + # produce an object pointer using the SAM decoder from the mask input + _, _, _, _, _, obj_ptr, _ = self._forward_sam_heads( + backbone_features=backbone_features, + mask_inputs=self.mask_downsample(mask_inputs_float), + high_res_features=high_res_features, + ) + # In this method, we are treating mask_input as output, e.g. using it directly to create spatial mem; + # Below, we follow the same design axiom to use mask_input to decide if obj appears or not instead of relying + # on the object_scores from the SAM decoder. + is_obj_appearing = torch.any(mask_inputs.flatten(1).float() > 0.0, dim=1) + is_obj_appearing = is_obj_appearing[..., None] + lambda_is_obj_appearing = is_obj_appearing.float() + object_score_logits = out_scale * lambda_is_obj_appearing + out_bias + if self.pred_obj_scores: + if self.fixed_no_obj_ptr: + obj_ptr = lambda_is_obj_appearing * obj_ptr + obj_ptr = obj_ptr + (1 - lambda_is_obj_appearing) * self.no_obj_ptr + + return ( + low_res_masks, + high_res_masks, + ious, + low_res_masks, + high_res_masks, + obj_ptr, + object_score_logits, + ) + + def forward_image(self, img_batch: torch.Tensor): + """Get the image feature on the input batch.""" + backbone_out = self.image_encoder(img_batch) + if self.use_high_res_features_in_sam: + # precompute projected level 0 and level 1 features in SAM decoder + # to avoid running it again on every SAM click + # NOTE: These are 1x1 convolutions + backbone_out["backbone_fpn"][0] = self.sam_mask_decoder.conv_s0( + backbone_out["backbone_fpn"][0] + ) + backbone_out["backbone_fpn"][1] = self.sam_mask_decoder.conv_s1( + backbone_out["backbone_fpn"][1] + ) + return backbone_out + + def _prepare_backbone_features(self, backbone_out): + """Prepare and flatten visual features.""" + backbone_out = backbone_out.copy() + assert len(backbone_out["backbone_fpn"]) == len(backbone_out["vision_pos_enc"]) + assert len(backbone_out["backbone_fpn"]) >= self.num_feature_levels + + feature_maps = backbone_out["backbone_fpn"][-self.num_feature_levels :] + vision_pos_embeds = backbone_out["vision_pos_enc"][-self.num_feature_levels :] + + feat_sizes = [(x.shape[-2], x.shape[-1]) for x in vision_pos_embeds] + # flatten NxCxHxW to HWxNxC + vision_feats = [x.flatten(2).permute(2, 0, 1) for x in feature_maps] + vision_pos_embeds = [x.flatten(2).permute(2, 0, 1) for x in vision_pos_embeds] + + return backbone_out, vision_feats, vision_pos_embeds, feat_sizes + + def _prepare_memory_conditioned_features( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + output_dict, + num_frames, + track_in_reverse=False, # tracking in reverse time order (for demo usage) + ): + """Fuse the current frame's visual feature map with previous memory.""" + B = current_vision_feats[-1].size(1) # batch size on this frame + C = self.hidden_dim + H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size + device = current_vision_feats[-1].device + # The case of `self.num_maskmem == 0` below is primarily used for reproducing SAM on images. + # In this case, we skip the fusion with any memory. + if self.num_maskmem == 0: # Disable memory and skip fusion + pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W) + return pix_feat + + num_obj_ptr_tokens = 0 + tpos_sign_mul = -1 if track_in_reverse else 1 + # Step 1: condition the visual features of the current frame on previous memories + if not is_init_cond_frame: + # Retrieve the memories encoded with the maskmem backbone + to_cat_memory, to_cat_memory_pos_embed = [], [] + # Add conditioning frames's output first (all cond frames have t_pos=0 for + # when getting temporal positional embedding below) + assert len(output_dict["cond_frame_outputs"]) > 0 + # Select a maximum number of temporally closest cond frames for cross attention + cond_outputs = output_dict["cond_frame_outputs"] + selected_cond_outputs, unselected_cond_outputs = select_closest_cond_frames( + frame_idx, cond_outputs, self.max_cond_frames_in_attn + ) + t_pos_and_prevs = [(0, out) for out in selected_cond_outputs.values()] + # Add last (self.num_maskmem - 1) frames before current frame for non-conditioning memory + # the earliest one has t_pos=1 and the latest one has t_pos=self.num_maskmem-1 + # We also allow taking the memory frame non-consecutively (with stride>1), in which case + # we take (self.num_maskmem - 2) frames among every stride-th frames plus the last frame. + stride = 1 if self.training else self.memory_temporal_stride_for_eval + for t_pos in range(1, self.num_maskmem): + t_rel = self.num_maskmem - t_pos # how many frames before current frame + if t_rel == 1: + # for t_rel == 1, we take the last frame (regardless of r) + if not track_in_reverse: + # the frame immediately before this frame (i.e. frame_idx - 1) + prev_frame_idx = frame_idx - t_rel + else: + # the frame immediately after this frame (i.e. frame_idx + 1) + prev_frame_idx = frame_idx + t_rel + else: + # for t_rel >= 2, we take the memory frame from every r-th frames + if not track_in_reverse: + # first find the nearest frame among every r-th frames before this frame + # for r=1, this would be (frame_idx - 2) + prev_frame_idx = ((frame_idx - 2) // stride) * stride + # then seek further among every r-th frames + prev_frame_idx = prev_frame_idx - (t_rel - 2) * stride + else: + # first find the nearest frame among every r-th frames after this frame + # for r=1, this would be (frame_idx + 2) + prev_frame_idx = -(-(frame_idx + 2) // stride) * stride + # then seek further among every r-th frames + prev_frame_idx = prev_frame_idx + (t_rel - 2) * stride + out = output_dict["non_cond_frame_outputs"].get(prev_frame_idx, None) + if out is None: + # If an unselected conditioning frame is among the last (self.num_maskmem - 1) + # frames, we still attend to it as if it's a non-conditioning frame. + out = unselected_cond_outputs.get(prev_frame_idx, None) + t_pos_and_prevs.append((t_pos, out)) + + for t_pos, prev in t_pos_and_prevs: + if prev is None: + continue # skip padding frames + # "maskmem_features" might have been offloaded to CPU in demo use cases, + # so we load it back to GPU (it's a no-op if it's already on GPU). + feats = prev["maskmem_features"].to(device, non_blocking=True) + to_cat_memory.append(feats.flatten(2).permute(2, 0, 1)) + # Spatial positional encoding (it might have been offloaded to CPU in eval) + maskmem_enc = prev["maskmem_pos_enc"][-1].to(device) + maskmem_enc = maskmem_enc.flatten(2).permute(2, 0, 1) + # Temporal positional encoding + maskmem_enc = ( + maskmem_enc + self.maskmem_tpos_enc[self.num_maskmem - t_pos - 1] + ) + to_cat_memory_pos_embed.append(maskmem_enc) + + # Construct the list of past object pointers + if self.use_obj_ptrs_in_encoder: + max_obj_ptrs_in_encoder = min(num_frames, self.max_obj_ptrs_in_encoder) + # First add those object pointers from selected conditioning frames + # (optionally, only include object pointers in the past during evaluation) + if not self.training and self.only_obj_ptrs_in_the_past_for_eval: + ptr_cond_outputs = { + t: out + for t, out in selected_cond_outputs.items() + if (t >= frame_idx if track_in_reverse else t <= frame_idx) + } + else: + ptr_cond_outputs = selected_cond_outputs + pos_and_ptrs = [ + # Temporal pos encoding contains how far away each pointer is from current frame + ( + ( + (frame_idx - t) * tpos_sign_mul + if self.use_signed_tpos_enc_to_obj_ptrs + else abs(frame_idx - t) + ), + out["obj_ptr"], + ) + for t, out in ptr_cond_outputs.items() + ] + # Add up to (max_obj_ptrs_in_encoder - 1) non-conditioning frames before current frame + for t_diff in range(1, max_obj_ptrs_in_encoder): + t = frame_idx + t_diff if track_in_reverse else frame_idx - t_diff + if t < 0 or (num_frames is not None and t >= num_frames): + break + out = output_dict["non_cond_frame_outputs"].get( + t, unselected_cond_outputs.get(t, None) + ) + if out is not None: + pos_and_ptrs.append((t_diff, out["obj_ptr"])) + # If we have at least one object pointer, add them to the across attention + if len(pos_and_ptrs) > 0: + pos_list, ptrs_list = zip(*pos_and_ptrs) + # stack object pointers along dim=0 into [ptr_seq_len, B, C] shape + obj_ptrs = torch.stack(ptrs_list, dim=0) + # a temporal positional embedding based on how far each object pointer is from + # the current frame (sine embedding normalized by the max pointer num). + if self.add_tpos_enc_to_obj_ptrs: + t_diff_max = max_obj_ptrs_in_encoder - 1 + tpos_dim = C if self.proj_tpos_enc_in_obj_ptrs else self.mem_dim + obj_pos = ( + torch.tensor(pos_list) + .pin_memory() + .to(device=device, non_blocking=True) + ) + obj_pos = get_1d_sine_pe(obj_pos / t_diff_max, dim=tpos_dim) + obj_pos = self.obj_ptr_tpos_proj(obj_pos) + obj_pos = obj_pos.unsqueeze(1).expand(-1, B, self.mem_dim) + else: + obj_pos = obj_ptrs.new_zeros(len(pos_list), B, self.mem_dim) + if self.mem_dim < C: + # split a pointer into (C // self.mem_dim) tokens for self.mem_dim < C + obj_ptrs = obj_ptrs.reshape( + -1, B, C // self.mem_dim, self.mem_dim + ) + obj_ptrs = obj_ptrs.permute(0, 2, 1, 3).flatten(0, 1) + obj_pos = obj_pos.repeat_interleave(C // self.mem_dim, dim=0) + to_cat_memory.append(obj_ptrs) + to_cat_memory_pos_embed.append(obj_pos) + num_obj_ptr_tokens = obj_ptrs.shape[0] + else: + num_obj_ptr_tokens = 0 + else: + # for initial conditioning frames, encode them without using any previous memory + if self.directly_add_no_mem_embed: + # directly add no-mem embedding (instead of using the transformer encoder) + pix_feat_with_mem = current_vision_feats[-1] + self.no_mem_embed + pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W) + return pix_feat_with_mem + + # Use a dummy token on the first frame (to avoid empty memory input to tranformer encoder) + to_cat_memory = [self.no_mem_embed.expand(1, B, self.mem_dim)] + to_cat_memory_pos_embed = [self.no_mem_pos_enc.expand(1, B, self.mem_dim)] + + # Step 2: Concatenate the memories and forward through the transformer encoder + memory = torch.cat(to_cat_memory, dim=0) + memory_pos_embed = torch.cat(to_cat_memory_pos_embed, dim=0) + + current_vision_feats = [c.clone() for c in current_vision_feats] + current_vision_pos_embeds = [c.clone() for c in current_vision_pos_embeds] + memory = memory.clone() + memory_pos_embed = memory_pos_embed.clone() + pix_feat_with_mem = self.memory_attention( + curr=current_vision_feats, + curr_pos=current_vision_pos_embeds, + memory=memory, + memory_pos=memory_pos_embed, + num_obj_ptr_tokens=num_obj_ptr_tokens, + ) + pix_feat_with_mem = pix_feat_with_mem.clone() + # reshape the output (HW)BC => BCHW + pix_feat_with_mem = pix_feat_with_mem.permute(1, 2, 0).view(B, C, H, W) + return pix_feat_with_mem + + def _encode_new_memory( + self, + current_vision_feats, + feat_sizes, + pred_masks_high_res, + object_score_logits, + is_mask_from_pts, + ): + """Encode the current image and its prediction into a memory feature.""" + B = current_vision_feats[-1].size(1) # batch size on this frame + C = self.hidden_dim + H, W = feat_sizes[-1] # top-level (lowest-resolution) feature size + # top-level feature, (HW)BC => BCHW + pix_feat = current_vision_feats[-1].permute(1, 2, 0).view(B, C, H, W) + if self.non_overlap_masks_for_mem_enc and not self.training: + # optionally, apply non-overlapping constraints to the masks (it's applied + # in the batch dimension and should only be used during eval, where all + # the objects come from the same video under batch size 1). + pred_masks_high_res = self._apply_non_overlapping_constraints( + pred_masks_high_res + ) + # scale the raw mask logits with a temperature before applying sigmoid + binarize = self.binarize_mask_from_pts_for_mem_enc and is_mask_from_pts + if binarize and not self.training: + mask_for_mem = (pred_masks_high_res > 0).float() + else: + # apply sigmoid on the raw mask logits to turn them into range (0, 1) + mask_for_mem = torch.sigmoid(pred_masks_high_res) + # apply scale and bias terms to the sigmoid probabilities + if self.sigmoid_scale_for_mem_enc != 1.0: + mask_for_mem = mask_for_mem * self.sigmoid_scale_for_mem_enc + if self.sigmoid_bias_for_mem_enc != 0.0: + mask_for_mem = mask_for_mem + self.sigmoid_bias_for_mem_enc + maskmem_out = self.memory_encoder( + pix_feat, + mask_for_mem, + skip_mask_sigmoid=True, # sigmoid already applied + ) + maskmem_features = maskmem_out["vision_features"].clone() + maskmem_pos_enc = [m.clone() for m in maskmem_out["vision_pos_enc"]] + # add a no-object embedding to the spatial memory to indicate that the frame + # is predicted to be occluded (i.e. no object is appearing in the frame) + if self.no_obj_embed_spatial is not None: + is_obj_appearing = (object_score_logits > 0).float() + maskmem_features += ( + 1 - is_obj_appearing[..., None, None] + ) * self.no_obj_embed_spatial[..., None, None].expand( + *maskmem_features.shape + ) + + return maskmem_features, maskmem_pos_enc + + def _track_step( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + point_inputs, + mask_inputs, + output_dict, + num_frames, + track_in_reverse, + prev_sam_mask_logits, + ): + current_out = {"point_inputs": point_inputs, "mask_inputs": mask_inputs} + # High-resolution feature maps for the SAM head, reshape (HW)BC => BCHW + if len(current_vision_feats) > 1: + high_res_features = [ + x.permute(1, 2, 0).view(x.size(1), x.size(2), *s) + for x, s in zip(current_vision_feats[:-1], feat_sizes[:-1]) + ] + else: + high_res_features = None + if mask_inputs is not None and self.use_mask_input_as_output_without_sam: + # When use_mask_input_as_output_without_sam=True, we directly output the mask input + # (see it as a GT mask) without using a SAM prompt encoder + mask decoder. + pix_feat = current_vision_feats[-1].permute(1, 2, 0) + pix_feat = pix_feat.view(-1, self.hidden_dim, *feat_sizes[-1]) + sam_outputs = self._use_mask_as_output( + pix_feat, high_res_features, mask_inputs + ) + else: + # fused the visual feature with previous memory features in the memory bank + pix_feat = self._prepare_memory_conditioned_features( + frame_idx=frame_idx, + is_init_cond_frame=is_init_cond_frame, + current_vision_feats=current_vision_feats[-1:], + current_vision_pos_embeds=current_vision_pos_embeds[-1:], + feat_sizes=feat_sizes[-1:], + output_dict=output_dict, + num_frames=num_frames, + track_in_reverse=track_in_reverse, + ) + # apply SAM-style segmentation head + # here we might feed previously predicted low-res SAM mask logits into the SAM mask decoder, + # e.g. in demo where such logits come from earlier interaction instead of correction sampling + # (in this case, any `mask_inputs` shouldn't reach here as they are sent to _use_mask_as_output instead) + if prev_sam_mask_logits is not None: + assert point_inputs is not None and mask_inputs is None + mask_inputs = prev_sam_mask_logits + else: + assert mask_inputs is None + multimask_output = self._use_multimask(is_init_cond_frame, point_inputs) + + assert multimask_output + if point_inputs is not None: + point_inputs = {k: point_inputs[k].contiguous() for k in point_inputs} + sam_outputs = self._forward_sam_heads( + backbone_features=pix_feat.contiguous(), + point_inputs=point_inputs, + mask_inputs=mask_inputs, + high_res_features=[h.contiguous() for h in high_res_features], + multimask_output=multimask_output, + ) + + return current_out, sam_outputs, high_res_features, pix_feat + + def _encode_memory_in_output( + self, + current_vision_feats, + feat_sizes, + point_inputs, + run_mem_encoder, + high_res_masks, + object_score_logits, + current_out, + ): + if run_mem_encoder and self.num_maskmem > 0: + high_res_masks_for_mem_enc = high_res_masks + maskmem_features, maskmem_pos_enc = self._encode_new_memory( + current_vision_feats=current_vision_feats, + feat_sizes=feat_sizes, + pred_masks_high_res=high_res_masks_for_mem_enc, + object_score_logits=object_score_logits, + is_mask_from_pts=(point_inputs is not None), + ) + current_out["maskmem_features"] = maskmem_features + current_out["maskmem_pos_enc"] = maskmem_pos_enc + else: + current_out["maskmem_features"] = None + current_out["maskmem_pos_enc"] = None + + @torch.autograd.profiler.record_function("track_step") + def track_step( + self, + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + point_inputs, + mask_inputs, + output_dict, + num_frames, + track_in_reverse=False, # tracking in reverse time order (for demo usage) + # Whether to run the memory encoder on the predicted masks. Sometimes we might want + # to skip the memory encoder with `run_mem_encoder=False`. For example, + # in demo we might call `track_step` multiple times for each user click, + # and only encode the memory when the user finalizes their clicks. And in ablation + # settings like SAM training on static images, we don't need the memory encoder. + run_mem_encoder=True, + # The previously predicted SAM mask logits (which can be fed together with new clicks in demo). + prev_sam_mask_logits=None, + ): + current_out, sam_outputs, _, _ = self._track_step( + frame_idx, + is_init_cond_frame, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + point_inputs, + mask_inputs, + output_dict, + num_frames, + track_in_reverse, + prev_sam_mask_logits, + ) + + ( + _, + _, + _, + low_res_masks, + high_res_masks, + obj_ptr, + object_score_logits, + ) = sam_outputs + + current_out["pred_masks"] = low_res_masks.clone() + current_out["pred_masks_high_res"] = high_res_masks.clone() + current_out["obj_ptr"] = obj_ptr.clone() + if not self.training: + # Only add this in inference (to avoid unused param in activation checkpointing; + # it's mainly used in the demo to encode spatial memories w/ consolidated masks) + current_out["object_score_logits"] = object_score_logits.clone() + + # Finally run the memory encoder on the predicted mask to encode + # it into a new memory feature (that can be used in future frames) + self._encode_memory_in_output( + current_vision_feats, + feat_sizes, + point_inputs, + run_mem_encoder, + high_res_masks, + object_score_logits.clone(), + current_out, + ) + + return current_out + + def _use_multimask(self, is_init_cond_frame, point_inputs): + """Whether to use multimask output in the SAM head.""" + num_pts = 0 if point_inputs is None else point_inputs["point_labels"].size(1) + multimask_output = ( + self.multimask_output_in_sam + and (is_init_cond_frame or self.multimask_output_for_tracking) + and (self.multimask_min_pt_num <= num_pts <= self.multimask_max_pt_num) + ) + return multimask_output + + def _apply_non_overlapping_constraints(self, pred_masks): + """ + Apply non-overlapping constraints to the object scores in pred_masks. Here we + keep only the highest scoring object at each spatial location in pred_masks. + """ + batch_size = pred_masks.size(0) + if batch_size == 1: + return pred_masks + + device = pred_masks.device + # "max_obj_inds": object index of the object with the highest score at each location + max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True) + # "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks` + batch_obj_inds = torch.arange(batch_size, device=device)[:, None, None, None] + keep = max_obj_inds == batch_obj_inds + # suppress overlapping regions' scores below -10.0 so that the foreground regions + # don't overlap (here sigmoid(-10.0)=4.5398e-05) + pred_masks = torch.where(keep, pred_masks, torch.clamp(pred_masks, max=-10.0)) + return pred_masks diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam2_utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam2_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..579bfc671a3f1e44a903a5d403a215321985c25b --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/modeling/sam2_utils.py @@ -0,0 +1,323 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + + +import copy +from typing import Tuple + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F + +from torchao._models.sam2.utils.misc import mask_to_box + + +def select_closest_cond_frames(frame_idx, cond_frame_outputs, max_cond_frame_num): + """ + Select up to `max_cond_frame_num` conditioning frames from `cond_frame_outputs` + that are temporally closest to the current frame at `frame_idx`. Here, we take + - a) the closest conditioning frame before `frame_idx` (if any); + - b) the closest conditioning frame after `frame_idx` (if any); + - c) any other temporally closest conditioning frames until reaching a total + of `max_cond_frame_num` conditioning frames. + + Outputs: + - selected_outputs: selected items (keys & values) from `cond_frame_outputs`. + - unselected_outputs: items (keys & values) not selected in `cond_frame_outputs`. + """ + if max_cond_frame_num == -1 or len(cond_frame_outputs) <= max_cond_frame_num: + selected_outputs = cond_frame_outputs + unselected_outputs = {} + else: + assert max_cond_frame_num >= 2, "we should allow using 2+ conditioning frames" + selected_outputs = {} + + # the closest conditioning frame before `frame_idx` (if any) + idx_before = max((t for t in cond_frame_outputs if t < frame_idx), default=None) + if idx_before is not None: + selected_outputs[idx_before] = cond_frame_outputs[idx_before] + + # the closest conditioning frame after `frame_idx` (if any) + idx_after = min((t for t in cond_frame_outputs if t >= frame_idx), default=None) + if idx_after is not None: + selected_outputs[idx_after] = cond_frame_outputs[idx_after] + + # add other temporally closest conditioning frames until reaching a total + # of `max_cond_frame_num` conditioning frames. + num_remain = max_cond_frame_num - len(selected_outputs) + inds_remain = sorted( + (t for t in cond_frame_outputs if t not in selected_outputs), + key=lambda x: abs(x - frame_idx), + )[:num_remain] + selected_outputs.update((t, cond_frame_outputs[t]) for t in inds_remain) + unselected_outputs = { + t: v for t, v in cond_frame_outputs.items() if t not in selected_outputs + } + + return selected_outputs, unselected_outputs + + +def get_1d_sine_pe(pos_inds, dim, temperature=10000): + """ + Get 1D sine positional embedding as in the original Transformer paper. + """ + pe_dim = dim // 2 + dim_t = torch.arange(pe_dim, dtype=torch.float32, device=pos_inds.device) + dim_t = temperature ** (2 * (dim_t // 2) / pe_dim) + + pos_embed = pos_inds.unsqueeze(-1) / dim_t + pos_embed = torch.cat([pos_embed.sin(), pos_embed.cos()], dim=-1) + return pos_embed + + +def get_activation_fn(activation): + """Return an activation function given a string""" + if activation == "relu": + return F.relu + if activation == "gelu": + return F.gelu + if activation == "glu": + return F.glu + raise RuntimeError(f"activation should be relu/gelu, not {activation}.") + + +def get_clones(module, N): + return nn.ModuleList([copy.deepcopy(module) for i in range(N)]) + + +class DropPath(nn.Module): + # adapted from https://github.com/huggingface/pytorch-image-models/blob/main/timm/layers/drop.py + def __init__(self, drop_prob=0.0, scale_by_keep=True): + super(DropPath, self).__init__() + self.drop_prob = drop_prob + self.scale_by_keep = scale_by_keep + + def forward(self, x): + if self.drop_prob == 0.0 or not self.training: + return x + keep_prob = 1 - self.drop_prob + shape = (x.shape[0],) + (1,) * (x.ndim - 1) + random_tensor = x.new_empty(shape).bernoulli_(keep_prob) + if keep_prob > 0.0 and self.scale_by_keep: + random_tensor.div_(keep_prob) + return x * random_tensor + + +# Lightly adapted from +# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa +class MLP(nn.Module): + def __init__( + self, + input_dim: int, + hidden_dim: int, + output_dim: int, + num_layers: int, + activation: nn.Module = nn.ReLU, + sigmoid_output: bool = False, + ) -> None: + super().__init__() + self.num_layers = num_layers + h = [hidden_dim] * (num_layers - 1) + self.layers = nn.ModuleList( + nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim]) + ) + self.sigmoid_output = sigmoid_output + self.act = activation() + + def forward(self, x): + for i, layer in enumerate(self.layers): + x = self.act(layer(x)) if i < self.num_layers - 1 else layer(x) + if self.sigmoid_output: + x = F.sigmoid(x) + return x + + +# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa +# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa +class LayerNorm2d(nn.Module): + def __init__(self, num_channels: int, eps: float = 1e-6) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(num_channels)) + self.bias = nn.Parameter(torch.zeros(num_channels)) + self.eps = eps + + def forward(self, x: torch.Tensor) -> torch.Tensor: + u = x.mean(1, keepdim=True) + s = (x - u).pow(2).mean(1, keepdim=True) + x = (x - u) / torch.sqrt(s + self.eps) + x = self.weight[:, None, None] * x + self.bias[:, None, None] + return x + + +def sample_box_points( + masks: torch.Tensor, + noise: float = 0.1, # SAM default + noise_bound: int = 20, # SAM default + top_left_label: int = 2, + bottom_right_label: int = 3, +) -> Tuple[np.array, np.array]: + """ + Sample a noised version of the top left and bottom right corners of a given `bbox` + + Inputs: + - masks: [B, 1, H,W] boxes, dtype=torch.Tensor + - noise: noise as a fraction of box width and height, dtype=float + - noise_bound: maximum amount of noise (in pure pixesl), dtype=int + + Returns: + - box_coords: [B, num_pt, 2], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.float + - box_labels: [B, num_pt], label 2 is reserverd for top left and 3 for bottom right corners, dtype=torch.int32 + """ + device = masks.device + box_coords = mask_to_box(masks) + B, _, H, W = masks.shape + box_labels = torch.tensor( + [top_left_label, bottom_right_label], dtype=torch.int, device=device + ).repeat(B) + if noise > 0.0: + if not isinstance(noise_bound, torch.Tensor): + noise_bound = torch.tensor(noise_bound, device=device) + bbox_w = box_coords[..., 2] - box_coords[..., 0] + bbox_h = box_coords[..., 3] - box_coords[..., 1] + max_dx = torch.min(bbox_w * noise, noise_bound) + max_dy = torch.min(bbox_h * noise, noise_bound) + box_noise = 2 * torch.rand(B, 1, 4, device=device) - 1 + box_noise = box_noise * torch.stack((max_dx, max_dy, max_dx, max_dy), dim=-1) + + box_coords = box_coords + box_noise + img_bounds = ( + torch.tensor([W, H, W, H], device=device) - 1 + ) # uncentered pixel coords + box_coords.clamp_(torch.zeros_like(img_bounds), img_bounds) # In place clamping + + box_coords = box_coords.reshape(-1, 2, 2) # always 2 points + box_labels = box_labels.reshape(-1, 2) + return box_coords, box_labels + + +def sample_random_points_from_errors(gt_masks, pred_masks, num_pt=1): + """ + Sample `num_pt` random points (along with their labels) independently from the error regions. + + Inputs: + - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool + - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None + - num_pt: int, number of points to sample independently for each of the B error maps + + Outputs: + - points: [B, num_pt, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point + - labels: [B, num_pt], dtype=torch.int32, where 1 means positive clicks and 0 means + negative clicks + """ + if pred_masks is None: # if pred_masks is not provided, treat it as empty + pred_masks = torch.zeros_like(gt_masks) + assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1 + assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape + assert num_pt >= 0 + + B, _, H_im, W_im = gt_masks.shape + device = gt_masks.device + + # false positive region, a new point sampled in this region should have + # negative label to correct the FP error + fp_masks = ~gt_masks & pred_masks + # false negative region, a new point sampled in this region should have + # positive label to correct the FN error + fn_masks = gt_masks & ~pred_masks + # whether the prediction completely match the ground-truth on each mask + all_correct = torch.all((gt_masks == pred_masks).flatten(2), dim=2) + all_correct = all_correct[..., None, None] + + # channel 0 is FP map, while channel 1 is FN map + pts_noise = torch.rand(B, num_pt, H_im, W_im, 2, device=device) + # sample a negative new click from FP region or a positive new click + # from FN region, depend on where the maximum falls, + # and in case the predictions are all correct (no FP or FN), we just + # sample a negative click from the background region + pts_noise[..., 0] *= fp_masks | (all_correct & ~gt_masks) + pts_noise[..., 1] *= fn_masks + pts_idx = pts_noise.flatten(2).argmax(dim=2) + labels = (pts_idx % 2).to(torch.int32) + pts_idx = pts_idx // 2 + pts_x = pts_idx % W_im + pts_y = pts_idx // W_im + points = torch.stack([pts_x, pts_y], dim=2).to(torch.float) + return points, labels + + +def sample_one_point_from_error_center(gt_masks, pred_masks, padding=True): + """ + Sample 1 random point (along with its label) from the center of each error region, + that is, the point with the largest distance to the boundary of each error region. + This is the RITM sampling method from https://github.com/saic-vul/ritm_interactive_segmentation/blob/master/isegm/inference/clicker.py + + Inputs: + - gt_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool + - pred_masks: [B, 1, H_im, W_im] masks, dtype=torch.bool or None + - padding: if True, pad with boundary of 1 px for distance transform + + Outputs: + - points: [B, 1, 2], dtype=torch.float, contains (x, y) coordinates of each sampled point + - labels: [B, 1], dtype=torch.int32, where 1 means positive clicks and 0 means negative clicks + """ + import cv2 + + if pred_masks is None: + pred_masks = torch.zeros_like(gt_masks) + assert gt_masks.dtype == torch.bool and gt_masks.size(1) == 1 + assert pred_masks.dtype == torch.bool and pred_masks.shape == gt_masks.shape + + B, _, _, W_im = gt_masks.shape + device = gt_masks.device + + # false positive region, a new point sampled in this region should have + # negative label to correct the FP error + fp_masks = ~gt_masks & pred_masks + # false negative region, a new point sampled in this region should have + # positive label to correct the FN error + fn_masks = gt_masks & ~pred_masks + + fp_masks = fp_masks.cpu().numpy() + fn_masks = fn_masks.cpu().numpy() + points = torch.zeros(B, 1, 2, dtype=torch.float) + labels = torch.ones(B, 1, dtype=torch.int32) + for b in range(B): + fn_mask = fn_masks[b, 0] + fp_mask = fp_masks[b, 0] + if padding: + fn_mask = np.pad(fn_mask, ((1, 1), (1, 1)), "constant") + fp_mask = np.pad(fp_mask, ((1, 1), (1, 1)), "constant") + # compute the distance of each point in FN/FP region to its boundary + fn_mask_dt = cv2.distanceTransform(fn_mask.astype(np.uint8), cv2.DIST_L2, 0) + fp_mask_dt = cv2.distanceTransform(fp_mask.astype(np.uint8), cv2.DIST_L2, 0) + if padding: + fn_mask_dt = fn_mask_dt[1:-1, 1:-1] + fp_mask_dt = fp_mask_dt[1:-1, 1:-1] + + # take the point in FN/FP region with the largest distance to its boundary + fn_mask_dt_flat = fn_mask_dt.reshape(-1) + fp_mask_dt_flat = fp_mask_dt.reshape(-1) + fn_argmax = np.argmax(fn_mask_dt_flat) + fp_argmax = np.argmax(fp_mask_dt_flat) + is_positive = fn_mask_dt_flat[fn_argmax] > fp_mask_dt_flat[fp_argmax] + pt_idx = fn_argmax if is_positive else fp_argmax + points[b, 0, 0] = pt_idx % W_im # x + points[b, 0, 1] = pt_idx // W_im # y + labels[b, 0] = int(is_positive) + + points = points.to(device) + labels = labels.to(device) + return points, labels + + +def get_next_point(gt_masks, pred_masks, method): + if method == "uniform": + return sample_random_points_from_errors(gt_masks, pred_masks) + elif method == "center": + return sample_one_point_from_error_center(gt_masks, pred_masks) + else: + raise ValueError(f"unknown sampling method {method}") diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_b+.yaml b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_b+.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b3ba469471ddaa57a341ddc64ad106cf293d5c66 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_b+.yaml @@ -0,0 +1,113 @@ +# @package _global_ + +# Model +model: + _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera + embed_dim: 112 + num_heads: 2 + neck: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [896, 448, 224, 112] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: torchao._models.sam2.modeling.memory_encoder.Fuser + layer: + _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_l.yaml b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_l.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59a8a1e36b13111ed149bb8971b26c67f1201cb1 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_l.yaml @@ -0,0 +1,117 @@ +# @package _global_ + +# Model +model: + _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera + embed_dim: 144 + num_heads: 2 + stages: [2, 6, 36, 4] + global_att_blocks: [23, 33, 43] + window_pos_embed_bkg_spatial_size: [7, 7] + window_spec: [8, 4, 16, 8] + neck: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [1152, 576, 288, 144] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: torchao._models.sam2.modeling.memory_encoder.Fuser + layer: + _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_s.yaml b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_s.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b051d3be63189303fdf3714e67dd2a891c220dc2 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_s.yaml @@ -0,0 +1,116 @@ +# @package _global_ + +# Model +model: + _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera + embed_dim: 96 + num_heads: 1 + stages: [1, 2, 11, 2] + global_att_blocks: [7, 10, 13] + window_pos_embed_bkg_spatial_size: [7, 7] + neck: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [768, 384, 192, 96] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: torchao._models.sam2.modeling.memory_encoder.Fuser + layer: + _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + compile_image_encoder: False diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_t.yaml b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_t.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b108e708f095a44dcd88221b51e8706494113b3 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_hiera_t.yaml @@ -0,0 +1,118 @@ +# @package _global_ + +# Model +model: + _target_: torchao._models.sam2.modeling.sam2_base.SAM2Base + image_encoder: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.ImageEncoder + scalp: 1 + trunk: + _target_: torchao._models.sam2.modeling.backbones.hieradet.Hiera + embed_dim: 96 + num_heads: 1 + stages: [1, 2, 7, 2] + global_att_blocks: [5, 7, 9] + window_pos_embed_bkg_spatial_size: [7, 7] + neck: + _target_: torchao._models.sam2.modeling.backbones.image_encoder.FpnNeck + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 256 + normalize: true + scale: null + temperature: 10000 + d_model: 256 + backbone_channel_list: [768, 384, 192, 96] + fpn_top_down_levels: [2, 3] # output level 0 and 1 directly use the backbone features + fpn_interp_model: nearest + + memory_attention: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttention + d_model: 256 + pos_enc_at_input: true + layer: + _target_: torchao._models.sam2.modeling.memory_attention.MemoryAttentionLayer + activation: relu + dim_feedforward: 2048 + dropout: 0.1 + pos_enc_at_attn: false + self_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + d_model: 256 + pos_enc_at_cross_attn_keys: true + pos_enc_at_cross_attn_queries: false + cross_attention: + _target_: torchao._models.sam2.modeling.sam.transformer.RoPEAttention + rope_theta: 10000.0 + feat_sizes: [32, 32] + rope_k_repeat: True + embedding_dim: 256 + num_heads: 1 + downsample_rate: 1 + dropout: 0.1 + kv_in_dim: 64 + num_layers: 4 + + memory_encoder: + _target_: torchao._models.sam2.modeling.memory_encoder.MemoryEncoder + out_dim: 64 + position_encoding: + _target_: torchao._models.sam2.modeling.position_encoding.PositionEmbeddingSine + num_pos_feats: 64 + normalize: true + scale: null + temperature: 10000 + mask_downsampler: + _target_: torchao._models.sam2.modeling.memory_encoder.MaskDownSampler + kernel_size: 3 + stride: 2 + padding: 1 + fuser: + _target_: torchao._models.sam2.modeling.memory_encoder.Fuser + layer: + _target_: torchao._models.sam2.modeling.memory_encoder.CXBlock + dim: 256 + kernel_size: 7 + padding: 3 + layer_scale_init_value: 1e-6 + use_dwconv: True # depth-wise convs + num_layers: 2 + + num_maskmem: 7 + image_size: 1024 + # apply scaled sigmoid on mask logits for memory encoder, and directly feed input mask as output mask + # SAM decoder + sigmoid_scale_for_mem_enc: 20.0 + sigmoid_bias_for_mem_enc: -10.0 + use_mask_input_as_output_without_sam: true + # Memory + directly_add_no_mem_embed: true + # use high-resolution feature map in the SAM mask decoder + use_high_res_features_in_sam: true + # output 3 masks on the first click on initial conditioning frames + multimask_output_in_sam: true + # SAM heads + iou_prediction_use_sigmoid: True + # cross-attend to object pointers from other frames (based on SAM output tokens) in the encoder + use_obj_ptrs_in_encoder: true + add_tpos_enc_to_obj_ptrs: false + only_obj_ptrs_in_the_past_for_eval: true + # object occlusion prediction + pred_obj_scores: true + pred_obj_scores_mlp: true + fixed_no_obj_ptr: true + # multimask tracking settings + multimask_output_for_tracking: true + use_multimask_token_for_obj_ptr: true + multimask_min_pt_num: 0 + multimask_max_pt_num: 1 + use_mlp_for_obj_ptr_proj: true + # Compilation flag + # HieraT does not currently support compilation, should always be set to False + compile_image_encoder: False diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_image_predictor.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_image_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..189e26b25caad4c09862c0abf20773899a9c6502 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_image_predictor.py @@ -0,0 +1,571 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import logging +from typing import List, Optional, Tuple, Union + +import numpy as np +import torch +from PIL.Image import Image + +from torchao._models.sam2.modeling.sam2_base import SAM2Base +from torchao._models.sam2.utils.misc import get_image_size +from torchao._models.sam2.utils.transforms import SAM2Transforms + + +class SAM2ImagePredictor(torch.nn.Module): + def __init__( + self, + sam_model: SAM2Base, + mask_threshold=0.0, + max_hole_area=0.0, + max_sprinkle_area=0.0, + **kwargs, + ) -> None: + """ + Uses SAM-2 to calculate the image embedding for an image, and then + allow repeated, efficient mask prediction given prompts. + + Arguments: + sam_model (Sam-2): The model to use for mask prediction. + mask_threshold (float): The threshold to use when converting mask logits + to binary masks. Masks are thresholded at 0 by default. + max_hole_area (int): If max_hole_area > 0, we fill small holes in up to + the maximum area of max_hole_area in low_res_masks. + max_sprinkle_area (int): If max_sprinkle_area > 0, we remove small sprinkles up to + the maximum area of max_sprinkle_area in low_res_masks. + """ + super().__init__() + self.model = sam_model + self._transforms = SAM2Transforms( + resolution=self.model.image_size, + mask_threshold=mask_threshold, + max_hole_area=max_hole_area, + max_sprinkle_area=max_sprinkle_area, + ) + + # Predictor state + self._is_image_set = False + self._features = None + self._orig_hw = None + # Whether the predictor is set for single image or a batch of images + self._is_batch = False + + # Predictor config + self.mask_threshold = mask_threshold + + # Spatial dim for backbone feature maps + self._bb_feat_sizes = [ + (256, 256), + (128, 128), + (64, 64), + ] + + self._image_dtype = torch.float32 + self._transforms_device = "cpu" + + @classmethod + def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2ImagePredictor": + """ + Load a pretrained model from the Hugging Face hub. + + Arguments: + model_id (str): The Hugging Face repository ID. + **kwargs: Additional arguments to pass to the model constructor. + + Returns: + (SAM2ImagePredictor): The loaded model. + """ + from sam2.build_sam import build_sam2_hf + + sam_model = build_sam2_hf(model_id, **kwargs) + return cls(sam_model, **kwargs) + + @torch.no_grad() + def set_image( + self, + image: Union[np.ndarray, Image, torch.Tensor], + ) -> None: + """ + Calculates the image embeddings for the provided image, allowing + masks to be predicted with the 'predict' method. + + Arguments: + 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 + with pixel values in [0, 255]. + image_format (str): The color format of the image, in ['RGB', 'BGR']. + """ + self.reset_predictor() + # Transform the image to the form expected by the model + self._orig_hw = [get_image_size(image)] + + if isinstance(image, torch.Tensor): + # from torchvision.transforms.v2 import functional as F + # input_image = F.to_dtype(image, torch.float32, scale=True) + input_image = image + else: + input_image = self._transforms.to_tensor(image) + + # NOTE: Doing these transforms on the GPU changes the numerics + input_image = input_image.to(device=self._transforms_device) + input_image = self._transforms.transforms(input_image) + input_image = input_image.to(device=self.device) + # input_image = self._transforms.transforms(input_image) + input_image = input_image[None, ...].to(dtype=self._image_dtype) + + assert len(input_image.shape) == 4 and input_image.shape[1] == 3, ( + f"input_image must be of size 1x3xHxW, got {input_image.shape}" + ) + logging.info("Computing image embeddings for the provided image...") + with torch.autograd.profiler.record_function("forward_image"): + backbone_out = self.model.forward_image(input_image) + _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out) + # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos + if self.model.directly_add_no_mem_embed: + vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed + + feats = [ + feat.permute(1, 2, 0).view(1, -1, *feat_size) + for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1]) + ][::-1] + self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} + self._is_image_set = True + logging.info("Image embeddings computed.") + + @torch.no_grad() + def set_image_batch( + self, + image_list: List[Union[np.ndarray, torch.Tensor]], + ) -> None: + """ + Calculates the image embeddings for the provided image batch, allowing + masks to be predicted with the 'predict_batch' method. + + Arguments: + image_list (List[np.ndarray]): The input images to embed in RGB format. The image should be in HWC format if np.ndarray + with pixel values in [0, 255]. + """ + self.reset_predictor() + assert isinstance(image_list, list) + self._orig_hw = list(map(get_image_size, image_list)) + with torch.autograd.profiler.record_function("forward_batch"): + # Transform the image to the form expected by the model + # img_batch = self._transforms.forward_batch(image_list) + image_list = [ + self._transforms.to_tensor(img) if isinstance(img, np.ndarray) else img + for img in image_list + ] + image_list = [self._transforms.transforms(img) for img in image_list] + img_batch = torch.stack(image_list, dim=0) + img_batch = img_batch.to(self.device) + img_batch = img_batch.to(self._image_dtype) + batch_size = img_batch.shape[0] + assert len(img_batch.shape) == 4 and img_batch.shape[1] == 3, ( + f"img_batch must be of size Bx3xHxW, got {img_batch.shape}" + ) + logging.info("Computing image embeddings for the provided images...") + with torch.autograd.profiler.record_function("forward_image"): + backbone_out = self.model.forward_image(img_batch) + with torch.autograd.profiler.record_function("_prepare_backbone_features"): + _, vision_feats, _, _ = self.model._prepare_backbone_features(backbone_out) + # Add no_mem_embed, which is added to the lowest rest feat. map during training on videos + if self.model.directly_add_no_mem_embed: + vision_feats[-1] = vision_feats[-1] + self.model.no_mem_embed + + feats = [ + feat.permute(1, 2, 0).view(batch_size, -1, *feat_size) + for feat, feat_size in zip(vision_feats[::-1], self._bb_feat_sizes[::-1]) + ][::-1] + self._features = {"image_embed": feats[-1], "high_res_feats": feats[:-1]} + self._is_image_set = True + self._is_batch = True + logging.info("Image embeddings computed.") + + def predict_batch( + self, + point_coords_batch: List[np.ndarray] = None, + point_labels_batch: List[np.ndarray] = None, + box_batch: List[np.ndarray] = None, + mask_input_batch: List[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + normalize_coords=True, + return_type: str = "numpy", + ) -> Tuple[List[np.ndarray], List[np.ndarray], List[np.ndarray]]: + """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. + It returns a tuple of lists of masks, ious, and low_res_masks_logits. + """ + if return_type not in ["numpy", "torch"]: + raise ValueError( + f"Expected return_type to be either numpy or torch, but got {return_type}" + ) + assert self._is_batch, "This function should only be used when in batched mode" + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image_batch(...) before mask prediction." + ) + num_images = len(self._features["image_embed"]) + all_masks = [] + all_ious = [] + all_low_res_masks = [] + for img_idx in range(num_images): + # Transform input prompts + point_coords = ( + point_coords_batch[img_idx] if point_coords_batch is not None else None + ) + point_labels = ( + point_labels_batch[img_idx] if point_labels_batch is not None else None + ) + box = box_batch[img_idx] if box_batch is not None else None + mask_input = ( + mask_input_batch[img_idx] if mask_input_batch is not None else None + ) + mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts( + point_coords, + point_labels, + box, + mask_input, + normalize_coords, + img_idx=img_idx, + ) + masks, iou_predictions, low_res_masks = self._predict( + unnorm_coords, + labels, + unnorm_box, + mask_input, + multimask_output, + return_logits=return_logits, + img_idx=img_idx, + ) + if return_type == "numpy": + masks = masks.squeeze(0).float().detach().cpu().numpy() + iou_predictions = ( + iou_predictions.squeeze(0).float().detach().cpu().numpy() + ) + low_res_masks = low_res_masks.squeeze(0).float().detach().cpu().numpy() + # NOTE: Need these additional clones to prevent overwriting tensor output of CUDAGraph + all_masks.append(masks.clone()) + all_ious.append(iou_predictions.clone()) + all_low_res_masks.append(low_res_masks.clone()) + + return all_masks, all_ious, all_low_res_masks + + def predict( + self, + point_coords: Optional[np.ndarray] = None, + point_labels: Optional[np.ndarray] = None, + box: Optional[np.ndarray] = None, + mask_input: Optional[np.ndarray] = None, + multimask_output: bool = True, + return_logits: bool = False, + normalize_coords=True, + return_type: str = "numpy", + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: + """ + Predict masks for the given input prompts, using the currently set image. + + Arguments: + point_coords (np.ndarray or None): A Nx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (np.ndarray or None): A length N array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + box (np.ndarray or None): A length 4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form 1xHxW, where + for SAM, H=W=256. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + 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. + + Returns: + (np.ndarray): The output masks in CxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (np.ndarray): An array of length C containing the model's + predictions for the quality of each mask. + (np.ndarray): An array of shape CxHxW, where C is the number + of masks and H=W=256. These low resolution logits can be passed to + a subsequent iteration as mask input. + """ + if return_type not in ["numpy", "torch"]: + raise ValueError( + f"Expected return_type to be either numpy or torch, but got {return_type}" + ) + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + # Transform input prompts + + mask_input, unnorm_coords, labels, unnorm_box = self._prep_prompts( + point_coords, point_labels, box, mask_input, normalize_coords + ) + + masks, iou_predictions, low_res_masks = self._predict( + unnorm_coords, + labels, + unnorm_box, + mask_input, + multimask_output, + return_logits=return_logits, + ) + + if return_type == "torch": + return ( + masks.squeeze(0), + iou_predictions.squeeze(0), + low_res_masks.squeeze(0), + ) + + masks_np = masks.squeeze(0).float().detach().cpu().numpy() + iou_predictions_np = iou_predictions.squeeze(0).float().detach().cpu().numpy() + low_res_masks_np = low_res_masks.squeeze(0).float().detach().cpu().numpy() + return masks_np, iou_predictions_np, low_res_masks_np + + def _prep_prompts( + self, point_coords, point_labels, box, mask_logits, normalize_coords, img_idx=-1 + ): + unnorm_coords, labels, unnorm_box, mask_input = None, None, None, None + if point_coords is not None: + assert point_labels is not None, ( + "point_labels must be supplied if point_coords is supplied." + ) + point_coords = ( + torch.as_tensor(point_coords, dtype=torch.float) + .pin_memory() + .to(self.device, non_blocking=True) + ) + unnorm_coords = self._transforms.transform_coords( + point_coords, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx] + ) + labels = ( + torch.as_tensor(point_labels, dtype=torch.int) + .pin_memory() + .to(self.device, non_blocking=True) + ) + if len(unnorm_coords.shape) == 2: + unnorm_coords, labels = unnorm_coords[None, ...], labels[None, ...] + if box is not None: + box = torch.as_tensor(box, dtype=torch.float, device=self.device) + unnorm_box = self._transforms.transform_boxes( + box, normalize=normalize_coords, orig_hw=self._orig_hw[img_idx] + ) # Bx2x2 + if mask_logits is not None: + mask_input = torch.as_tensor( + mask_logits, dtype=torch.float, device=self.device + ) + if len(mask_input.shape) == 3: + mask_input = mask_input[None, :, :, :] + return mask_input, unnorm_coords, labels, unnorm_box + + @torch.no_grad() + def _predict( + self, + point_coords: Optional[torch.Tensor], + point_labels: Optional[torch.Tensor], + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + return_logits: bool = False, + img_idx: int = -1, + ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Predict masks for the given input prompts, using the currently set image. + Input prompts are batched torch tensors and are expected to already be + transformed to the input frame using SAM2Transforms. + + Arguments: + point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the + model. Each point is in (X,Y) in pixels. + point_labels (torch.Tensor or None): A BxN array of labels for the + point prompts. 1 indicates a foreground point and 0 indicates a + background point. + boxes (np.ndarray or None): A Bx4 array given a box prompt to the + model, in XYXY format. + mask_input (np.ndarray): A low resolution mask input to the model, typically + coming from a previous prediction iteration. Has form Bx1xHxW, where + for SAM, H=W=256. Masks returned by a previous iteration of the + predict method do not need further transformation. + multimask_output (bool): If true, the model will return three masks. + For ambiguous input prompts (such as a single click), this will often + produce better masks than a single prediction. If only a single + mask is needed, the model's predicted quality score can be used + to select the best mask. For non-ambiguous prompts, such as multiple + input prompts, multimask_output=False can give better results. + return_logits (bool): If true, returns un-thresholded masks logits + instead of a binary mask. + + Returns: + (torch.Tensor): The output masks in BxCxHxW format, where C is the + number of masks, and (H, W) is the original image size. + (torch.Tensor): An array of shape BxC containing the model's + predictions for the quality of each mask. + (torch.Tensor): An array of shape BxCxHxW, where C is the number + of masks and H=W=256. These low res logits can be passed to + a subsequent iteration as mask input. + """ + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) before mask prediction." + ) + + with torch.autograd.profiler.record_function("_predict_masks"): + high_res_feats = self._features["high_res_feats"] + image_embed = self._features["image_embed"] + image_pe = self.model.sam_prompt_encoder.get_dense_pe().clone() + high_res_feats_input = [ + feat_level[img_idx].unsqueeze(0).clone() + # for feat_level in self._features["high_res_feats"] + for feat_level in high_res_feats + ] + image_embed_input = image_embed[img_idx].unsqueeze(0).clone() + assert boxes is None + assert mask_input is None + assert multimask_output is True + low_res_masks, iou_predictions = self._predict_masks( + [t.contiguous() for t in high_res_feats_input], + image_embed_input.contiguous(), + image_pe.contiguous(), + point_coords.contiguous(), + point_labels.contiguous(), + boxes=boxes, + mask_input=mask_input, + multimask_output=multimask_output, + ) + # img_idx=img_idx) + with torch.autograd.profiler.record_function("_predict_masks_postprocess"): + masks, low_res_masks = self._predict_masks_postprocess( + low_res_masks, img_idx, return_logits + ) + return masks, iou_predictions, low_res_masks + + def _predict_masks( + self, + high_res_feats_input, + image_embed, + image_pe, + point_coords, + point_labels, + boxes: Optional[torch.Tensor] = None, + mask_input: Optional[torch.Tensor] = None, + multimask_output: bool = True, + ): + # NOTE: img_idx causes unnecessary recompilations, because + # the int guard will fail otherwise. + # img_idx: int = -1): + if point_coords is not None: + concat_points = (point_coords, point_labels) + else: + concat_points = None + + # Embed prompts + if boxes is not None: + box_coords = boxes.reshape(-1, 2, 2) + box_labels = torch.tensor([[2, 3]], dtype=torch.int, device=boxes.device) + box_labels = box_labels.repeat(boxes.size(0), 1) + # we merge "boxes" and "points" into a single "concat_points" input (where + # boxes are added at the beginning) to sam_prompt_encoder + if concat_points is not None: + concat_coords = torch.cat([box_coords, concat_points[0]], dim=1) + concat_labels = torch.cat([box_labels, concat_points[1]], dim=1) + concat_points = (concat_coords, concat_labels) + else: + concat_points = (box_coords, box_labels) + + with torch.autograd.profiler.record_function("self.model.sam_prompt_encoder"): + sparse_embeddings, dense_embeddings = self.model.sam_prompt_encoder( + points=concat_points, + boxes=None, + masks=mask_input, + ) + + # Predict masks + batched_mode = ( + concat_points is not None and concat_points[0].shape[0] > 1 + ) # multi object prediction + # high_res_features = [ + # feat_level[img_idx].unsqueeze(0).clone() + # # for feat_level in self._features["high_res_feats"] + # for feat_level in high_res_feats_input + # ] + high_res_features = high_res_feats_input + with torch.autograd.profiler.record_function("self.model.sam_mask_decoder"): + # if not multimask_output: + # raise ValueError("Expected multimask_output.") + # if batched_mode: + # raise ValueError("Did not expected repeat_image.") + low_res_masks, iou_predictions, _, _ = self.model.sam_mask_decoder( + # image_embeddings=self._features["image_embed"][img_idx].unsqueeze(0).clone(), + # image_embeddings=image_embed[img_idx].unsqueeze(0).clone(), + image_embeddings=image_embed, + # image_pe=self.model.sam_prompt_encoder.get_dense_pe().clone(), + image_pe=image_pe, + sparse_prompt_embeddings=sparse_embeddings.clone(), + dense_prompt_embeddings=dense_embeddings.clone(), + multimask_output=multimask_output, + repeat_image=batched_mode, + high_res_features=high_res_features, + ) + + return low_res_masks, iou_predictions + + def _predict_masks_postprocess( + self, low_res_masks, img_idx, return_logits, channel_1=False + ): + # TODO: Might want to defer this until after data["iou_preds"] > self.pred_iou_thresh + with torch.autograd.profiler.record_function( + "self._transforms.postprocess_masks" + ): + # Upscale the masks to the original image resolution + if channel_1: + masks = self._transforms.postprocess_masks_1_channel( + low_res_masks, self._orig_hw[img_idx], self._image_dtype + ) + else: + masks = self._transforms.postprocess_masks( + low_res_masks, self._orig_hw[img_idx], self._image_dtype + ) + low_res_masks = torch.clamp(low_res_masks, -32.0, 32.0) + if not return_logits: + masks = masks > self.mask_threshold + + return masks, low_res_masks + + def get_image_embedding(self) -> torch.Tensor: + """ + Returns the image embeddings for the currently set image, with + shape 1xCxHxW, where C is the embedding dimension and (H,W) are + the embedding spatial dimension of SAM (typically C=256, H=W=64). + """ + if not self._is_image_set: + raise RuntimeError( + "An image must be set with .set_image(...) to generate an embedding." + ) + assert self._features is not None, ( + "Features must exist if an image has been set." + ) + return self._features["image_embed"] + + @property + def device(self) -> torch.device: + return self.model.device + + def reset_predictor(self) -> None: + """ + Resets the image embeddings and other state variables. + """ + self._is_image_set = False + self._features = None + self._orig_hw = None + self._is_batch = False diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_video_predictor.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_video_predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..53b0a11d7c7c3d9f2040af0f2debb5ce7ce17eda --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/sam2_video_predictor.py @@ -0,0 +1,1192 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import warnings +from collections import OrderedDict + +import torch +from tqdm import tqdm + +from torchao._models.sam2.modeling.sam2_base import NO_OBJ_SCORE, SAM2Base +from torchao._models.sam2.utils.misc import ( + concat_points, + fill_holes_in_mask_scores, + load_video_frames, +) + + +class SAM2VideoPredictor(SAM2Base): + """The predictor class to handle user interactions and manage inference states.""" + + def __init__( + self, + fill_hole_area=0, + # whether to apply non-overlapping constraints on the output object masks + non_overlap_masks=False, + # whether to clear non-conditioning memory of the surrounding frames (which may contain outdated information) after adding correction clicks; + # note that this would only apply to *single-object tracking* unless `clear_non_cond_mem_for_multi_obj` is also set to True) + clear_non_cond_mem_around_input=False, + # whether to also clear non-conditioning memory of the surrounding frames (only effective when `clear_non_cond_mem_around_input` is True). + clear_non_cond_mem_for_multi_obj=False, + # 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 + # if `add_all_frames_to_correct_as_cond` is False, we conditioning frame list to only use those initial conditioning frames + add_all_frames_to_correct_as_cond=False, + **kwargs, + ): + super().__init__(**kwargs) + self.fill_hole_area = fill_hole_area + self.non_overlap_masks = non_overlap_masks + self.clear_non_cond_mem_around_input = clear_non_cond_mem_around_input + self.clear_non_cond_mem_for_multi_obj = clear_non_cond_mem_for_multi_obj + self.add_all_frames_to_correct_as_cond = add_all_frames_to_correct_as_cond + + @staticmethod + def batch_inference_states(inference_states: list): + assert all(dict == type(state) for state in inference_states) + num_states = len(inference_states) + assert num_states > 0 + import copy + + batched_inference_state = copy.copy(inference_states[0]) + + from torchao._models.sam2.map_tensor import to_map_tensor + + # NOTE: Making a build assumption only images differ + all_images = torch.stack([state["images"] for state in inference_states]) + batched_inference_state["images"] = to_map_tensor(all_images) + return batched_inference_state + + @torch.no_grad() + def init_state( + self, + video_path, + offload_video_to_cpu=False, + offload_state_to_cpu=False, + async_loading_frames=False, + ): + """Initialize an inference state.""" + compute_device = self.device # device of the model + images, video_height, video_width = load_video_frames( + video_path=video_path, + image_size=self.image_size, + offload_video_to_cpu=offload_video_to_cpu, + async_loading_frames=async_loading_frames, + compute_device=compute_device, + ) + inference_state = {} + inference_state["images"] = images + inference_state["num_frames"] = len(images) + # whether to offload the video frames to CPU memory + # turning on this option saves the GPU memory with only a very small overhead + inference_state["offload_video_to_cpu"] = offload_video_to_cpu + # whether to offload the inference state to CPU memory + # turning on this option saves the GPU memory at the cost of a lower tracking fps + # (e.g. in a test case of 768x768 model, fps dropped from 27 to 24 when tracking one object + # and from 24 to 21 when tracking two objects) + inference_state["offload_state_to_cpu"] = offload_state_to_cpu + # the original video height and width, used for resizing final output scores + inference_state["video_height"] = video_height + inference_state["video_width"] = video_width + inference_state["device"] = compute_device + if offload_state_to_cpu: + inference_state["storage_device"] = torch.device("cpu") + else: + inference_state["storage_device"] = compute_device + # inputs on each frame + inference_state["point_inputs_per_obj"] = {} + inference_state["mask_inputs_per_obj"] = {} + # visual features on a small number of recently visited frames for quick interactions + inference_state["cached_features"] = {} + # values that don't change across frames (so we only need to hold one copy of them) + inference_state["constants"] = {} + # mapping between client-side object id and model-side object index + inference_state["obj_id_to_idx"] = OrderedDict() + inference_state["obj_idx_to_id"] = OrderedDict() + inference_state["obj_ids"] = [] + # A storage to hold the model's tracking results and states on each frame + inference_state["output_dict"] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + # Slice (view) of each object tracking results, sharing the same memory with "output_dict" + inference_state["output_dict_per_obj"] = {} + # A temporary storage to hold new outputs when user interact with a frame + # to add clicks or mask (it's merged into "output_dict" before propagation starts) + inference_state["temp_output_dict_per_obj"] = {} + # Frames that already holds consolidated outputs from click or mask inputs + # (we directly use their consolidated outputs during tracking) + inference_state["consolidated_frame_inds"] = { + "cond_frame_outputs": set(), # set containing frame indices + "non_cond_frame_outputs": set(), # set containing frame indices + } + # metadata for each tracking frame (e.g. which direction it's tracked) + inference_state["tracking_has_started"] = False + inference_state["frames_already_tracked"] = {} + # Warm up the visual backbone and cache the image feature on frame 0 + self._get_image_feature(inference_state, frame_idx=0, batch_size=1) + return inference_state + + @classmethod + def from_pretrained(cls, model_id: str, **kwargs) -> "SAM2VideoPredictor": + """ + Load a pretrained model from the Hugging Face hub. + + Arguments: + model_id (str): The Hugging Face repository ID. + **kwargs: Additional arguments to pass to the model constructor. + + Returns: + (SAM2VideoPredictor): The loaded model. + """ + from sam2.build_sam import build_sam2_video_predictor_hf + + sam_model = build_sam2_video_predictor_hf(model_id, **kwargs) + return sam_model + + def _obj_id_to_idx(self, inference_state, obj_id): + """Map client-side object id to model-side object index.""" + obj_idx = inference_state["obj_id_to_idx"].get(obj_id, None) + if obj_idx is not None: + return obj_idx + + # This is a new object id not sent to the server before. We only allow adding + # new objects *before* the tracking starts. + allow_new_object = not inference_state["tracking_has_started"] + if allow_new_object: + # get the next object slot + obj_idx = len(inference_state["obj_id_to_idx"]) + inference_state["obj_id_to_idx"][obj_id] = obj_idx + inference_state["obj_idx_to_id"][obj_idx] = obj_id + inference_state["obj_ids"] = list(inference_state["obj_id_to_idx"]) + # set up input and output structures for this object + inference_state["point_inputs_per_obj"][obj_idx] = {} + inference_state["mask_inputs_per_obj"][obj_idx] = {} + inference_state["output_dict_per_obj"][obj_idx] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + inference_state["temp_output_dict_per_obj"][obj_idx] = { + "cond_frame_outputs": {}, # dict containing {frame_idx: } + "non_cond_frame_outputs": {}, # dict containing {frame_idx: } + } + return obj_idx + else: + raise RuntimeError( + f"Cannot add new object id {obj_id} after tracking starts. " + f"All existing object ids: {inference_state['obj_ids']}. " + f"Please call 'reset_state' to restart from scratch." + ) + + def _obj_idx_to_id(self, inference_state, obj_idx): + """Map model-side object index to client-side object id.""" + return inference_state["obj_idx_to_id"][obj_idx] + + def _get_obj_num(self, inference_state): + """Get the total number of unique object ids received so far in this session.""" + return len(inference_state["obj_idx_to_id"]) + + @torch.no_grad() + def add_new_points_or_box( + self, + inference_state, + frame_idx, + obj_id, + points=None, + labels=None, + clear_old_points=True, + normalize_coords=True, + box=None, + ): + """Add new points to a frame.""" + obj_idx = self._obj_id_to_idx(inference_state, obj_id) + point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx] + mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx] + + if (points is not None) != (labels is not None): + raise ValueError("points and labels must be provided together") + if points is None and box is None: + raise ValueError("at least one of points or box must be provided as input") + + if points is None: + points = torch.zeros(0, 2, dtype=torch.float32) + elif not isinstance(points, torch.Tensor): + points = torch.tensor(points, dtype=torch.float32) + if labels is None: + labels = torch.zeros(0, dtype=torch.int32) + elif not isinstance(labels, torch.Tensor): + labels = torch.tensor(labels, dtype=torch.int32) + if points.dim() == 2: + points = points.unsqueeze(0) # add batch dimension + if labels.dim() == 1: + labels = labels.unsqueeze(0) # add batch dimension + + # If `box` is provided, we add it as the first two points with labels 2 and 3 + # along with the user-provided points (consistent with how SAM 2 is trained). + if box is not None: + if not clear_old_points: + raise ValueError( + "cannot add box without clearing old points, since " + "box prompt must be provided before any point prompt " + "(please use clear_old_points=True instead)" + ) + if inference_state["tracking_has_started"]: + warnings.warn( + "You are adding a box after tracking starts. SAM 2 may not always be " + "able to incorporate a box prompt for *refinement*. If you intend to " + "use box prompt as an *initial* input before tracking, please call " + "'reset_state' on the inference state to restart from scratch.", + category=UserWarning, + stacklevel=2, + ) + if not isinstance(box, torch.Tensor): + box = torch.tensor(box, dtype=torch.float32, device=points.device) + box_coords = box.reshape(1, 2, 2) + box_labels = torch.tensor([2, 3], dtype=torch.int32, device=labels.device) + box_labels = box_labels.reshape(1, 2) + points = torch.cat([box_coords, points], dim=1) + labels = torch.cat([box_labels, labels], dim=1) + + if normalize_coords: + video_H = inference_state["video_height"] + video_W = inference_state["video_width"] + points = points / torch.tensor([video_W, video_H]).to(points.device) + # scale the (normalized) coordinates by the model's internal image size + points = points * self.image_size + points = points.to(inference_state["device"]) + labels = labels.to(inference_state["device"]) + + if not clear_old_points: + point_inputs = point_inputs_per_frame.get(frame_idx, None) + else: + point_inputs = None + point_inputs = concat_points(point_inputs, points, labels) + + point_inputs_per_frame[frame_idx] = point_inputs + mask_inputs_per_frame.pop(frame_idx, None) + # If this frame hasn't been tracked before, we treat it as an initial conditioning + # frame, meaning that the inputs points are to generate segments on this frame without + # using any memory from other frames, like in SAM. Otherwise (if it has been tracked), + # the input points will be used to correct the already tracked masks. + is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"] + # whether to track in reverse time order + if is_init_cond_frame: + reverse = False + else: + reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + # Add a frame to conditioning output if it's an initial conditioning frame or + # if the model sees all frames receiving clicks/mask as conditioning frames. + is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + + # Get any previously predicted mask logits on this object and feed it along with + # the new clicks into the SAM mask decoder. + prev_sam_mask_logits = None + # lookup temporary output dict first, which contains the most recent output + # (if not found, then lookup conditioning and non-conditioning frame output) + prev_out = obj_temp_output_dict[storage_key].get(frame_idx) + if prev_out is None: + prev_out = obj_output_dict["cond_frame_outputs"].get(frame_idx) + if prev_out is None: + prev_out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx) + + if prev_out is not None and prev_out["pred_masks"] is not None: + device = inference_state["device"] + prev_sam_mask_logits = prev_out["pred_masks"].to(device, non_blocking=True) + # Clamp the scale of prev_sam_mask_logits to avoid rare numerical issues. + prev_sam_mask_logits = torch.clamp(prev_sam_mask_logits, -32.0, 32.0) + current_out, _ = self._run_single_frame_inference( + inference_state=inference_state, + output_dict=obj_output_dict, # run on the slice of a single object + frame_idx=frame_idx, + batch_size=1, # run on the slice of a single object + is_init_cond_frame=is_init_cond_frame, + point_inputs=point_inputs, + mask_inputs=None, + reverse=reverse, + # Skip the memory encoder when adding clicks or mask. We execute the memory encoder + # at the beginning of `propagate_in_video` (after user finalize their clicks). This + # allows us to enforce non-overlapping constraints on all objects before encoding + # them into memory. + run_mem_encoder=False, + prev_sam_mask_logits=prev_sam_mask_logits, + ) + # Add the output to the output dict (to be used as future memory) + obj_temp_output_dict[storage_key][frame_idx] = current_out + + # Resize the output mask to the original video resolution + obj_ids = inference_state["obj_ids"] + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + return frame_idx, obj_ids, video_res_masks + + def add_new_points(self, *args, **kwargs): + """Deprecated method. Please use `add_new_points_or_box` instead.""" + return self.add_new_points_or_box(*args, **kwargs) + + @torch.no_grad() + def add_new_mask( + self, + inference_state, + frame_idx, + obj_id, + mask, + ): + """Add new mask to a frame.""" + obj_idx = self._obj_id_to_idx(inference_state, obj_id) + point_inputs_per_frame = inference_state["point_inputs_per_obj"][obj_idx] + mask_inputs_per_frame = inference_state["mask_inputs_per_obj"][obj_idx] + + if not isinstance(mask, torch.Tensor): + mask = torch.tensor(mask, dtype=torch.bool) + assert mask.dim() == 2 + mask_H, mask_W = mask.shape + mask_inputs_orig = mask[None, None] # add batch and channel dimension + mask_inputs_orig = mask_inputs_orig.float().to(inference_state["device"]) + + # resize the mask if it doesn't match the model's image size + if mask_H != self.image_size or mask_W != self.image_size: + mask_inputs = torch.nn.functional.interpolate( + mask_inputs_orig, + size=(self.image_size, self.image_size), + align_corners=False, + mode="bilinear", + antialias=True, # use antialias for downsampling + ) + mask_inputs = (mask_inputs >= 0.5).float() + else: + mask_inputs = mask_inputs_orig + + mask_inputs_per_frame[frame_idx] = mask_inputs + point_inputs_per_frame.pop(frame_idx, None) + # If this frame hasn't been tracked before, we treat it as an initial conditioning + # frame, meaning that the inputs points are to generate segments on this frame without + # using any memory from other frames, like in SAM. Otherwise (if it has been tracked), + # the input points will be used to correct the already tracked masks. + is_init_cond_frame = frame_idx not in inference_state["frames_already_tracked"] + # whether to track in reverse time order + if is_init_cond_frame: + reverse = False + else: + reverse = inference_state["frames_already_tracked"][frame_idx]["reverse"] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + # Add a frame to conditioning output if it's an initial conditioning frame or + # if the model sees all frames receiving clicks/mask as conditioning frames. + is_cond = is_init_cond_frame or self.add_all_frames_to_correct_as_cond + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + + current_out, _ = self._run_single_frame_inference( + inference_state=inference_state, + output_dict=obj_output_dict, # run on the slice of a single object + frame_idx=frame_idx, + batch_size=1, # run on the slice of a single object + is_init_cond_frame=is_init_cond_frame, + point_inputs=None, + mask_inputs=mask_inputs, + reverse=reverse, + # Skip the memory encoder when adding clicks or mask. We execute the memory encoder + # at the beginning of `propagate_in_video` (after user finalize their clicks). This + # allows us to enforce non-overlapping constraints on all objects before encoding + # them into memory. + run_mem_encoder=False, + ) + # Add the output to the output dict (to be used as future memory) + obj_temp_output_dict[storage_key][frame_idx] = current_out + + # Resize the output mask to the original video resolution + obj_ids = inference_state["obj_ids"] + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + return frame_idx, obj_ids, video_res_masks + + def _get_orig_video_res_output(self, inference_state, any_res_masks): + """ + Resize the object scores to the original video resolution (video_res_masks) + and apply non-overlapping constraints for final output. + """ + device = inference_state["device"] + video_H = inference_state["video_height"] + video_W = inference_state["video_width"] + any_res_masks = any_res_masks.to(device, non_blocking=True) + if any_res_masks.shape[-2:] == (video_H, video_W): + video_res_masks = any_res_masks + else: + video_res_masks = torch.nn.functional.interpolate( + any_res_masks, + size=(video_H, video_W), + mode="bilinear", + align_corners=False, + ) + if self.non_overlap_masks: + video_res_masks = self._apply_non_overlapping_constraints(video_res_masks) + return any_res_masks, video_res_masks + + def _consolidate_temp_output_across_obj( + self, + inference_state, + frame_idx, + is_cond, + run_mem_encoder, + consolidate_at_video_res=False, + ): + """ + Consolidate the per-object temporary outputs in `temp_output_dict_per_obj` on + a frame into a single output for all objects, including + 1) fill any missing objects either from `output_dict_per_obj` (if they exist in + `output_dict_per_obj` for this frame) or leave them as placeholder values + (if they don't exist in `output_dict_per_obj` for this frame); + 2) if specified, rerun memory encoder after apply non-overlapping constraints + on the object scores. + """ + batch_size = self._get_obj_num(inference_state) + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + # Optionally, we allow consolidating the temporary outputs at the original + # video resolution (to provide a better editing experience for mask prompts). + if consolidate_at_video_res: + assert not run_mem_encoder, "memory encoder cannot run at video resolution" + consolidated_H = inference_state["video_height"] + consolidated_W = inference_state["video_width"] + consolidated_mask_key = "pred_masks_video_res" + else: + consolidated_H = consolidated_W = self.image_size // 4 + consolidated_mask_key = "pred_masks" + + # Initialize `consolidated_out`. Its "maskmem_features" and "maskmem_pos_enc" + # will be added when rerunning the memory encoder after applying non-overlapping + # constraints to object scores. Its "pred_masks" are prefilled with a large + # negative value (NO_OBJ_SCORE) to represent missing objects. + consolidated_out = { + "maskmem_features": None, + "maskmem_pos_enc": None, + consolidated_mask_key: torch.full( + size=(batch_size, 1, consolidated_H, consolidated_W), + fill_value=NO_OBJ_SCORE, + dtype=torch.float32, + device=inference_state["storage_device"], + ), + "obj_ptr": torch.full( + size=(batch_size, self.hidden_dim), + fill_value=NO_OBJ_SCORE, + dtype=torch.float32, + device=inference_state["device"], + ), + "object_score_logits": torch.full( + size=(batch_size, 1), + # default to 10.0 for object_score_logits, i.e. assuming the object is + # present as sigmoid(10)=1, same as in `predict_masks` of `MaskDecoder` + fill_value=10.0, + dtype=torch.float32, + device=inference_state["device"], + ), + } + empty_mask_ptr = None + for obj_idx in range(batch_size): + obj_temp_output_dict = inference_state["temp_output_dict_per_obj"][obj_idx] + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx] + out = obj_temp_output_dict[storage_key].get(frame_idx, None) + # If the object doesn't appear in "temp_output_dict_per_obj" on this frame, + # we fall back and look up its previous output in "output_dict_per_obj". + # We look up both "cond_frame_outputs" and "non_cond_frame_outputs" in + # "output_dict_per_obj" to find a previous output for this object. + if out is None: + out = obj_output_dict["cond_frame_outputs"].get(frame_idx, None) + if out is None: + out = obj_output_dict["non_cond_frame_outputs"].get(frame_idx, None) + # If the object doesn't appear in "output_dict_per_obj" either, we skip it + # and leave its mask scores to the default scores (i.e. the NO_OBJ_SCORE + # placeholder above) and set its object pointer to be a dummy pointer. + if out is None: + # Fill in dummy object pointers for those objects without any inputs or + # tracking outcomes on this frame (only do it under `run_mem_encoder=True`, + # i.e. when we need to build the memory for tracking). + if run_mem_encoder: + if empty_mask_ptr is None: + empty_mask_ptr = self._get_empty_mask_ptr( + inference_state, frame_idx + ) + # fill object pointer with a dummy pointer (based on an empty mask) + consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = empty_mask_ptr + continue + # Add the temporary object output mask to consolidated output mask + obj_mask = out["pred_masks"] + consolidated_pred_masks = consolidated_out[consolidated_mask_key] + if obj_mask.shape[-2:] == consolidated_pred_masks.shape[-2:]: + consolidated_pred_masks[obj_idx : obj_idx + 1] = obj_mask + else: + # Resize first if temporary object mask has a different resolution + resized_obj_mask = torch.nn.functional.interpolate( + obj_mask, + size=consolidated_pred_masks.shape[-2:], + mode="bilinear", + align_corners=False, + ) + consolidated_pred_masks[obj_idx : obj_idx + 1] = resized_obj_mask + consolidated_out["obj_ptr"][obj_idx : obj_idx + 1] = out["obj_ptr"] + consolidated_out["object_score_logits"][obj_idx : obj_idx + 1] = out[ + "object_score_logits" + ] + + # Optionally, apply non-overlapping constraints on the consolidated scores + # and rerun the memory encoder + if run_mem_encoder: + device = inference_state["device"] + high_res_masks = torch.nn.functional.interpolate( + consolidated_out["pred_masks"].to(device, non_blocking=True), + size=(self.image_size, self.image_size), + mode="bilinear", + align_corners=False, + ) + if self.non_overlap_masks_for_mem_enc: + high_res_masks = self._apply_non_overlapping_constraints(high_res_masks) + maskmem_features, maskmem_pos_enc = self._run_memory_encoder( + inference_state=inference_state, + frame_idx=frame_idx, + batch_size=batch_size, + high_res_masks=high_res_masks, + object_score_logits=consolidated_out["object_score_logits"], + is_mask_from_pts=True, # these frames are what the user interacted with + ) + consolidated_out["maskmem_features"] = maskmem_features + consolidated_out["maskmem_pos_enc"] = maskmem_pos_enc + + return consolidated_out + + def _get_empty_mask_ptr(self, inference_state, frame_idx): + """Get a dummy object pointer based on an empty mask on the current frame.""" + # A dummy (empty) mask with a single object + batch_size = 1 + mask_inputs = torch.zeros( + (batch_size, 1, self.image_size, self.image_size), + dtype=torch.float32, + device=inference_state["device"], + ) + + # Retrieve correct image features + ( + _, + _, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + ) = self._get_image_feature(inference_state, frame_idx, batch_size) + + # Feed the empty mask and image feature above to get a dummy object pointer + current_out = self.track_step( + frame_idx=frame_idx, + is_init_cond_frame=True, + current_vision_feats=current_vision_feats, + current_vision_pos_embeds=current_vision_pos_embeds, + feat_sizes=feat_sizes, + point_inputs=None, + mask_inputs=mask_inputs, + output_dict={}, + num_frames=inference_state["num_frames"], + track_in_reverse=False, + run_mem_encoder=False, + prev_sam_mask_logits=None, + ) + return current_out["obj_ptr"] + + @torch.no_grad() + def propagate_in_video_preflight(self, inference_state): + """Prepare inference_state and consolidate temporary outputs before tracking.""" + # Tracking has started and we don't allow adding new objects until session is reset. + inference_state["tracking_has_started"] = True + batch_size = self._get_obj_num(inference_state) + + # Consolidate per-object temporary outputs in "temp_output_dict_per_obj" and + # add them into "output_dict". + temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] + output_dict = inference_state["output_dict"] + # "consolidated_frame_inds" contains indices of those frames where consolidated + # temporary outputs have been added (either in this call or any previous calls + # to `propagate_in_video_preflight`). + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + for is_cond in [False, True]: + # Separately consolidate conditioning and non-conditioning temp outputs + storage_key = "cond_frame_outputs" if is_cond else "non_cond_frame_outputs" + # Find all the frames that contain temporary outputs for any objects + # (these should be the frames that have just received clicks for mask inputs + # via `add_new_points_or_box` or `add_new_mask`) + temp_frame_inds = set() + for obj_temp_output_dict in temp_output_dict_per_obj.values(): + temp_frame_inds.update(obj_temp_output_dict[storage_key].keys()) + consolidated_frame_inds[storage_key].update(temp_frame_inds) + # consolidate the temporary output across all objects on this frame + for frame_idx in temp_frame_inds: + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, frame_idx, is_cond=is_cond, run_mem_encoder=True + ) + # merge them into "output_dict" and also create per-object slices + output_dict[storage_key][frame_idx] = consolidated_out + self._add_output_per_object( + inference_state, frame_idx, consolidated_out, storage_key + ) + clear_non_cond_mem = self.clear_non_cond_mem_around_input and ( + self.clear_non_cond_mem_for_multi_obj or batch_size <= 1 + ) + if clear_non_cond_mem: + # clear non-conditioning memory of the surrounding frames + self._clear_non_cond_mem_around_input(inference_state, frame_idx) + + # clear temporary outputs in `temp_output_dict_per_obj` + for obj_temp_output_dict in temp_output_dict_per_obj.values(): + obj_temp_output_dict[storage_key].clear() + + # edge case: if an output is added to "cond_frame_outputs", we remove any prior + # output on the same frame in "non_cond_frame_outputs" + for frame_idx in output_dict["cond_frame_outputs"]: + output_dict["non_cond_frame_outputs"].pop(frame_idx, None) + for obj_output_dict in inference_state["output_dict_per_obj"].values(): + for frame_idx in obj_output_dict["cond_frame_outputs"]: + obj_output_dict["non_cond_frame_outputs"].pop(frame_idx, None) + for frame_idx in consolidated_frame_inds["cond_frame_outputs"]: + assert frame_idx in output_dict["cond_frame_outputs"] + consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx) + + # Make sure that the frame indices in "consolidated_frame_inds" are exactly those frames + # with either points or mask inputs (which should be true under a correct workflow). + all_consolidated_frame_inds = ( + consolidated_frame_inds["cond_frame_outputs"] + | consolidated_frame_inds["non_cond_frame_outputs"] + ) + input_frames_inds = set() + for point_inputs_per_frame in inference_state["point_inputs_per_obj"].values(): + input_frames_inds.update(point_inputs_per_frame.keys()) + for mask_inputs_per_frame in inference_state["mask_inputs_per_obj"].values(): + input_frames_inds.update(mask_inputs_per_frame.keys()) + assert all_consolidated_frame_inds == input_frames_inds + + @torch.no_grad() + def propagate_in_video( + self, + inference_state, + start_frame_idx=None, + max_frame_num_to_track=None, + reverse=False, + ): + """Propagate the input points across frames to track in the entire video.""" + self.propagate_in_video_preflight(inference_state) + + output_dict = inference_state["output_dict"] + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + obj_ids = inference_state["obj_ids"] + num_frames = inference_state["num_frames"] + batch_size = self._get_obj_num(inference_state) + if len(output_dict["cond_frame_outputs"]) == 0: + raise RuntimeError("No points are provided; please add points first") + clear_non_cond_mem = self.clear_non_cond_mem_around_input and ( + self.clear_non_cond_mem_for_multi_obj or batch_size <= 1 + ) + + # set start index, end index, and processing order + if start_frame_idx is None: + # default: start from the earliest frame with input points + start_frame_idx = min(output_dict["cond_frame_outputs"]) + if max_frame_num_to_track is None: + # default: track all the frames in the video + max_frame_num_to_track = num_frames + if reverse: + end_frame_idx = max(start_frame_idx - max_frame_num_to_track, 0) + if start_frame_idx > 0: + processing_order = range(start_frame_idx, end_frame_idx - 1, -1) + else: + processing_order = [] # skip reverse tracking if starting from frame 0 + else: + end_frame_idx = min( + start_frame_idx + max_frame_num_to_track, num_frames - 1 + ) + processing_order = range(start_frame_idx, end_frame_idx + 1) + + for frame_idx in tqdm(processing_order, desc="propagate in video"): + # We skip those frames already in consolidated outputs (these are frames + # that received input clicks or mask). Note that we cannot directly run + # batched forward on them via `_run_single_frame_inference` because the + # number of clicks on each object might be different. + if frame_idx in consolidated_frame_inds["cond_frame_outputs"]: + storage_key = "cond_frame_outputs" + current_out = output_dict[storage_key][frame_idx] + pred_masks = current_out["pred_masks"] + if clear_non_cond_mem: + # clear non-conditioning memory of the surrounding frames + self._clear_non_cond_mem_around_input(inference_state, frame_idx) + elif frame_idx in consolidated_frame_inds["non_cond_frame_outputs"]: + storage_key = "non_cond_frame_outputs" + current_out = output_dict[storage_key][frame_idx] + pred_masks = current_out["pred_masks"] + else: + storage_key = "non_cond_frame_outputs" + current_out, pred_masks = self._run_single_frame_inference( + inference_state=inference_state, + output_dict=output_dict, + frame_idx=frame_idx, + batch_size=batch_size, + is_init_cond_frame=False, + point_inputs=None, + mask_inputs=None, + reverse=reverse, + run_mem_encoder=True, + ) + output_dict[storage_key][frame_idx] = current_out + # Create slices of per-object outputs for subsequent interaction with each + # individual object after tracking. + self._add_output_per_object( + inference_state, frame_idx, current_out, storage_key + ) + inference_state["frames_already_tracked"][frame_idx] = {"reverse": reverse} + + # Resize the output mask to the original video resolution (we directly use + # the mask scores on GPU for output to avoid any CPU conversion in between) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, pred_masks + ) + yield frame_idx, obj_ids, video_res_masks + + def _add_output_per_object( + self, inference_state, frame_idx, current_out, storage_key + ): + """ + Split a multi-object output into per-object output slices and add them into + `output_dict_per_obj`. The resulting slices share the same tensor storage. + """ + maskmem_features = current_out["maskmem_features"] + assert maskmem_features is None or isinstance(maskmem_features, torch.Tensor) + + maskmem_pos_enc = current_out["maskmem_pos_enc"] + assert maskmem_pos_enc is None or isinstance(maskmem_pos_enc, list) + + output_dict_per_obj = inference_state["output_dict_per_obj"] + for obj_idx, obj_output_dict in output_dict_per_obj.items(): + obj_slice = slice(obj_idx, obj_idx + 1) + obj_out = { + "maskmem_features": None, + "maskmem_pos_enc": None, + "pred_masks": current_out["pred_masks"][obj_slice], + "obj_ptr": current_out["obj_ptr"][obj_slice], + "object_score_logits": current_out["object_score_logits"][obj_slice], + } + if maskmem_features is not None: + obj_out["maskmem_features"] = maskmem_features[obj_slice] + if maskmem_pos_enc is not None: + obj_out["maskmem_pos_enc"] = [x[obj_slice] for x in maskmem_pos_enc] + obj_output_dict[storage_key][frame_idx] = obj_out + + @torch.no_grad() + def clear_all_prompts_in_frame( + self, inference_state, frame_idx, obj_id, need_output=True + ): + """Remove all input points or mask in a specific frame for a given object.""" + obj_idx = self._obj_id_to_idx(inference_state, obj_id) + + # Clear the conditioning information on the given frame + inference_state["point_inputs_per_obj"][obj_idx].pop(frame_idx, None) + inference_state["mask_inputs_per_obj"][obj_idx].pop(frame_idx, None) + + temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] + temp_output_dict_per_obj[obj_idx]["cond_frame_outputs"].pop(frame_idx, None) + temp_output_dict_per_obj[obj_idx]["non_cond_frame_outputs"].pop(frame_idx, None) + + # Check and see if there are still any inputs left on this frame + batch_size = self._get_obj_num(inference_state) + frame_has_input = False + for obj_idx2 in range(batch_size): + if frame_idx in inference_state["point_inputs_per_obj"][obj_idx2]: + frame_has_input = True + break + if frame_idx in inference_state["mask_inputs_per_obj"][obj_idx2]: + frame_has_input = True + break + + # If this frame has no remaining inputs for any objects, we further clear its + # conditioning frame status + if not frame_has_input: + output_dict = inference_state["output_dict"] + consolidated_frame_inds = inference_state["consolidated_frame_inds"] + consolidated_frame_inds["cond_frame_outputs"].discard(frame_idx) + consolidated_frame_inds["non_cond_frame_outputs"].discard(frame_idx) + # Remove the frame's conditioning output (possibly downgrading it to non-conditioning) + out = output_dict["cond_frame_outputs"].pop(frame_idx, None) + if out is not None: + # The frame is not a conditioning frame anymore since it's not receiving inputs, + # so we "downgrade" its output (if exists) to a non-conditioning frame output. + output_dict["non_cond_frame_outputs"][frame_idx] = out + inference_state["frames_already_tracked"].pop(frame_idx, None) + # Similarly, do it for the sliced output on each object. + for obj_idx2 in range(batch_size): + obj_output_dict = inference_state["output_dict_per_obj"][obj_idx2] + obj_out = obj_output_dict["cond_frame_outputs"].pop(frame_idx, None) + if obj_out is not None: + obj_output_dict["non_cond_frame_outputs"][frame_idx] = obj_out + + # If all the conditioning frames have been removed, we also clear the tracking outputs + if len(output_dict["cond_frame_outputs"]) == 0: + self._reset_tracking_results(inference_state) + + if not need_output: + return + # Finally, output updated masks per object (after removing the inputs above) + obj_ids = inference_state["obj_ids"] + is_cond = any( + frame_idx in obj_temp_output_dict["cond_frame_outputs"] + for obj_temp_output_dict in temp_output_dict_per_obj.values() + ) + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + return frame_idx, obj_ids, video_res_masks + + @torch.no_grad() + def reset_state(self, inference_state): + """Remove all input points or mask in all frames throughout the video.""" + self._reset_tracking_results(inference_state) + # Remove all object ids + inference_state["obj_id_to_idx"].clear() + inference_state["obj_idx_to_id"].clear() + inference_state["obj_ids"].clear() + inference_state["point_inputs_per_obj"].clear() + inference_state["mask_inputs_per_obj"].clear() + inference_state["output_dict_per_obj"].clear() + inference_state["temp_output_dict_per_obj"].clear() + + def _reset_tracking_results(self, inference_state): + """Reset all tracking inputs and results across the videos.""" + for v in inference_state["point_inputs_per_obj"].values(): + v.clear() + for v in inference_state["mask_inputs_per_obj"].values(): + v.clear() + for v in inference_state["output_dict_per_obj"].values(): + v["cond_frame_outputs"].clear() + v["non_cond_frame_outputs"].clear() + for v in inference_state["temp_output_dict_per_obj"].values(): + v["cond_frame_outputs"].clear() + v["non_cond_frame_outputs"].clear() + inference_state["output_dict"]["cond_frame_outputs"].clear() + inference_state["output_dict"]["non_cond_frame_outputs"].clear() + inference_state["consolidated_frame_inds"]["cond_frame_outputs"].clear() + inference_state["consolidated_frame_inds"]["non_cond_frame_outputs"].clear() + inference_state["tracking_has_started"] = False + inference_state["frames_already_tracked"].clear() + + def _get_image_feature(self, inference_state, frame_idx, batch_size): + """Compute the image features on a given frame.""" + # Look up in the cache first + image, backbone_out = inference_state["cached_features"].get( + frame_idx, (None, None) + ) + if backbone_out is None: + # Cache miss -- we will run inference on a single image + device = inference_state["device"] + image = inference_state["images"][frame_idx].to(device).float().unsqueeze(0) + backbone_out = self.forward_image(image) + # Cache the most recent frame's feature (for repeated interactions with + # a frame; we can use an LRU cache for more frames in the future). + inference_state["cached_features"] = {frame_idx: (image, backbone_out)} + + # expand the features to have the same dimension as the number of objects + expanded_image = image.expand(batch_size, -1, -1, -1) + expanded_backbone_out = { + "backbone_fpn": backbone_out["backbone_fpn"].copy(), + "vision_pos_enc": backbone_out["vision_pos_enc"].copy(), + } + for i, feat in enumerate(expanded_backbone_out["backbone_fpn"]): + expanded_backbone_out["backbone_fpn"][i] = feat.expand( + batch_size, -1, -1, -1 + ) + for i, pos in enumerate(expanded_backbone_out["vision_pos_enc"]): + pos = pos.expand(batch_size, -1, -1, -1) + expanded_backbone_out["vision_pos_enc"][i] = pos + + features = self._prepare_backbone_features(expanded_backbone_out) + features = (expanded_image,) + features + return features + + @torch.autograd.profiler.record_function("_run_single_frame_inference") + def _run_single_frame_inference( + self, + inference_state, + output_dict, + frame_idx, + batch_size, + is_init_cond_frame, + point_inputs, + mask_inputs, + reverse, + run_mem_encoder, + prev_sam_mask_logits=None, + ): + """Run tracking on a single frame based on current inputs and previous memory.""" + # Retrieve correct image features + ( + _, + _, + current_vision_feats, + current_vision_pos_embeds, + feat_sizes, + ) = self._get_image_feature(inference_state, frame_idx, batch_size) + + # point and mask should not appear as input simultaneously on the same frame + assert point_inputs is None or mask_inputs is None + current_out = self.track_step( + frame_idx=frame_idx, + is_init_cond_frame=is_init_cond_frame, + current_vision_feats=current_vision_feats, + current_vision_pos_embeds=current_vision_pos_embeds, + feat_sizes=feat_sizes, + point_inputs=point_inputs, + mask_inputs=mask_inputs, + output_dict=output_dict, + num_frames=inference_state["num_frames"], + track_in_reverse=reverse, + run_mem_encoder=run_mem_encoder, + prev_sam_mask_logits=prev_sam_mask_logits, + ) + + # optionally offload the output to CPU memory to save GPU space + storage_device = inference_state["storage_device"] + maskmem_features = current_out["maskmem_features"] + if maskmem_features is not None: + maskmem_features = maskmem_features.to(torch.bfloat16) + maskmem_features = maskmem_features.to(storage_device, non_blocking=True) + pred_masks_gpu = current_out["pred_masks"] + # potentially fill holes in the predicted masks + if self.fill_hole_area > 0: + pred_masks_gpu = fill_holes_in_mask_scores( + pred_masks_gpu, self.fill_hole_area + ) + pred_masks = pred_masks_gpu.to(storage_device, non_blocking=True) + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + maskmem_pos_enc = self._get_maskmem_pos_enc(inference_state, current_out) + # object pointer is a small tensor, so we always keep it on GPU memory for fast access + obj_ptr = current_out["obj_ptr"] + object_score_logits = current_out["object_score_logits"] + # make a compact version of this frame's output to reduce the state size + compact_current_out = { + "maskmem_features": maskmem_features, + "maskmem_pos_enc": maskmem_pos_enc, + "pred_masks": pred_masks, + "obj_ptr": obj_ptr, + "object_score_logits": object_score_logits, + } + return compact_current_out, pred_masks_gpu + + def _run_memory_encoder( + self, + inference_state, + frame_idx, + batch_size, + high_res_masks, + object_score_logits, + is_mask_from_pts, + ): + """ + Run the memory encoder on `high_res_masks`. This is usually after applying + non-overlapping constraints to object scores. Since their scores changed, their + memory also need to be computed again with the memory encoder. + """ + # Retrieve correct image features + _, _, current_vision_feats, _, feat_sizes = self._get_image_feature( + inference_state, frame_idx, batch_size + ) + maskmem_features, maskmem_pos_enc = self._encode_new_memory( + current_vision_feats=current_vision_feats, + feat_sizes=feat_sizes, + pred_masks_high_res=high_res_masks, + object_score_logits=object_score_logits, + is_mask_from_pts=is_mask_from_pts, + ) + + # optionally offload the output to CPU memory to save GPU space + storage_device = inference_state["storage_device"] + maskmem_features = maskmem_features.to(torch.bfloat16) + maskmem_features = maskmem_features.to(storage_device, non_blocking=True) + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + maskmem_pos_enc = self._get_maskmem_pos_enc( + inference_state, {"maskmem_pos_enc": maskmem_pos_enc} + ) + return maskmem_features, maskmem_pos_enc + + def _get_maskmem_pos_enc(self, inference_state, current_out): + """ + `maskmem_pos_enc` is the same across frames and objects, so we cache it as + a constant in the inference session to reduce session storage size. + """ + model_constants = inference_state["constants"] + # "out_maskmem_pos_enc" should be either a list of tensors or None + out_maskmem_pos_enc = current_out["maskmem_pos_enc"] + if out_maskmem_pos_enc is not None: + if "maskmem_pos_enc" not in model_constants: + assert isinstance(out_maskmem_pos_enc, list) + # only take the slice for one object, since it's same across objects + maskmem_pos_enc = [x[0:1].clone() for x in out_maskmem_pos_enc] + model_constants["maskmem_pos_enc"] = maskmem_pos_enc + else: + maskmem_pos_enc = model_constants["maskmem_pos_enc"] + # expand the cached maskmem_pos_enc to the actual batch size + batch_size = out_maskmem_pos_enc[0].size(0) + expanded_maskmem_pos_enc = [ + x.expand(batch_size, -1, -1, -1) for x in maskmem_pos_enc + ] + else: + expanded_maskmem_pos_enc = None + return expanded_maskmem_pos_enc + + @torch.no_grad() + def remove_object(self, inference_state, obj_id, strict=False, need_output=True): + """ + Remove an object id from the tracking state. If strict is True, we check whether + the object id actually exists and raise an error if it doesn't exist. + """ + old_obj_idx_to_rm = inference_state["obj_id_to_idx"].get(obj_id, None) + updated_frames = [] + # Check whether this object_id to remove actually exists and possibly raise an error. + if old_obj_idx_to_rm is None: + if not strict: + return inference_state["obj_ids"], updated_frames + raise RuntimeError( + f"Cannot remove object id {obj_id} as it doesn't exist. " + f"All existing object ids: {inference_state['obj_ids']}." + ) + + # If this is the only remaining object id, we simply reset the state. + if len(inference_state["obj_id_to_idx"]) == 1: + self.reset_state(inference_state) + return inference_state["obj_ids"], updated_frames + + # There are still remaining objects after removing this object id. In this case, + # we need to delete the object storage from inference state tensors. + # Step 0: clear the input on those frames where this object id has point or mask input + # (note that this step is required as it might downgrade conditioning frames to + # non-conditioning ones) + obj_input_frames_inds = set() + obj_input_frames_inds.update( + inference_state["point_inputs_per_obj"][old_obj_idx_to_rm] + ) + obj_input_frames_inds.update( + inference_state["mask_inputs_per_obj"][old_obj_idx_to_rm] + ) + for frame_idx in obj_input_frames_inds: + self.clear_all_prompts_in_frame( + inference_state, frame_idx, obj_id, need_output=False + ) + + # Step 1: Update the object id mapping (note that it must be done after Step 0, + # since Step 0 still requires the old object id mappings in inference_state) + old_obj_ids = inference_state["obj_ids"] + old_obj_inds = list(range(len(old_obj_ids))) + remain_old_obj_inds = old_obj_inds.copy() + remain_old_obj_inds.remove(old_obj_idx_to_rm) + new_obj_ids = [old_obj_ids[old_idx] for old_idx in remain_old_obj_inds] + new_obj_inds = list(range(len(new_obj_ids))) + # build new mappings + old_idx_to_new_idx = dict(zip(remain_old_obj_inds, new_obj_inds)) + inference_state["obj_id_to_idx"] = dict(zip(new_obj_ids, new_obj_inds)) + inference_state["obj_idx_to_id"] = dict(zip(new_obj_inds, new_obj_ids)) + inference_state["obj_ids"] = new_obj_ids + + # Step 2: For per-object tensor storage, we shift their obj_idx in the dict keys. + # (note that "consolidated_frame_inds" doesn't need to be updated in this step as + # it's already handled in Step 0) + def _map_keys(container): + new_kvs = [] + for k in old_obj_inds: + v = container.pop(k) + if k in old_idx_to_new_idx: + new_kvs.append((old_idx_to_new_idx[k], v)) + container.update(new_kvs) + + _map_keys(inference_state["point_inputs_per_obj"]) + _map_keys(inference_state["mask_inputs_per_obj"]) + _map_keys(inference_state["output_dict_per_obj"]) + _map_keys(inference_state["temp_output_dict_per_obj"]) + + # Step 3: For packed tensor storage, we index the remaining ids and rebuild the per-object slices. + def _slice_state(output_dict, storage_key): + for frame_idx, out in output_dict[storage_key].items(): + out["maskmem_features"] = out["maskmem_features"][remain_old_obj_inds] + out["maskmem_pos_enc"] = [ + x[remain_old_obj_inds] for x in out["maskmem_pos_enc"] + ] + # "maskmem_pos_enc" is the same across frames, so we only need to store one copy of it + out["maskmem_pos_enc"] = self._get_maskmem_pos_enc(inference_state, out) + out["pred_masks"] = out["pred_masks"][remain_old_obj_inds] + out["obj_ptr"] = out["obj_ptr"][remain_old_obj_inds] + out["object_score_logits"] = out["object_score_logits"][ + remain_old_obj_inds + ] + # also update the per-object slices + self._add_output_per_object( + inference_state, frame_idx, out, storage_key + ) + + _slice_state(inference_state["output_dict"], "cond_frame_outputs") + _slice_state(inference_state["output_dict"], "non_cond_frame_outputs") + + # Step 4: Further collect the outputs on those frames in `obj_input_frames_inds`, which + # could show an updated mask for objects previously occluded by the object being removed + if need_output: + temp_output_dict_per_obj = inference_state["temp_output_dict_per_obj"] + for frame_idx in obj_input_frames_inds: + is_cond = any( + frame_idx in obj_temp_output_dict["cond_frame_outputs"] + for obj_temp_output_dict in temp_output_dict_per_obj.values() + ) + consolidated_out = self._consolidate_temp_output_across_obj( + inference_state, + frame_idx, + is_cond=is_cond, + run_mem_encoder=False, + consolidate_at_video_res=True, + ) + _, video_res_masks = self._get_orig_video_res_output( + inference_state, consolidated_out["pred_masks_video_res"] + ) + updated_frames.append((frame_idx, video_res_masks)) + + return inference_state["obj_ids"], updated_frames + + def _clear_non_cond_mem_around_input(self, inference_state, frame_idx): + """ + Remove the non-conditioning memory around the input frame. When users provide + correction clicks, the surrounding frames' non-conditioning memories can still + contain outdated object appearance information and could confuse the model. + + This method clears those non-conditioning memories surrounding the interacted + frame to avoid giving the model both old and new information about the object. + """ + r = self.memory_temporal_stride_for_eval + frame_idx_begin = frame_idx - r * self.num_maskmem + frame_idx_end = frame_idx + r * self.num_maskmem + output_dict = inference_state["output_dict"] + non_cond_frame_outputs = output_dict["non_cond_frame_outputs"] + for t in range(frame_idx_begin, frame_idx_end + 1): + non_cond_frame_outputs.pop(t, None) + for obj_output_dict in inference_state["output_dict_per_obj"].values(): + obj_output_dict["non_cond_frame_outputs"].pop(t, None) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/amg.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/amg.py new file mode 100644 index 0000000000000000000000000000000000000000..66f8fa15ebed0e60ab5441d1790ba30de8c11db4 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/amg.py @@ -0,0 +1,523 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import math +from copy import deepcopy +from dataclasses import dataclass +from itertools import product +from typing import Any, Dict, Generator, ItemsView, List, Tuple + +import numpy as np +import torch + + +@dataclass +class RLEData: + alt_lens_nt: torch.Tensor + counts_init: torch.Tensor + b: int + h: int + w: int + + def __len__(self): + return self.b + + +def nt_index_select_dim_0(nt, index): + values = nt.values() + offsets = nt.offsets() + lengths = offsets.diff() + offsets_index = offsets[index].cpu() + lengths_index = lengths[index].cpu() + indices = [o + torch.arange(l) for (o, l) in zip(offsets_index, lengths_index)] + indices = torch.cat(indices).to(values.device) + values_index = torch.index_select(values, 0, indices) + lengths_index = lengths_index.to(values.device) + return torch.nested.nested_tensor_from_jagged(values_index, lengths=lengths_index) + + +def nt_cat_dim_0(nts: List[torch.Tensor]): + all_values = [] + all_lengths = [] + for nt in nts: + all_values.append(nt.values()) + all_lengths.append(nt.offsets().diff()) + new_values = torch.cat(all_values) + new_lengths = torch.cat(all_lengths) + return torch.nested.nested_tensor_from_jagged(new_values, lengths=new_lengths) + + +# Very lightly adapted from https://github.com/facebookresearch/segment-anything/blob/main/segment_anything/utils/amg.py +class MaskData: + """ + A structure for storing masks and their related data in batched format. + Implements basic filtering and concatenation. + """ + + def __init__(self, **kwargs) -> None: + for v in kwargs.values(): + assert isinstance(v, (list, np.ndarray, torch.Tensor, RLEData)), ( + "MaskData only supports list, numpy arrays, and torch tensors." + ) + self._stats = dict(**kwargs) + + def __setitem__(self, key: str, item: Any) -> None: + assert isinstance(item, (list, np.ndarray, torch.Tensor, RLEData)), ( + "MaskData only supports list, numpy arrays, and torch tensors." + ) + self._stats[key] = item + + def __delitem__(self, key: str) -> None: + del self._stats[key] + + def __getitem__(self, key: str) -> Any: + return self._stats[key] + + def items(self) -> ItemsView[str, Any]: + return self._stats.items() + + def filter(self, keep: torch.Tensor) -> None: + for k, v in self._stats.items(): + if v is None: + self._stats[k] = None + elif isinstance(v, torch.Tensor): + # self._stats[k] = v[torch.as_tensor(keep, device=v.device)] + self._stats[k] = v[keep] + elif isinstance(v, np.ndarray): + self._stats[k] = v[keep.detach().cpu().numpy()] + elif isinstance(v, list) and keep.dtype == torch.bool: + self._stats[k] = [a for i, a in enumerate(v) if keep[i]] + elif isinstance(v, list): + self._stats[k] = [v[i] for i in keep] + elif isinstance(v, RLEData): + new_alt_lens_nt = nt_index_select_dim_0(v.alt_lens_nt, keep) + self._stats[k] = RLEData( + alt_lens_nt=new_alt_lens_nt, + counts_init=v.counts_init[keep], + b=new_alt_lens_nt.size(0), + h=v.h, + w=v.w, + ) + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def cat(self, new_stats: "MaskData") -> None: + for k, v in new_stats.items(): + if k not in self._stats or self._stats[k] is None: + self._stats[k] = deepcopy(v) + elif isinstance(v, torch.Tensor): + self._stats[k] = torch.cat([self._stats[k], v], dim=0) + elif isinstance(v, np.ndarray): + self._stats[k] = np.concatenate([self._stats[k], v], axis=0) + elif isinstance(v, list): + self._stats[k] = self._stats[k] + deepcopy(v) + elif isinstance(v, RLEData): + assert self._stats[k].h == v.h + assert self._stats[k].w == v.w + self._stats[k] = RLEData( + alt_lens_nt=nt_cat_dim_0( + [self._stats[k].alt_lens_nt, v.alt_lens_nt] + ), + counts_init=torch.cat([self._stats[k].counts_init, v.counts_init]), + b=self._stats[k].b + v.b, + h=v.h, + w=v.w, + ) + else: + raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.") + + def to_numpy(self) -> None: + for k, v in self._stats.items(): + if isinstance(v, torch.Tensor): + self._stats[k] = v.float().detach().cpu().numpy() + + +def is_box_near_crop_edge_torch( + boxes: torch.Tensor, + crop_box: List[int], + crop_box_torch: torch.Tensor, + orig_box_torch: torch.Tensor, + atol: float = 20.0, +) -> torch.Tensor: + """Filter masks at the edge of a crop, but not at the edge of the original image.""" + boxes = uncrop_boxes_xyxy(boxes, crop_box).float() + near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0) + near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0) + near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge) + return torch.any(near_crop_edge, dim=1) + + +def is_box_near_crop_edge( + boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0 +) -> torch.Tensor: + crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device) + orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device) + return is_box_near_crop_edge_torch( + boxes, crop_box, crop_box_torch, orig_box_torch, atol + ) + + +def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor: + box_xywh = deepcopy(box_xyxy) + box_xywh[2] = box_xywh[2] - box_xywh[0] + box_xywh[3] = box_xywh[3] - box_xywh[1] + return box_xywh + + +def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]: + assert len(args) > 0 and all(len(a) == len(args[0]) for a in args), ( + "Batched iteration must have inputs of all the same size." + ) + n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0) + for b in range(n_batches): + yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args] + + +def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]: + """ + Encodes masks to an uncompressed RLE, in the format expected by + pycoco tools. + """ + # Put in fortran order and flatten h,w + b, h, w = tensor.shape + tensor = tensor.permute(0, 2, 1).flatten(1) + + # Compute change indices + diff = tensor[:, 1:] ^ tensor[:, :-1] + change_indices = diff.nonzero() + + # Encode run length + out = [] + for i in range(b): + cur_idxs = change_indices[change_indices[:, 0] == i, 1] + cur_idxs = torch.cat( + [ + torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device), + cur_idxs + 1, + torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device), + ] + ) + btw_idxs = cur_idxs[1:] - cur_idxs[:-1] + counts = [] if tensor[i, 0] == 0 else [0] + counts.extend(btw_idxs.detach().cpu().tolist()) + out.append({"size": [h, w], "counts": counts}) + return out + + +def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray: + """Compute a binary mask from an uncompressed RLE.""" + h, w = rle["size"] + mask = np.empty(h * w, dtype=bool) + idx = 0 + parity = False + for count in rle["counts"]: + mask[idx : idx + count] = parity + idx += count + parity ^= True + mask = mask.reshape(w, h) + return mask.transpose() # Put in C order + + +# @torch.compile(fullgraph=True, dynamic=True) +def _mask_to_rle_pytorch_2_0_0(tensor: torch.Tensor) -> (torch.Tensor, torch.Tensor): + """ + Encodes masks to an uncompressed RLE, in the format expected by + pycoco tools. + """ + # Put in fortran order and flatten h,w + b, h, w = tensor.shape + tensor = tensor.permute(0, 2, 1).flatten(1) + + # Compute change indices + diff = tensor[:, 1:] ^ tensor[:, :-1] + # a = torch.tensor([[True]]) + a = torch.ones((1, 1), dtype=bool, device=diff.device) + # if diff.is_cuda: + # a = a.pin_memory().cuda() + # # a = a.to(diff.device) + a = a.expand_as(diff.narrow(1, 0, 1)) + diff = torch.cat([a, diff, a], dim=1) + return diff + + +# @torch.compile(fullgraph=True, dynamic=True) +def _mask_to_rle_pytorch_2_0_1( + tensor: torch.Tensor, diff: torch.Tensor, change_indices: torch.Tensor +) -> (torch.Tensor, torch.Tensor): + tensor = tensor.permute(0, 2, 1).flatten(1) + + alt_lens = diff.sum(dim=1) + + all_cur_idx = change_indices[:, 1] + if all_cur_idx.numel() == 0: + all_cur_idx_0 = all_cur_idx + all_cur_idx_1 = all_cur_idx + else: + all_cur_idx_0 = all_cur_idx.narrow(0, 1, all_cur_idx.size(0) - 1) + all_cur_idx_1 = all_cur_idx.narrow(0, 0, 1) + all_btw_idx = torch.cat([all_cur_idx_0, all_cur_idx_1]) + all_btw_idx = all_btw_idx - all_cur_idx + + alt_lens_nt = torch.nested.nested_tensor_from_jagged(all_btw_idx, lengths=alt_lens) + # Encode run length + counts_init = tensor[:, 0] == 0 + return alt_lens_nt, counts_init + + +def _mask_to_rle_pytorch_2_0(tensor: torch.Tensor) -> RLEData: + b, h, w = tensor.shape + with torch.autograd.profiler.record_function( + "mask_to_rle_pytorch_2: _mask_to_rle_pytorch_2_0_0" + ): + diff = _mask_to_rle_pytorch_2_0_0(tensor) + with torch.autograd.profiler.record_function("mask_to_rle_pytorch_2: nonzero"): + # NOTE: While we could operate on less chunks, a set number of chunks prevents recompilations + # if diff.numel() > 2147483646: + # num_chunks = (diff.numel() + 2147483646) // 2147483646 + # change_indices = torch.cat([d.nonzero() for d in diff.chunk(num_chunks)]) + # else: + # change_indices = diff.nonzero() + num_chunks = 8 + assert num_chunks >= ((diff.numel() + 2147483646) // 2147483646), ( + "Needed more chunks than expected." + ) + change_indices = torch.cat([d.nonzero() for d in diff.chunk(num_chunks)]) + with torch.autograd.profiler.record_function( + "mask_to_rle_pytorch_2: _mask_to_rle_pytorch_2_0_1" + ): + alt_lens_nt, counts_init = _mask_to_rle_pytorch_2_0_1( + tensor, diff, change_indices + ) + return RLEData(alt_lens_nt=alt_lens_nt, counts_init=counts_init, b=b, h=h, w=w) + + +def _mask_to_rle_pytorch_2_1(rle_data: RLEData): + with torch.autograd.profiler.record_function( + "mask_to_rle_pytorch_2: Encode run length" + ): + out = [] + alt_lens = rle_data.alt_lens_nt.offsets().diff() + all_btw_idx = rle_data.alt_lens_nt.values() + alt_lens = alt_lens.tolist() + all_btw_idx = all_btw_idx.tolist() + counts_init = rle_data.counts_init.tolist() + offset = 0 + for i, ci in zip(range(rle_data.b), counts_init): + btw_idxs = all_btw_idx[offset : offset + alt_lens[i]][:-1] + offset += alt_lens[i] + counts = [] if ci else [0] + counts.extend(btw_idxs) + out.append({"size": [rle_data.h, rle_data.w], "counts": counts}) + + return out + + +def mask_to_rle_pytorch_2(tensor: torch.Tensor) -> List[Dict[str, Any]]: + with torch.autograd.profiler.record_function("mask_to_rle_pytorch_2"): + return _mask_to_rle_pytorch_2_1(_mask_to_rle_pytorch_2_0(tensor)) + + +def area_from_rle(rle: Dict[str, Any]) -> int: + return sum(rle["counts"][1::2]) + + +# TODO: Turn this on if you can mitigate recompiles! +# @torch.compile(fullgraph=True, dynamic=True) +def calculate_stability_score( + masks: torch.Tensor, mask_threshold: float, threshold_offset: float +) -> torch.Tensor: + """ + Computes the stability score for a batch of masks. The stability + score is the IoU between the binary masks obtained by thresholding + the predicted mask logits at high and low values. + """ + # One mask is always contained inside the other. + # Save memory by preventing unnecessary cast to torch.int64 + intersections = ( + (masks > (mask_threshold + threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + unions = ( + (masks > (mask_threshold - threshold_offset)) + .sum(-1, dtype=torch.int16) + .sum(-1, dtype=torch.int32) + ) + return intersections / unions + + +def build_point_grid(n_per_side: int) -> np.ndarray: + """Generates a 2D grid of points evenly spaced in [0,1]x[0,1].""" + offset = 1 / (2 * n_per_side) + points_one_side = np.linspace(offset, 1 - offset, n_per_side) + points_x = np.tile(points_one_side[None, :], (n_per_side, 1)) + points_y = np.tile(points_one_side[:, None], (1, n_per_side)) + points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2) + return points + + +def build_all_layer_point_grids( + n_per_side: int, n_layers: int, scale_per_layer: int +) -> List[np.ndarray]: + """Generates point grids for all crop layers.""" + points_by_layer = [] + for i in range(n_layers + 1): + n_points = int(n_per_side / (scale_per_layer**i)) + points_by_layer.append(build_point_grid(n_points)) + return points_by_layer + + +def generate_crop_boxes( + im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float +) -> Tuple[List[List[int]], List[int]]: + """ + Generates a list of crop boxes of different sizes. Each layer + has (2**i)**2 boxes for the ith layer. + """ + crop_boxes, layer_idxs = [], [] + im_h, im_w = im_size + short_side = min(im_h, im_w) + + # Original image + crop_boxes.append([0, 0, im_w, im_h]) + layer_idxs.append(0) + + def crop_len(orig_len, n_crops, overlap): + return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops)) + + for i_layer in range(n_layers): + n_crops_per_side = 2 ** (i_layer + 1) + overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side)) + + crop_w = crop_len(im_w, n_crops_per_side, overlap) + crop_h = crop_len(im_h, n_crops_per_side, overlap) + + crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)] + crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)] + + # Crops in XYWH format + for x0, y0 in product(crop_box_x0, crop_box_y0): + box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)] + crop_boxes.append(box) + layer_idxs.append(i_layer + 1) + + return crop_boxes, layer_idxs + + +def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0, x0, y0]]).pin_memory() + offset = offset.to(device=boxes.device, non_blocking=True) + # Check if boxes has a channel dimension + if len(boxes.shape) == 3: + offset = offset.unsqueeze(1) + return boxes + offset + + +def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor: + x0, y0, _, _ = crop_box + offset = torch.tensor([[x0, y0]]).pin_memory() + offset = offset.to(device=points.device, non_blocking=True) + # Check if points has a channel dimension + if len(points.shape) == 3: + offset = offset.unsqueeze(1) + return points + offset + + +def uncrop_masks( + masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int +) -> torch.Tensor: + x0, y0, x1, y1 = crop_box + if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h: + return masks + # Coordinate transform masks + pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0) + pad = (x0, pad_x - x0, y0, pad_y - y0) + return torch.nn.functional.pad(masks, pad, value=0) + + +def remove_small_regions( + mask: np.ndarray, area_thresh: float, mode: str +) -> Tuple[np.ndarray, bool]: + """ + Removes small disconnected regions and holes in a mask. Returns the + mask and an indicator of if the mask has been modified. + """ + import cv2 # type: ignore + + assert mode in ["holes", "islands"] + correct_holes = mode == "holes" + working_mask = (correct_holes ^ mask).astype(np.uint8) + n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8) + sizes = stats[:, -1][1:] # Row 0 is background label + small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh] + if len(small_regions) == 0: + return mask, False + fill_labels = [0] + small_regions + if not correct_holes: + fill_labels = [i for i in range(n_labels) if i not in fill_labels] + # If every region is below threshold, keep largest + if len(fill_labels) == 0: + fill_labels = [int(np.argmax(sizes)) + 1] + mask = np.isin(regions, fill_labels) + return mask, True + + +def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]: + from pycocotools import mask as mask_utils # type: ignore + + h, w = uncompressed_rle["size"] + rle = mask_utils.frPyObjects(uncompressed_rle, h, w) + rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json + return rle + + +# TODO: Turn this on if you can mitigate recompiles! +# @torch.compile(fullgraph=True, dynamic=True) +def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor: + """ + Calculates boxes in XYXY format around masks. Return [0,0,0,0] for + an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4. + """ + # # torch.max below raises an error on empty inputs, just skip in this case + # if torch.numel(masks) == 0: + # return torch.zeros(*masks.shape[:-2], 4, device=masks.device) + + # Normalize shape to CxHxW + shape = masks.shape + h, w = shape[-2:] + if len(shape) > 2: + masks = masks.flatten(0, -3) + else: + masks = masks.unsqueeze(0) + + # Get top and bottom edges + in_height, _ = torch.max(masks, dim=-1) + in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :] + bottom_edges, _ = torch.max(in_height_coords, dim=-1) + in_height_coords = in_height_coords + h * (~in_height) + top_edges, _ = torch.min(in_height_coords, dim=-1) + + # Get left and right edges + in_width, _ = torch.max(masks, dim=-2) + in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :] + right_edges, _ = torch.max(in_width_coords, dim=-1) + in_width_coords = in_width_coords + w * (~in_width) + left_edges, _ = torch.min(in_width_coords, dim=-1) + + # If the mask is empty the right edge will be to the left of the left edge. + # Replace these boxes with [0, 0, 0, 0] + empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges) + out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1) + out = out * (~empty_filter).unsqueeze(-1) + + # Return to original shape + if len(shape) > 2: + out = out.reshape(*shape[:-2], 4) + else: + out = out[0] + + return out diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/misc.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/misc.py new file mode 100644 index 0000000000000000000000000000000000000000..b98fbcdae461ec191a6f0d68260d795bc672f4bf --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/misc.py @@ -0,0 +1,382 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import os +import warnings +from threading import Thread +from typing import Tuple, Union + +import numpy as np +import torch +from PIL import Image +from tqdm import tqdm + + +def get_sdpa_settings(): + if torch.cuda.is_available(): + old_gpu = torch.cuda.get_device_properties(0).major < 7 + # only use Flash Attention on Ampere (8.0) or newer GPUs + use_flash_attn = torch.cuda.get_device_properties(0).major >= 8 + if not use_flash_attn: + warnings.warn( + "Flash Attention is disabled as it requires a GPU with Ampere (8.0) CUDA capability.", + category=UserWarning, + stacklevel=2, + ) + # keep math kernel for PyTorch versions before 2.2 (Flash Attention v2 is only + # available on PyTorch 2.2+, while Flash Attention v1 cannot handle all cases) + pytorch_version = tuple(int(v) for v in torch.__version__.split(".")[:2]) + if pytorch_version < (2, 2): + warnings.warn( + f"You are using PyTorch {torch.__version__} without Flash Attention v2 support. " + "Consider upgrading to PyTorch 2.2+ for Flash Attention v2 (which could be faster).", + category=UserWarning, + stacklevel=2, + ) + math_kernel_on = pytorch_version < (2, 2) or not use_flash_attn + else: + old_gpu = True + use_flash_attn = False + math_kernel_on = True + + return old_gpu, use_flash_attn, math_kernel_on + + +def get_connected_components(mask): + """ + Get the connected components (8-connectivity) of binary masks of shape (N, 1, H, W). + + Inputs: + - mask: A binary mask tensor of shape (N, 1, H, W), where 1 is foreground and 0 is + background. + + Outputs: + - labels: A tensor of shape (N, 1, H, W) containing the connected component labels + for foreground pixels and 0 for background pixels. + - counts: A tensor of shape (N, 1, H, W) containing the area of the connected + components for foreground pixels and 0 for background pixels. + """ + from sam2 import _C + + return _C.get_connected_componnets(mask.to(torch.uint8).contiguous()) + + +def mask_to_box(masks: torch.Tensor): + """ + compute bounding box given an input mask + + Inputs: + - masks: [B, 1, H, W] masks, dtype=torch.Tensor + + Returns: + - box_coords: [B, 1, 4], contains (x, y) coordinates of top left and bottom right box corners, dtype=torch.Tensor + """ + B, _, h, w = masks.shape + device = masks.device + xs = torch.arange(w, device=device, dtype=torch.int32) + ys = torch.arange(h, device=device, dtype=torch.int32) + grid_xs, grid_ys = torch.meshgrid(xs, ys, indexing="xy") + grid_xs = grid_xs[None, None, ...].expand(B, 1, h, w) + grid_ys = grid_ys[None, None, ...].expand(B, 1, h, w) + min_xs, _ = torch.min(torch.where(masks, grid_xs, w).flatten(-2), dim=-1) + max_xs, _ = torch.max(torch.where(masks, grid_xs, -1).flatten(-2), dim=-1) + min_ys, _ = torch.min(torch.where(masks, grid_ys, h).flatten(-2), dim=-1) + max_ys, _ = torch.max(torch.where(masks, grid_ys, -1).flatten(-2), dim=-1) + bbox_coords = torch.stack((min_xs, min_ys, max_xs, max_ys), dim=-1) + + return bbox_coords + + +def _load_img_as_tensor(img_path, image_size): + img_pil = Image.open(img_path) + img_np = np.array(img_pil.convert("RGB").resize((image_size, image_size))) + if img_np.dtype == np.uint8: # np.uint8 is expected for JPEG images + img_np = img_np / 255.0 + else: + raise RuntimeError(f"Unknown image dtype: {img_np.dtype} on {img_path}") + img = torch.from_numpy(img_np).permute(2, 0, 1) + video_width, video_height = img_pil.size # the original video size + return img, video_height, video_width + + +class AsyncVideoFrameLoader: + """ + A list of video frames to be load asynchronously without blocking session start. + """ + + def __init__( + self, + img_paths, + image_size, + offload_video_to_cpu, + img_mean, + img_std, + compute_device, + ): + self.img_paths = img_paths + self.image_size = image_size + self.offload_video_to_cpu = offload_video_to_cpu + self.img_mean = img_mean + self.img_std = img_std + # items in `self.images` will be loaded asynchronously + self.images = [None] * len(img_paths) + # catch and raise any exceptions in the async loading thread + self.exception = None + # video_height and video_width be filled when loading the first image + self.video_height = None + self.video_width = None + self.compute_device = compute_device + + # load the first frame to fill video_height and video_width and also + # to cache it (since it's most likely where the user will click) + self.__getitem__(0) + + # load the rest of frames asynchronously without blocking the session start + def _load_frames(): + try: + for n in tqdm(range(len(self.images)), desc="frame loading (JPEG)"): + self.__getitem__(n) + except Exception as e: + self.exception = e + + self.thread = Thread(target=_load_frames, daemon=True) + self.thread.start() + + def __getitem__(self, index): + if self.exception is not None: + raise RuntimeError("Failure in frame loading thread") from self.exception + + img = self.images[index] + if img is not None: + return img + + img, video_height, video_width = _load_img_as_tensor( + self.img_paths[index], self.image_size + ) + self.video_height = video_height + self.video_width = video_width + # normalize by mean and std + img -= self.img_mean + img /= self.img_std + if not self.offload_video_to_cpu: + img = img.to(self.compute_device, non_blocking=True) + self.images[index] = img + return img + + def __len__(self): + return len(self.images) + + +def load_video_frames( + video_path, + image_size, + offload_video_to_cpu, + img_mean=(0.485, 0.456, 0.406), + img_std=(0.229, 0.224, 0.225), + async_loading_frames=False, + compute_device=torch.device("cuda"), +): + """ + Load the video frames from video_path. The frames are resized to image_size as in + the model and are loaded to GPU if offload_video_to_cpu=False. This is used by the demo. + """ + is_bytes = isinstance(video_path, bytes) + is_str = isinstance(video_path, str) + is_mp4_path = is_str and os.path.splitext(video_path)[-1] in [".mp4", ".MP4"] + if is_bytes or is_mp4_path: + return load_video_frames_from_video_file( + video_path=video_path, + image_size=image_size, + offload_video_to_cpu=offload_video_to_cpu, + img_mean=img_mean, + img_std=img_std, + compute_device=compute_device, + ) + elif is_str and os.path.isdir(video_path): + return load_video_frames_from_jpg_images( + video_path=video_path, + image_size=image_size, + offload_video_to_cpu=offload_video_to_cpu, + img_mean=img_mean, + img_std=img_std, + async_loading_frames=async_loading_frames, + compute_device=compute_device, + ) + else: + raise NotImplementedError( + "Only MP4 video and JPEG folder are supported at this moment" + ) + + +def load_video_frames_from_jpg_images( + video_path, + image_size, + offload_video_to_cpu, + img_mean=(0.485, 0.456, 0.406), + img_std=(0.229, 0.224, 0.225), + async_loading_frames=False, + compute_device=torch.device("cuda"), +): + """ + Load the video frames from a directory of JPEG files (".jpg" format). + + The frames are resized to image_size x image_size and are loaded to GPU if + `offload_video_to_cpu` is `False` and to CPU if `offload_video_to_cpu` is `True`. + + You can load a frame asynchronously by setting `async_loading_frames` to `True`. + """ + if isinstance(video_path, str) and os.path.isdir(video_path): + jpg_folder = video_path + else: + raise NotImplementedError( + "Only JPEG frames are supported at this moment. For video files, you may use " + "ffmpeg (https://ffmpeg.org/) to extract frames into a folder of JPEG files, such as \n" + "```\n" + "ffmpeg -i .mp4 -q:v 2 -start_number 0 /'%05d.jpg'\n" + "```\n" + "where `-q:v` generates high-quality JPEG frames and `-start_number 0` asks " + "ffmpeg to start the JPEG file from 00000.jpg." + ) + + frame_names = [ + p + for p in os.listdir(jpg_folder) + if os.path.splitext(p)[-1] in [".jpg", ".jpeg", ".JPG", ".JPEG"] + ] + frame_names.sort(key=lambda p: int(os.path.splitext(p)[0])) + num_frames = len(frame_names) + if num_frames == 0: + raise RuntimeError(f"no images found in {jpg_folder}") + img_paths = [os.path.join(jpg_folder, frame_name) for frame_name in frame_names] + img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None] + img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None] + + if async_loading_frames: + lazy_images = AsyncVideoFrameLoader( + img_paths, + image_size, + offload_video_to_cpu, + img_mean, + img_std, + compute_device, + ) + return lazy_images, lazy_images.video_height, lazy_images.video_width + + images = torch.zeros(num_frames, 3, image_size, image_size, dtype=torch.float32) + for n, img_path in enumerate(tqdm(img_paths, desc="frame loading (JPEG)")): + images[n], video_height, video_width = _load_img_as_tensor(img_path, image_size) + if not offload_video_to_cpu: + images = images.to(compute_device) + img_mean = img_mean.to(compute_device) + img_std = img_std.to(compute_device) + # normalize by mean and std + images -= img_mean + images /= img_std + return images, video_height, video_width + + +def load_video_frames_from_video_file( + video_path, + image_size, + offload_video_to_cpu, + img_mean=(0.485, 0.456, 0.406), + img_std=(0.229, 0.224, 0.225), + compute_device=torch.device("cuda"), +): + """Load the video frames from a video file.""" + import decord + + img_mean = torch.tensor(img_mean, dtype=torch.float32)[:, None, None] + img_std = torch.tensor(img_std, dtype=torch.float32)[:, None, None] + # Get the original video height and width + decord.bridge.set_bridge("torch") + video_height, video_width, _ = decord.VideoReader(video_path).next().shape + # Iterate over all frames in the video + images = [] + for frame in decord.VideoReader(video_path, width=image_size, height=image_size): + images.append(frame.permute(2, 0, 1)) + + images = torch.stack(images, dim=0).float() / 255.0 + if not offload_video_to_cpu: + images = images.to(compute_device) + img_mean = img_mean.to(compute_device) + img_std = img_std.to(compute_device) + # normalize by mean and std + images -= img_mean + images /= img_std + return images, video_height, video_width + + +def fill_holes_in_mask_scores(mask, max_area): + """ + A post processor to fill small holes in mask scores with area under `max_area`. + """ + # Holes are those connected components in background with area <= self.max_area + # (background regions are those with mask scores <= 0) + assert max_area > 0, "max_area must be positive" + + input_mask = mask + try: + labels, areas = get_connected_components(mask <= 0) + is_hole = (labels > 0) & (areas <= max_area) + # We fill holes with a small positive mask score (0.1) to change them to foreground. + mask = torch.where(is_hole, 0.1, mask) + except Exception as e: + # Skip the post-processing step on removing small holes if the CUDA kernel fails + warnings.warn( + f"{e}\n\nSkipping the post-processing step due to the error above. You can " + "still use SAM 2 and it's OK to ignore the error above, although some post-processing " + "functionality may be limited (which doesn't affect the results in most cases; see " + "https://github.com/facebookresearch/sam2/blob/main/INSTALL.md).", + category=UserWarning, + stacklevel=2, + ) + mask = input_mask + + return mask + + +def concat_points(old_point_inputs, new_points, new_labels): + """Add new points and labels to previous point inputs (add at the end).""" + if old_point_inputs is None: + points, labels = new_points, new_labels + else: + points = torch.cat([old_point_inputs["point_coords"], new_points], dim=1) + labels = torch.cat([old_point_inputs["point_labels"], new_labels], dim=1) + + return {"point_coords": points, "point_labels": labels} + + +def get_image_size(image: Union[np.ndarray, torch.Tensor]): + if isinstance(image, np.ndarray): + return image.shape[:2] + elif isinstance(image, torch.Tensor): + _, h, w = image.shape + return (h, w) + elif isinstance(image, Image): + w, h = image.size + return (h, w) + else: + raise NotImplementedError( + f"Only support np.ndarray, torch.Tensoror PIL Image, but got {type(image)}" + ) + + +def crop_image( + image: Union[np.ndarray, torch.Tensor], crop_box: Tuple[int, int, int, int] +): + x0, y0, x1, y1 = crop_box + if isinstance(image, np.ndarray): + # HxWxC + return image[y0:y1, x0:x1, :] + elif isinstance(image, torch.Tensor): + # CxHxW + return image[:, y0:y1, x0:x1] + else: + raise ValueError( + "Expected image to be of type np.ndarray or " + f"torch.Tensor, but got {type(image)}" + ) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/transforms.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..c616233050bd5b2ab8d1ea873163f8253f68d20a --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/sam2/utils/transforms.py @@ -0,0 +1,170 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +import warnings + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torchvision.transforms import Normalize, Resize, ToTensor + + +class SAM2Transforms(nn.Module): + def __init__( + self, resolution, mask_threshold, max_hole_area=0.0, max_sprinkle_area=0.0 + ): + """ + Transforms for SAM2. + """ + super().__init__() + self.resolution = resolution + self.mask_threshold = mask_threshold + self.max_hole_area = max_hole_area + self.max_sprinkle_area = max_sprinkle_area + self.mean = [0.485, 0.456, 0.406] + self.std = [0.229, 0.224, 0.225] + self.to_tensor = ToTensor() + # self.transforms = torch.jit.script( + self.transforms = nn.Sequential( + Resize((self.resolution, self.resolution)), + Normalize(self.mean, self.std), + ) + + def __call__(self, x): + x = self.to_tensor(x) + return self.transforms(x) + + def forward_batch(self, img_list): + img_batch = [self.transforms(self.to_tensor(img)) for img in img_list] + img_batch = torch.stack(img_batch, dim=0) + return img_batch + + def transform_coords( + self, coords: torch.Tensor, normalize=False, orig_hw=None + ) -> torch.Tensor: + """ + Expects a torch tensor with length 2 in the last dimension. The coordinates can be in absolute image or normalized coordinates, + If the coords are in absolute image coordinates, normalize should be set to True and original image size is required. + + Returns + Un-normalized coordinates in the range of [0, 1] which is expected by the SAM2 model. + """ + if normalize: + assert orig_hw is not None + h, w = orig_hw + coords = coords.clone() + coords[..., 0] = coords[..., 0] / w + coords[..., 1] = coords[..., 1] / h + + coords = coords * self.resolution # unnormalize coords + return coords + + def transform_boxes( + self, boxes: torch.Tensor, normalize=False, orig_hw=None + ) -> torch.Tensor: + """ + Expects a tensor of shape Bx4. The coordinates can be in absolute image or normalized coordinates, + if the coords are in absolute image coordinates, normalize should be set to True and original image size is required. + """ + boxes = self.transform_coords(boxes.reshape(-1, 2, 2), normalize, orig_hw) + return boxes + + def postprocess_masks( + self, masks: torch.Tensor, orig_hw, output_dtype + ) -> torch.Tensor: + """ + Perform PostProcessing on output masks. + """ + from torchao._models.sam2.utils.misc import get_connected_components + + masks = masks.float() + input_masks = masks + mask_flat = masks.flatten(0, 1).unsqueeze(1) # flatten as 1-channel image + try: + if self.max_hole_area > 0: + # Holes are those connected components in background with area <= self.fill_hole_area + # (background regions are those with mask scores <= self.mask_threshold) + labels, areas = get_connected_components( + mask_flat <= self.mask_threshold + ) + is_hole = (labels > 0) & (areas <= self.max_hole_area) + is_hole = is_hole.reshape_as(masks) + # We fill holes with a small positive mask score (10.0) to change them to foreground. + masks = torch.where(is_hole, self.mask_threshold + 10.0, masks) + + if self.max_sprinkle_area > 0: + labels, areas = get_connected_components( + mask_flat > self.mask_threshold + ) + is_hole = (labels > 0) & (areas <= self.max_sprinkle_area) + is_hole = is_hole.reshape_as(masks) + # We fill holes with negative mask score (-10.0) to change them to background. + masks = torch.where(is_hole, self.mask_threshold - 10.0, masks) + except Exception as e: + # Skip the post-processing step if the CUDA kernel fails + warnings.warn( + f"{e}\n\nSkipping the post-processing step due to the error above. You can " + "still use SAM 2 and it's OK to ignore the error above, although some post-processing " + "functionality may be limited (which doesn't affect the results in most cases; see " + "https://github.com/facebookresearch/sam2/blob/main/INSTALL.md).", + category=UserWarning, + stacklevel=2, + ) + masks = input_masks + + masks = masks.to(output_dtype) + masks = F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False) + return masks + + def postprocess_masks_1_channel( + self, masks: torch.Tensor, orig_hw, output_dtype + ) -> torch.Tensor: + """ + Perform PostProcessing on output masks. + """ + from torchao._models.sam2.utils.misc import get_connected_components + + assert masks.dim() == 4 + assert masks.size(1) == 1 + masks = masks.float() + input_masks = masks + # mask_flat = masks.flatten(0, 1).unsqueeze(1) # flatten as 1-channel image + mask_flat = masks + try: + if self.max_hole_area > 0: + # Holes are those connected components in background with area <= self.fill_hole_area + # (background regions are those with mask scores <= self.mask_threshold) + labels, areas = get_connected_components( + mask_flat <= self.mask_threshold + ) + is_hole = (labels > 0) & (areas <= self.max_hole_area) + # is_hole = is_hole.reshape_as(masks) + # We fill holes with a small positive mask score (10.0) to change them to foreground. + masks = torch.where(is_hole, self.mask_threshold + 10.0, masks) + + if self.max_sprinkle_area > 0: + labels, areas = get_connected_components( + mask_flat > self.mask_threshold + ) + is_hole = (labels > 0) & (areas <= self.max_sprinkle_area) + # is_hole = is_hole.reshape_as(masks) + # We fill holes with negative mask score (-10.0) to change them to background. + masks = torch.where(is_hole, self.mask_threshold - 10.0, masks) + except Exception as e: + # Skip the post-processing step if the CUDA kernel fails + warnings.warn( + f"{e}\n\nSkipping the post-processing step due to the error above. You can " + "still use SAM 2 and it's OK to ignore the error above, although some post-processing " + "functionality may be limited (which doesn't affect the results in most cases; see " + "https://github.com/facebookresearch/sam2/blob/main/INSTALL.md).", + category=UserWarning, + stacklevel=2, + ) + masks = input_masks + + masks = masks.to(output_dtype) + masks = F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False) + return masks diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2b46f06aa732211e92b25e8add24df22150752c5 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/_models/utils.py @@ -0,0 +1,111 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import datetime +import hashlib +import json +import os +import platform +import time + +import torch + + +def get_arch_name() -> str: + if torch.cuda.is_available(): + return torch.cuda.get_device_name() + else: + # This returns x86_64 or arm64 (for aarch64) + return platform.machine() + + +def write_json_result_ossci(output_json_path, headers, row): + """ + Write the result into JSON format, so that it can be uploaded to the benchmark database + to be displayed on OSS dashboard. The JSON format is defined at + https://github.com/pytorch/pytorch/wiki/How-to-integrate-with-PyTorch-OSS-benchmark-database + + OSS CI version, that will leave many fields to be filled in by CI + """ + mapping_headers = {headers[i]: v for i, v in enumerate(row)} + record = { + "benchmark": { + "name": "TorchAO benchmark", + "mode": "inference", + "dtype": mapping_headers["dtype"], + "extra_info": { + "device": mapping_headers["device"], + "arch": mapping_headers["arch"], + "min_sqnr": mapping_headers["min_sqnr"], + # True means compile is enabled, False means eager mode + "compile": mapping_headers["compile"], + }, + }, + "model": { + "name": mapping_headers["name"], + "type": "model", + "origins": ["torchao"], + }, + "metric": { + "name": mapping_headers["metric"], + "benchmark_values": [mapping_headers["actual"]], + "target_value": mapping_headers["target"], + }, + } + + with open(f"{os.path.splitext(output_json_path)[0]}.json", "a") as f: + print(json.dumps(record), file=f) + + +def write_json_result_local(output_json_path, headers, row): + """ + Write the result into JSON format, so that it can be uploaded to the benchmark database + to be displayed on OSS dashboard. The JSON format is defined at + https://github.com/pytorch/pytorch/wiki/How-to-integrate-with-PyTorch-OSS-benchmark-database + + Local version (filling in dummy values for fields that should be populated by CI) + """ + mapping_headers = {headers[i]: v for i, v in enumerate(row)} + today = datetime.date.today() + sha_hash = hashlib.sha256(str(today).encode("utf-8")).hexdigest() + first_second = datetime.datetime.combine(today, datetime.time.min) + workflow_id = int(first_second.timestamp()) + job_id = workflow_id + 1 + record = { + "timestamp": int(time.time()), + "schema_version": "v3", + "name": "devvm local benchmark", + "repo": "pytorch/ao", + "head_branch": "main", + "head_sha": sha_hash, + "workflow_id": workflow_id, + "run_attempt": 1, + "job_id": job_id, + "benchmark": { + "name": "TorchAO benchmark", + "mode": "inference", + "dtype": mapping_headers["dtype"], + "extra_info": { + "device": mapping_headers["device"], + "arch": mapping_headers["arch"], + "min_sqnr": mapping_headers["min_sqnr"], + # True means compile is enabled, False means eager mode + "compile": mapping_headers["compile"], + }, + }, + "model": { + "name": mapping_headers["name"], + "type": "model", + "origins": ["torchao"], + }, + "metric": { + "name": mapping_headers["metric"], + "benchmark_values": [mapping_headers["actual"]], + "target_value": mapping_headers["target"], + }, + } + + with open(f"{os.path.splitext(output_json_path)[0]}.json", "a") as f: + print(json.dumps(record), file=f) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/GPTQ/GPTQ.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/GPTQ/GPTQ.py new file mode 100644 index 0000000000000000000000000000000000000000..f20a5a49656fc04ca1708e88eeacc5d121a32478 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/GPTQ/GPTQ.py @@ -0,0 +1,1043 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import math +from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union + +import torch +import torch.nn as nn +from torch.utils._pytree import tree_flatten, tree_unflatten + +from torchao.dtypes import ( + Layout, + TensorCoreTiledLayout, + to_affine_quantized_intx_static, +) +from torchao.quantization.quant_primitives import ( + ZeroPointDomain, +) +from torchao.quantization.unified import Quantizer +from torchao.quantization.utils import compute_error as SQNR +from torchao.quantization.utils import ( + get_groupwise_affine_qparams, + groupwise_affine_dequantize_tensor_from_qparams, + groupwise_affine_quantize_tensor_from_qparams, +) + +GPTQ_FUNC_LIST = {} + + +__all__ = [ + "Int4WeightOnlyGPTQQuantizer", + "MultiTensorInputRecorder", + "MultiTensor", + "GPTQQuantizer", + "StateDictManager", +] + + +############################# +# Core Classes # +############################# + + +class MultiTensor(torch.Tensor): + get_qparams_func = None + quantize_func = None + dequantize_func = None + combine_qparams_list_func = None + make_qtensor = None + skip_layer_func = None + act_fake_quant_func = None + group_size: int = -1 + percdamp: float = 0.01 + blocksize: int = 128 + in_place_threshold: int = ( + 3 # Number of times to see a function before assuming it's not in-place + ) + + @staticmethod + def __new__( + cls, input: Union[torch.Tensor, Sequence[torch.Tensor]], **kwargs: Any + ) -> "MultiTensor": + if isinstance(input, (list, tuple)): + input = input[0] + kwargs["dtype"] = kwargs.get("dtype", input.dtype) + shape = kwargs.pop("shape", input.shape) + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) + + def __init__( + self, input: Union[torch.Tensor, Sequence[torch.Tensor]], **kwargs: Any + ) -> None: + self.values: List[torch.Tensor] = [] + self.state_dict_manager = StateDictManager.get_instance() + self.count: int = 0 + self.add_tensors(input) + self.debug: bool = False + self.gptq_done = False + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(shape={self.shape}, example={self.values[0]})" + ) + + def append(self, input: torch.Tensor): + return self.add_tensors(input) + + def add_tensors( + self, input: Union[torch.Tensor, Sequence[torch.Tensor]] + ) -> "MultiTensor": + if isinstance(input, (tuple, list)): + for inp in input: + self.add_tensors(inp) + else: + assert isinstance(input, torch.Tensor), ( + f"MultiTensor can only use add_tensors for Tensors or lists of tensors but got {type(input)}" + ) + self.count += 1 + self.values.append(input) + return self + + def pad_to_length(self, length, pad_in_place=True): + if self.count < length: + if pad_in_place: + for _ in range(length - self.count): + # we need to handle in place ops where we do want the model's value to stay changed. + # e.g. if someone does z[1,:]=x, if z were a size 1 multiTensor and x were size 3, + # we want z to become a multi tensor of size 3. Thus we pad the MultiTensor to the correct + # size by adding new tensor instances (and not just instances of the pointers to the same original tensor.. + # otherwise changes to one would change all of them) + self.add_tensors(self.values[-1].clone()) + else: + # for non in place ops, no need to bloat memory, can just pad with same tensor instance + return self.__class__(self.values).add_tensors( + [self.values[-1]] * (length - self.count) + ) + return self + + def unpad(self, count=1): + count = min(count, self.count) + self.values = self.values[:count] + self.count = count + + @classmethod + def configure_quantization_mode( + cls, + get_qparams_func, + quantize_func, + dequantize_func, + combine_qparams_list_func, + make_qtensor, + skip_layer_func, + act_fake_quant_func=None, + group_size=-1, + percdamp=0.01, + blocksize=128, + device: torch.device = torch.device("cuda"), + ): + cls.get_qparams_func = get_qparams_func + cls.quantize_func = quantize_func + cls.dequantize_func = dequantize_func + cls.combine_qparams_list_func = combine_qparams_list_func + cls.make_qtensor = make_qtensor + cls.skip_layer_func = skip_layer_func + cls.act_fake_quant_func = ( + act_fake_quant_func if act_fake_quant_func is not None else lambda x: x + ) + cls.group_size = group_size + cls.percdamp = percdamp + cls.blocksize = blocksize + cls.device = device + + @classmethod + def __torch_function__( + cls, + func: Callable, + types: Tuple[type, ...], + args: Tuple[Any, ...] = (), + kwargs: Optional[Dict[str, Any]] = None, + skip_gptq: bool = False, + ) -> Any: + # The way MultiTensor handles various functions is as follows. Normally when you apply a function on a MultiTensor that has n Tensors inside, we want + # the function handling here to run that function once for each of the MultiTensor inputs. We also want it to happen in the same way as if you ran the function + # first input and the second independently, i.e. if you ran model(input1)=out1 and model(input2), vs model(MultiTensor(input1, input2)) the output for the + # second case should be MultiTensor(out1, out2) and all the activations along the way should be the same. Normally it is easy enough to handle MultiTensors + # running the func for each set of inputs and then combine the outputs back into MultiTensors at the end if applicable. Since we can have a lot of tensors in a MultiTensor but we + # normally want to execute the function on cuda, we can move them over to cuda before we evaluate the function. + # this scheme works pretty well but has a few issues + # 1) We end up moving the same tensors to cuda over and over again which can make things slow. if we have a function input like (MultiTensor(a), MultiTensor(b1, b2, ...b_n) + # when we pad and group MultiTensors into Tensor-only function inputs i.e. (a, b1), (a, b2), ..., (a, b_n), since each Tensor-only input uses a common tensor a but a unique tensor b, + # we would be moving the same tensor a to cuda n times for no reason. This is easy to fix normally, just move all singular MultiTensors to cuda before padding/grouping but... + # 2) In place ops are tricky to handle (funcs that modify the inputs). We want in_place operations like k_cache[:, indices] = k_val (where k_cache, k_val are MultiTensor inputs) + # to be supported but if we move tensors to cuda then any modifications to the inputs will be applied to the cuda tensors rather than the originals. Additionally the originals are often + # singular MultiTensors i.e. MultiTensor(a) that only has a single value, we don't want each in place op to overwrite the value of a, we need each change to the inputs to be recorded. So + # we can modify MultiTensor(a) -> MultiTensor(a1, a2, ...) at the start so that each change of a can be recorded and won't overwrite the value of a for other ops, but then problem 1 comes back + # since we have to move a1, a2, a3...etc to cuda over and over again. despite them all being the same value initially. And if we move them to cuda then the in place value changes will + # be applied to a1_cuda not a1 and a1_cuda isn't in the MultiTensor. So we have to manually copy those values back a1.copy_(a1_cuda). + # There's not really a great way to resolve the 2 issues, when there's an in place op you have to do the slow thing with cuda and checking for modified values....etc, when + # there's not an in place op you can throw all singular tensors onto cuda at the start and go much faster. + # This brings up the final issue, how do we know if we have an in place op? In general we don't so I added handling to MultiTensor to resolve that as well as can be hoped. + # we have a dict that contains all the funcs we see GPTQ_FUNC_LIST, we initially treat ops as in place and see if any of the inputs got modified if they do then it gets + # set to always be handled as an in place op. If nothing changes then once we've seen the op enough times that we're confident its not an in place op (cls.in_place_threshold) + # then we can do the fast thing. + + quantize_linear = not skip_gptq and cls.is_linear_layer(func) + if hasattr(cls, "device") and isinstance(cls.device, torch.device): + device = cls.device + else: + device = "cpu" + # Determine if function is in-place + + # initialize function tracking + if func not in GPTQ_FUNC_LIST: + GPTQ_FUNC_LIST[func] = {"count": 0, "is_in_place": None} + GPTQ_FUNC_LIST[func]["count"] += 1 + + if GPTQ_FUNC_LIST[func]["is_in_place"] is not None: + is_in_place = GPTQ_FUNC_LIST[func]["is_in_place"] + elif GPTQ_FUNC_LIST[func]["count"] >= cls.in_place_threshold or quantize_linear: + is_in_place = False # Assume not in-place after threshold + else: + is_in_place = True + + kwargs = {} if kwargs is None else kwargs + # combine args and kwargs into a single tuple + # flat_args holds all the actual inputs, spec stores the original structure + flat_args, spec = tree_flatten((args, kwargs)) + + # if we're not doing an in place op, move singular tensors to cuda now + if not is_in_place: + flat_args = _tensors_to_device(flat_args, device=device) + + # convert [A, MultiTensor(b), MultiTensor(c1,c2,c3)] => [[A,b,c1], [A,b,c2] [A,b,c3]] + # if its in place then instead we first pad i.e. MultiTensor(b) => MultiTensor(b1, b2, b3) + # then proceed as normal. + grouped_args, orig_counts = _flat_to_grouped_and_pad(flat_args, is_in_place) + + with torch._C.DisableTorchFunctionSubclass(): + if not quantize_linear: # normal function eval + out = cls._evaluate_function( + func, grouped_args, spec, is_in_place, device + ) + + # go back and unpad everything where possible. + if not GPTQ_FUNC_LIST[func]["is_in_place"]: + _do_unpad(flat_args, orig_counts) + return out + + # GPTQ quantization for linear layers + # Calculate Hessian approximation + H = _calculate_hessian(grouped_args, spec, device) + + # turn weight MultiTensor into single cuda tensor + W = args[1] + if isinstance(W, MultiTensor): + W = W.values[0] + W = W.to(H.device) + + Q, DQ, all_qparams = cls.faster_quant(H, W.detach(), device) + + # make quantized tensor subclass + qtensor = cls.make_qtensor(Q, all_qparams) + + # Get the original parameter name + state_dict_manager = StateDictManager.get_instance() + original_param_name = state_dict_manager.get_name_for_param(args[1]) + state_dict_manager.update_param(original_param_name, qtensor) + print(original_param_name) + + # Run the function again with updated weights and skip_gptq=True + out = cls.__torch_function__( + func, types, (args[0], DQ.cpu(), *args[2:]), kwargs, skip_gptq=True + ) + if not args[0].debug: + _do_unpad(flat_args, orig_counts=orig_counts) + return out + if args[0].debug: + act = args[0].values[0].to(device) + bias = args[2].values[0].to(device) if args[2] is not None else args[2] + + new_out = out.values[0].cpu() + old_out = ( + cls.__torch_function__( + func, + types, + (act, args[1].values[0], bias), + kwargs, + skip_gptq=True, + ) + .values[0] + .cpu() + ) + + DQ_after = cls.dequantize_func(Q, all_qparams).to(W.dtype) + print( + "SQNR for QDQ (this should be inf)", SQNR(DQ, DQ_after) + ) # matches + print( + "SQNR for weight (can be low)", SQNR(W, DQ.to(device)) + ) # fine to not match + print( + "SQNR for output with GPTQ (hopefully 35+)", + SQNR(old_out, new_out), + ) + + DQ_from_qtensor = qtensor.dequantize() + qtensor_out = torch.nn.functional.linear(act, qtensor, bias).cpu() + print( + "SQNR for output from qtensor vs output from DQ (should be high)", + SQNR(qtensor_out, new_out), + ) + print( + "SQNR for DQ vs DQ from qtensor (should be inf)", + SQNR(DQ, DQ_from_qtensor), + ) + + qparams2 = cls.get_qparams_func(W, W.dtype) + Q2 = cls.quantize_func(W, qparams2) + DQ2 = cls.dequantize_func(Q2, qparams2).to(W.dtype) + old_q_out = ( + cls.__torch_function__( + func, types, (act, DQ2, bias), kwargs, skip_gptq=True + ) + .values[0] + .cpu() + ) + + print( + "SQNR for output without GPTQ (should be less than above)", + SQNR(old_out, old_q_out), + ) + _do_unpad(flat_args, orig_counts=orig_counts) + return out + + @classmethod + def grouped_to_flat(cls, grouped: List[Tuple[Any, ...]]) -> Tuple[List[Any], bool]: + # convert [[A,b1,c1], [A,b2,c2] [A,b3,c3]] => [(A,A,A), (b1,b2,b3), (c1,c2,c3)] + flat_tups = list(zip(*grouped)) + # convert [(A,A,A), (b1,b2,b3), (c1,c2,c3)] => [A, MultiTensor(b1,b2,b3), MultiTensor(c1,c2,c3)] + flattened = [ + cls(tup).cpu() if isinstance(tup[0], torch.Tensor) else tup[0] + for tup in flat_tups + ] + non_tensors_equal = all( + all(x == tup[0] for x in tup) + for tup in flat_tups + if not isinstance(tup[0], torch.Tensor) + ) + return flattened, non_tensors_equal + + @classmethod + def _evaluate_function(cls, func, grouped_args, spec, is_in_place, device): + outputs = [] + for inp in grouped_args: + # we move all remaining cpu tensors to cuda + device_inp = _tensors_to_device(inp, device) + + # return input to original structure + cur_args, cur_kwargs = tree_unflatten(device_inp, spec) + + out = func(*cur_args, **cur_kwargs) + + outputs.append(out.cpu() if isinstance(out, torch.Tensor) else out) + + # if we're doing an in place op, here is where we copy modifications + # back to the original tensors, if we saw any mutated inputs, immediately + # categortize func as in place. + if is_in_place: + detected_mutation = _maybe_copy_new_values( + inp, device_inp, force=GPTQ_FUNC_LIST[func]["is_in_place"] + ) # if we already know its in place, don't compare, just copy + if detected_mutation and GPTQ_FUNC_LIST[func]["is_in_place"] is None: + GPTQ_FUNC_LIST[func]["is_in_place"] = True + print( + f">>GPTQ process identified function {func} as in-place, continuing...<<" + ) + + # if no inputs were mutated and we've seen the function enough times, categorize it as not in place. + elif GPTQ_FUNC_LIST[func][ + "count" + ] >= cls.in_place_threshold and not isinstance( + GPTQ_FUNC_LIST[func]["is_in_place"], bool + ): + GPTQ_FUNC_LIST[func]["is_in_place"] = False + + grouped_outputs = [tree_flatten(x)[0] for x in outputs] + out_spec = tree_flatten(outputs[0])[1] + # conslidate out into MultiTensors [[A,b1,c1], [A,b2,c2] [A,b3,c3]] => [A, MultiTensor(b1,b2,b3), MultiTensor(c1,c2,c3)] + flat_outputs, non_tensors_equal = cls.grouped_to_flat(grouped_outputs) + assert non_tensors_equal, ( + f"ERR: found a function in model: {func} which " + + "caused an error in GPTQ MultiTensor, the function dispatch only works for functions" + + "with Tensor outputs or that have the same non-Tensor output value across all inputs" + ) + final_out = tree_unflatten(flat_outputs, out_spec) + return final_out + + @classmethod + def faster_quant(cls, H, W, device): + """ + GPTQ quantization implementation. + + Args: + H: Hessian matrix approximation + W: Weight matrix to quantize + device: accelerator device + + Returns: + Tuple containing: + - Q: Quantized weights + - DQ: Dequantized weights + - all_qparams: Quantization parameters + """ + msg = ( + "tried to do faster quant but configure quantization mode was never called" + ) + assert cls.get_qparams_func is not None, msg + assert cls.quantize_func is not None, msg + assert cls.dequantize_func is not None, msg + assert cls.combine_qparams_list_func is not None, msg + + percdamp = cls.percdamp + blocksize = cls.blocksize + group_size = cls.group_size + orig_dtype = W.dtype + W = W.detach().float() + _, columns = W.shape[0], W.shape[1] + device = W.device + + if group_size == -1: + group_size = columns + else: + blocksize = math.ceil(blocksize / group_size) * group_size + + dead = torch.diag(H) == 0 + H[dead, dead] = 1 + W[:, dead] = 0 + + DQ = torch.zeros_like(W) + + damp = percdamp * torch.mean(torch.diag(H)) + diag = torch.arange(columns, device=device) + H[diag, diag] += damp + H = torch.linalg.cholesky(H) + H = torch.cholesky_inverse(H) + H = torch.linalg.cholesky(H, upper=True) + Hinv = H + + cur_qparams = None + all_qparams = [] + + for block_start in range( + 0, columns, blocksize + ): # go through all columns block by block + block_end = min(block_start + blocksize, columns) + W1 = W[:, block_start:block_end].clone() + DQ1 = torch.zeros_like(W1) + Err1 = torch.zeros_like(W1) + Hinv1 = Hinv[block_start:block_end, block_start:block_end] + for group_start in range( + block_start, block_end, group_size + ): # break up blocks by groupsize + group_end = min(group_start + group_size, columns) + if group_start % group_size == 0: + # needed for when group_size == columns so only calculate qparams once + cur_qparams = cls.get_qparams_func( + W[:, group_start:group_end], orig_dtype + ) + all_qparams.append(cur_qparams) + + for index in range(group_start, group_end): # within each group + i = index - block_start + w = W1[:, i] + d = Hinv1[i, i] + + q = cls.quantize_func(w.unsqueeze(1), cur_qparams).flatten() + dq = cls.dequantize_func(q.unsqueeze(1), cur_qparams).flatten() + + DQ1[:, i] = dq + + err1 = (w - dq) / d + W1[:, i:] -= ( + err1.to(Hinv1.dtype) + .unsqueeze(1) + .matmul(Hinv1[i, i:].unsqueeze(0)) + ) + Err1[:, i] = err1 + + DQ[:, block_start:block_end] = DQ1 + W[:, block_end:] -= Err1.to(Hinv.dtype).matmul( + Hinv[block_start:block_end, block_end:] + ) + + if "xpu" in device.type: + torch.xpu.synchronize() + elif "cuda" in device.type: + torch.cuda.synchronize() + else: + pass + + if all_qparams == []: + all_qparams.append(cur_qparams) + + all_qparams = cls.combine_qparams_list_func(all_qparams) + Q = cls.quantize_func(DQ, all_qparams) + return Q, DQ.to(orig_dtype), all_qparams + + @classmethod + def __torch_dispatch__( + cls, + func: Callable, + types: Tuple[type, ...], + args: Tuple[Any, ...] = (), + kwargs: Dict[str, Any] = {}, + skip_gptq: bool = False, + ) -> Any: + pass + + def __tensor_flatten__(self) -> Tuple[List[str], Optional[Any]]: + return ["values"], None + + @classmethod + def __tensor_unflatten__( + cls, + tensor_data_dict: Dict[str, Any], + tensor_attributes: Optional[Any], + outer_size: torch.Size, + outer_stride: Tuple[int, ...], + ) -> "MultiTensor": + return cls(tensor_data_dict["values"]) + + @classmethod + def is_linear_layer(cls, func: Callable) -> bool: + return func == torch.nn.functional.linear + + +class MultiTensorInputRecorder(torch.nn.Module): + def __init__(self, disable_input_validation=False, target_class=MultiTensor): + super().__init__() + self.flat_args = [] + self.spec = None + self.validate = not disable_input_validation + self.target_class = target_class + self.count = 0 + + def forward(self, *args: Any, **kwargs: Any) -> "MultiTensorInputRecorder": + def validate_input(flat_args, spec): + if self.spec is None: + assert spec == self.spec, ( + f"got two different input structures when recording inputs, {self.spec} is not the same as {spec}" + ) + + for count, x in enumerate(flat_args): + y = self.flat_args[count] + if not isinstance(x, torch.Tensor): + assert x == y, ( + f"got different values for nontensor input {x} is not the same as {y} for flattened input element {count}, different inputs to input recorder must have same nontensor values" + ) + else: + assert isinstance(y, self.target_class), ( + f"expected input of type torch.Tensor but got {type(x)} for flattened input element {count}" + ) + assert y.dtype == x.dtype, ( + f"expected input of dtype {y.dtype} but got {x.dtype} for flattened input element {count} different inputs to input recorder must have same tensor dtypes" + ) + assert y.shape == y.shape, ( + f"expected input of shape {y.shape} but got {y.dtype} for flattened input element {count} different inputs to input recorder must have same tensor shape" + ) + + kwargs = {} if kwargs is None else kwargs + flat_args, spec = tree_flatten((args, kwargs)) + if self.spec is None: + self.spec = spec + self.flat_args = [ + self.target_class(x) if isinstance(x, torch.Tensor) else x + for x in flat_args + ] + return self + + if self.validate: + validate_input(flat_args, spec) + self.count += 1 + + for count, x in enumerate(flat_args): + if isinstance(x, torch.Tensor): + self.flat_args[count].append(x) + return self + + def get_recorded_inputs(self) -> Tuple[Any, ...]: + args, kwargs = self.get_recorded_args_and_kwargs() + assert len(kwargs) == 0, ( + "kwargs is not empty but get_recorded_inputs called on MultiTensorInputRecorder, use get_recorded_args_and_kwargs instead" + ) + return args + + def get_recorded_args_and_kwargs(self) -> Tuple[Tuple[Any, ...], Dict[str, Any]]: + assert self.spec is not None, "no inputs have been recorded yet" + args, kwargs = tree_unflatten(self.flat_args, self.spec) + return args, kwargs + + +class GPTQQuantizer(Quantizer): + def __init__(self): + super().__init__() + self.state_dict_manager = StateDictManager.get_instance() + self.get_qparams_func = None + self.quantize_func = None + self.dequantize_func = None + self.combine_qparams_list_func = None + self.make_qtensor = None + self.skip_layer_func = None + self.act_fake_quant_func = None + self.device = None + + def _check_functions(self): + assert self.get_qparams_func is not None, "get_qparams_func must be set" + assert self.quantize_func is not None, "quantize_func must be set" + assert self.dequantize_func is not None, "dequantize_func must be set" + assert self.combine_qparams_list_func is not None, ( + "combine_qparams_list_func must be set" + ) + assert self.make_qtensor is not None, "make_qtensor must be set" + assert self.skip_layer_func is not None, "skip_layer_func must be set" + + def covert_multi_tensors_to_tensors(self, state_dict): + for key, value in state_dict.items(): + if isinstance(value, MultiTensor): + state_dict[key] = value.values[0] + return state_dict + + @torch.no_grad() + def _create_quantized_state_dict( + self, + model, + args, + kwargs, + group_size=64, + blocksize=128, + percdamp=0.01, + # `typing.Dict[, ]` to avoid runtime subscripting errors. + ) -> Dict: + if kwargs is None: + kwargs = {} + MultiTensor.configure_quantization_mode( + get_qparams_func=self.get_qparams_func, + quantize_func=self.quantize_func, + dequantize_func=self.dequantize_func, + combine_qparams_list_func=self.combine_qparams_list_func, + make_qtensor=self.make_qtensor, + skip_layer_func=self.skip_layer_func, + group_size=group_size, + percdamp=percdamp, + blocksize=blocksize, + device=self.device, + ) + # Set the state dict for the original model + self.state_dict_manager.set_state_dict(model) + + with torch.no_grad(): + _replace_with_custom_fn_if_matches_filter( + model=model, + replacement_fn=_replace_buffers_and_params_with_multitensors, + filter_fn=lambda x, y: True, + ) + self.state_dict_manager.update_id_to_name(model) + # Run the model + + with torch.no_grad(): + model(*args, **kwargs) + state_dict = self.state_dict_manager.get_state_dict() + return state_dict + + +class Int4WeightOnlyGPTQQuantizer(GPTQQuantizer): + def __init__( + self, + group_size=64, + blocksize=128, + percdamp=0.01, + inner_k_tiles=8, + padding_allowed=True, + device: torch.device = torch.device("cuda"), + layout: Optional[Layout] = TensorCoreTiledLayout(inner_k_tiles=8), + ): + super().__init__() + self.group_size = group_size + self.blocksize = blocksize + self.percdamp = percdamp + self.inner_k_tiles = inner_k_tiles + self.padding_allowed = padding_allowed + self.device = device + self.device = self.device + self.act_fake_quant_func = None + self.layout = layout + n_bit = 4 + + if "xpu" in self.device.type: + self.zero_point_domain = ZeroPointDomain.INT + self.zeros_precision = torch.int8 + else: + self.zero_point_domain = ZeroPointDomain.FLOAT + + self.get_qparams_func = lambda w, precision: get_groupwise_affine_qparams( + w, + n_bit, + group_size, + dtype=precision, + zero_point_domain=self.zero_point_domain, + ) + self.quantize_func = ( + lambda w, qparams: groupwise_affine_quantize_tensor_from_qparams( + w, + qparams[0], + qparams[1], + n_bit, + group_size, + zero_point_domain=self.zero_point_domain, + ) + ) + self.dequantize_func = ( + lambda q, qparams: groupwise_affine_dequantize_tensor_from_qparams( + q, + qparams[0], + qparams[1], + n_bit, + group_size, + zero_point_domain=self.zero_point_domain, + ) + ) + self.combine_qparams_list_func = lambda qparams_list: [ + torch.cat(x, dim=1) for x in zip(*qparams_list) + ] + # skip unless padding_allowed=True or its correctly sized + self.skip_layer_func = lambda linear_weight: not ( + _check_linear_int4_k(linear_weight.shape[-1], group_size) or padding_allowed + ) + + def make_qtensor(q, qparams): + # this should be setup to just use the quantized tensor and qparams directly to make + # the aqt int4 tensor but i don't think we have that functionality atm so just dequant + # then requant + weight = self.dequantize_func(q, qparams) + scale = qparams[0] + zero_point = qparams[1] + if self.zero_point_domain == ZeroPointDomain.INT: + zero_point = zero_point.to(self.zeros_precision) + + # copied from quant_api apply_int4_weight_only_quant (this should probably be made into a utility fn at some point) + # mapping_type = MappingType.ASYMMETRIC + block_size = (1, group_size) + target_dtype = torch.int32 + quant_min = 0 + quant_max = 15 + # at least the big up to here should be a util + + quantized_tensor = to_affine_quantized_intx_static( + weight, + scale=scale, + zero_point=zero_point, + block_size=block_size, + target_dtype=target_dtype, + quant_min=quant_min, + quant_max=quant_max, + zero_point_domain=self.zero_point_domain, + _layout=self.layout, + ) + return quantized_tensor + + self.make_qtensor = make_qtensor + + self._check_functions() + + def quantize( + self, model: torch.nn.Module, *args: Tuple[Any, ...], **kwargs: Dict[str, Any] + ) -> torch.nn.Module: + state_dict = self._create_quantized_state_dict( + model, + args, + kwargs, + self.group_size, + self.blocksize, + self.percdamp, + ) + + # this is hacky and potentially wrong, better to just make the flow return a state dict and let user + # do with it what they will + + model = _replace_with_custom_fn_if_matches_filter( + model=model, + replacement_fn=_remove_multitensors_from_buffers_and_params, + filter_fn=lambda x, y: True, + ) + remove = [k for k in state_dict if "kv_cache" in k] + for k in remove: + del state_dict[k] + + model.load_state_dict(state_dict, assign=True, strict=False) + + return model + + +class StateDictManager: + _instance = None + + @staticmethod + def get_instance(): + if StateDictManager._instance is None: + StateDictManager._instance = StateDictManager() + return StateDictManager._instance + + def __init__(self): + self.state_dict = {} + self.id_to_name = {} + + def set_state_dict(self, model): + self.state_dict = model.state_dict() + self.id_to_name = {id(v): k for k, v in model.named_parameters()} + + def update_id_to_name(self, model): + self.id_to_name = {id(v): k for k, v in model.named_parameters()} + + def get_name_for_param(self, param): + return self.id_to_name.get(id(param), None) + + def update_param(self, name, new_value): + if name in self.state_dict: + if isinstance(new_value, MultiTensor): + self.state_dict[name] = new_value.values[ + 0 + ] # Convert MultiTensor to regular tensor + else: + self.state_dict[name] = new_value + else: + raise KeyError(f"Parameter {name} not found in state_dict") + + def get_state_dict(self): + return self.state_dict + + +############################# +# Utility Functions +############################# + + +def _check_linear_int4_k(k, group_size=1, inner_k_tiles=None): + """ + Check if the dimensions are compatible with int4 quantization. + + Args: + k: The dimension size to check + group_size: The group size for quantization + inner_k_tiles: The inner k tiles size + + Returns: + bool: Whether the dimensions are compatible + """ + k_divisible_by_group_size = k % group_size == 0 + if inner_k_tiles is not None: + k_divisible_by_16_times_inner_k_tiles = k % (inner_k_tiles * 16) == 0 + return k_divisible_by_group_size and k_divisible_by_16_times_inner_k_tiles + return k_divisible_by_group_size + + +def _flat_to_grouped_and_pad( + flat: List[Any], pad_in_place=True +) -> Tuple[List[Tuple[Any, ...]], List[int]]: + """ + Convert flattened arguments to grouped arguments with padding. + + Args: + flat: Flattened arguments + pad_in_place: Whether to pad in place + + Returns: + Tuple containing grouped arguments and original counts + """ + # Convert [A, MultiTensor(b1,b2,b3), MultiTensor(c1,c2,c3)] => [[A,b1,c1], [A,b2,c2] [A,b3,c3]] + orig_counts = [x.count if isinstance(x, MultiTensor) else 1 for x in flat] + multi_tensor_size = max(orig_counts) + grouped = list( + zip( + *[ + x.pad_to_length(multi_tensor_size, pad_in_place=pad_in_place).values + if isinstance(x, MultiTensor) + else [x] * multi_tensor_size + for x in flat + ] + ) + ) + return grouped, orig_counts + + +def _tensors_to_device(args, device=torch.device("cuda"), move_all=False): + """ + Move tensors to accelerator for faster processing. + + Args: + args: Arguments that may contain tensors + device: accelerator device + move_all: Whether to move all tensors or just single count tensors + + Returns: + List with tensors moved to CUDA + """ + new_args = [] + for x in args: + if isinstance(x, MultiTensor) and (x.count == 1 or move_all): + new_args.append(x.__class__(x.values[0].to(device))) + else: + new_args.append( + x.to(device) + if isinstance(x, torch.Tensor) and not isinstance(x, MultiTensor) + else x + ) + return new_args + + +def _maybe_copy_new_values(orig_inp, new_inp, force=False): + """ + Copy values from new inputs to original inputs if they've changed. + Used for handling in-place operations. + + Args: + orig_inp: Original inputs + new_inp: New inputs (potentially modified) + force: Whether to force copying regardless of differences + + Returns: + bool: Whether any differences were detected + """ + detected_difference = False + for x, new_x in zip(orig_inp, new_inp): + if isinstance(x, torch.Tensor): + if force or (x != new_x.to(x.device)).any(): + x.copy_(new_x) + detected_difference = True + return detected_difference + + +def _do_unpad(args, orig_counts): + """ + Unpad MultiTensors to their original counts. + + Args: + args: Arguments that may contain MultiTensors + orig_counts: Original counts of MultiTensors + """ + for arg, count in zip(args, orig_counts): + if isinstance(arg, MultiTensor) and arg.count > count: + arg.unpad(count) + + +def _calculate_hessian(grouped_args, spec, device=torch.device("cuda")): + """ + Calculate the Hessian matrix for GPTQ. + + Args: + grouped_args: Grouped arguments + spec: Original structure specification + device: accelerator device + + Returns: + torch.Tensor: Hessian matrix + """ + H = 0 + total_batches = 0 + for inp in grouped_args: + # Move all remaining CPU tensors to CUDA + device_inp = [x.to(device) if isinstance(x, torch.Tensor) else x for x in inp] + + # Return input to original structure + cur_args, _ = tree_unflatten(device_inp, spec) + + # Setup x (activation tensor) + x = cur_args[0].float() + shape = x.shape + n = 1 if len(shape) == 2 else shape[0] + x = x.reshape(-1, shape[-1]) + + # Update Hessian with running average + H *= total_batches / (total_batches + n) + total_batches += n + + x = ((2 / total_batches) ** (1 / 2)) * x.t() + H += x.matmul(x.t()) + + return H + + +def _replace_with_custom_fn_if_matches_filter( + model: nn.Module, + replacement_fn: Callable[[nn.Module], nn.Module], + filter_fn: Callable[[nn.Module, str], bool], + cur_fqn: str = "", +) -> nn.Module: + """ + Replace modules in the model if they match a filter. + + Args: + model: The model to modify + replacement_fn: Function to apply to matching modules + filter_fn: Function to determine if a module should be replaced + cur_fqn: Current fully qualified name (for tracking position in model hierarchy) + + Returns: + nn.Module: Modified model + """ + if filter_fn(model, cur_fqn[:-1]): + model = replacement_fn(model) + + for name, child in model.named_children(): + new_child = _replace_with_custom_fn_if_matches_filter( + child, replacement_fn, filter_fn, f"{cur_fqn}{name}." + ) + if new_child is not child: + setattr(model, name, new_child) + + return model + + +def _replace_buffers_and_params_with_multitensors(model: nn.Module) -> nn.Module: + """ + Replace model buffers and parameters with MultiTensors. + + Args: + model: The model to modify + + Returns: + nn.Module: Modified model + """ + for name, buf in model.named_buffers(recurse=False): + setattr(model, name, MultiTensor([buf])) + + for name, param in model.named_parameters(recurse=False): + setattr(model, name, nn.Parameter(MultiTensor([param]), param.requires_grad)) + + return model + + +def _remove_multitensors_from_buffers_and_params(model: nn.Module) -> nn.Module: + """ + Convert MultiTensors in model buffers and parameters back to regular tensors. + + Args: + model: The model to modify + + Returns: + nn.Module: Modified model + """ + for name, buf in model.named_buffers(recurse=False): + if isinstance(buf, MultiTensor): + setattr(model, name, buf.values[0]) + + for name, param in model.named_parameters(recurse=False): + if isinstance(param, MultiTensor): + setattr( + model, + name, + nn.Parameter(param.values[0], param.values[0].requires_grad), + ) + + return model diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/GPTQ/README.md b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/GPTQ/README.md new file mode 100644 index 0000000000000000000000000000000000000000..89fde3487c6cf698a0d2c728581136acec607a2d --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/GPTQ/README.md @@ -0,0 +1,74 @@ +# GPTQ + +GPTQ is a quantization technique that improves accuracy for various forms of quantization as introduced in the paper: https://arxiv.org/abs/2210.17323 + +In general GPTQ requires a model, a quantization technique and calibration data. GPTQ then optimizes the quantization parameters and quantized weights so they are more accurate accross the calibration data. + +## API + +The api for this technique is as follows: + + +```python +from torchao.quantization import MultiTensorInputRecorder, Int4WeightOnlyGPTQQuantizer + +model = get_model() # user provided function + +# first gather inputs +input_recorder = MultiTensorInputRecorder() +for i in range(calibration_limit): + args = get_next_input() # user provided function + input_recorder(*args) # compare to model(*args) + # note: can do input_recorder(*args, **kwargs) if needed + +# then perform GPTQ +quantizer = Int4WeightOnlyGPTQQuantizer() # quantization parameters like group_size can be set here +args = input_recorder.get_recorded_inputs() # use get_recorded_args_and_kwargs if necessary +quantizer.quantize(model, *args) +# model is now quantized and can be saved, compiled or run + +args = get_next_input() +out = model(*args) +``` + +important notes: +1) `input_recorder`, `quantizer.quantize` and `model` all take the same type of input. If you pass in kwargs to the model like `model(*args, **kwargs)` you'll need to do `input_recorder(*args, **kwargs)` and `quantizer.quantize(model, *args, **kwargs)` +2) the GPTQ process can take a significant period of time depending on the size of the model and the size of the calibration set. +3) We currently only support int4 weight only quantization for GPTQ though this framework can be relatively easily extended to other techniques. + + +In many cases users use lm_eval to get calibration data. We also have an input recorder that integrates directly with lm_eval. This is equivalent to using lm_eval but setting your model to be a MultiTensorInputRecorder. + +```python +from torchao._models._eval import LMEvalInputRecorder + +args = ( + LMEvalInputRecorder( + get_tokenizer(), # tokenizer + calibration_seq_length, + prepare_inputs_for_model, # optional function that transforms the input, e.g. constructing the indices tensor + get_tokenizer_vocab_size(), + pad_calibration_inputs, # boolean to allow padding + ) + .record_inputs( + calibration_tasks, + calibration_limit, + ) + .get_recorded_inputs() +) + + +``` + +## Results + +We tested the GPTQ implementation using the llama model in torchao/_models/llama with 10 calibration samples from lm_eval. + +| Technique: | Llama-2-7b-chat-hf | Meta-Llama-3-8B | +|----------------|--------------------|-----------------| +| bf16 | 12.245 | 7.441 | +| int4wo-64 | 12.876 | 8.316 | +| gptq-int4wo-64 | 12.523 | 8.026 | + +In practice we find that GPTQ recovers ~1/2 to 1/3 of the perplexity lost compared to quantizing directly to int4. +You can reproduce these numbers using `python eval.py --checkpoint_path $CHECKPOINT_PATH/$MODEL_REPO/model.pth --quantization gptq-int4wo-64 --calibration_limit 10` diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/GPTQ/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/GPTQ/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8d62e68c3c3e78e37208d7a1cbcfc48b0ff3b98f --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/GPTQ/__init__.py @@ -0,0 +1,21 @@ +from torchao.quantization.linear_quant_modules import ( + Int4WeightOnlyQuantizer, + Int8DynActInt4WeightLinear, + Int8DynActInt4WeightQuantizer, + WeightOnlyInt4Linear, + # for BC + _replace_linear_8da4w, # noqa: F401 + _replace_linear_int4, # noqa: F401 +) + +from .GPTQ import Int4WeightOnlyGPTQQuantizer, MultiTensor, MultiTensorInputRecorder + +__all__ = [ + "Int4WeightOnlyGPTQQuantizer", + "MultiTensorInputRecorder", + "MultiTensor", + "Int4WeightOnlyQuantizer", + "Int8DynActInt4WeightQuantizer", + "WeightOnlyInt4Linear", + "Int8DynActInt4WeightLinear", +] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/marlin_qqq/README.md b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/marlin_qqq/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f3bbecaa2a3ded2791e5c9021ad2912122af8a58 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/marlin_qqq/README.md @@ -0,0 +1,14 @@ +# Marlin QQQ + +Marlin QQQ kernel is now compatible with GPUs for sm80 and above. +Marlin QQQ kernel and Marlin kernel mainly have the following differences: +1. Marlin QQQ kernel supports W4A8 mixed precision GEMM using INT8 Tensor Core, while the original Marlin kernel supports W4A16 mixed precision GEMM using FP16 Tensor Core. +2. Because the mma instruction requires that the data types of weight and activation be consistent, type conversion is required. Marlin QQQ needs to convert INT4 weight to INT8, while Marlin needs to convert INT4 weight to FP16. +3. Similar to W8A8, Marlin QQQ needs to dequant to FP16 before writing the final result because the calculation result is accumulated in INT32, while Marlin does not need this processing. + +For more details about Marlin QQQ, please refer to [paper](https://arxiv.org/pdf/2406.09904). + +Marlin QQQ implementation adapted from the two below sources: + +* [QQQ](https://github.com/HandH1998/QQQ/tree/main) +* [vllm](https://github.com/vllm-project/vllm/tree/main) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/marlin_qqq/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/marlin_qqq/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7251771cc377d3181158587caa4137ccdba835bd --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/marlin_qqq/__init__.py @@ -0,0 +1,282 @@ +from typing import Tuple + +import torch + +from torchao.quantization.granularity import ( + PerAxis, + PerGroup, +) +from torchao.quantization.marlin_qqq.utils import ( + const, + get_pack_factor, + get_qqq_scale_perms, + get_qqq_scale_reverse_perms, + get_qqq_weight_perm, + get_qqq_weight_reverse_perm, + marlin_permute_weights, + reverse_marlin_permute_weights, +) + +__all__ = [ + "marlin_qqq_workspace", + "pack_to_marlin_qqq", + "unpack_from_marlin_qqq", +] + + +def marlin_qqq_workspace( + out_features: int, + min_thread_n: int = const.MIN_THREAD_N, + max_parallel: int = const.MAX_PARALLEL, +) -> torch.Tensor: + """Creates a workspace for marlin qqq. The workspace is used to coordinate the locks + during the execution of the kernel. + + Args: + out_features (int): The number of output features. + min_thread_n (int, optional): The minimum number of threads per block. Defaults to `MARLIN_QQQ_MIN_THREAD_N`. + max_parallel (int, optional): The maximum number of parallel threads. Defaults to `MARLIN_QQQ_MAX_PARALLEL`. + Returns: + torch.Tensor: The workspace tensor fully initialized with zeros. + """ + assert out_features % min_thread_n == 0, ( + f"out_features = {out_features}, min_thread_n = {min_thread_n}" + ) + max_workspace_size = (out_features // min_thread_n) * max_parallel + return torch.zeros(max_workspace_size, dtype=torch.int, device="cuda") + + +def pack_to_marlin_qqq( + q_w: torch.Tensor, + s_group: torch.Tensor, + s_channel: torch.Tensor, + num_bits: int, + group_size: int, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Pack the quantized weights and scales to the marlin format. + + Args: + q_w (torch.Tensor): The quantized weight. + s_group (torch.Tensor): The per-group quantization scale. + s_channel (torch.Tensor): The per-channel quantization scale. + num_bits (int): The number of bits used for quantization. + group_size (int): The group size of quantization. + Returns: + Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: The packed quantized weight in marlin format, the packed per-group scale in marlin format, and the packed per-channel scale in marlin format. + """ + in_features, out_features = q_w.shape + + assert num_bits == 4, "Marlin QQQ only supports 4-bit for now." + + # Reformat to marlin + marlin_qqq_q_w = _to_marlin_weights( + q_w, in_features, out_features, num_bits, group_size + ) + marlin_qqq_s_group, marlin_qqq_s_channel = _to_marlin_scales( + s_group, s_channel, in_features, out_features, num_bits, group_size + ) + + return marlin_qqq_q_w, marlin_qqq_s_group, marlin_qqq_s_channel + + +def _to_marlin_weights( + q_w: torch.Tensor, + size_k: int, + size_n: int, + num_bits: int, + group_size: int, +) -> torch.Tensor: + """Converts a quantized weight tensor to the marlin format. + + Args: + q_w (torch.Tensor): The quantized weight. + size_k (int): The number of input features. + size_n (int): The number of output features. + num_bits (int): The number of bits used for quantization. + group_size (int): The group size of quantization. + Returns: + torch.Tensor: The packed quantized weight in marlin format. + """ + if group_size == -1: + group_size = size_k + granularity = PerAxis(1) if group_size == size_k else PerGroup(group_size) + # Permute + perm = get_qqq_weight_perm(num_bits, granularity) + q_w = marlin_permute_weights(q_w, size_k, size_n, perm) + + # Pack + pack_factor = get_pack_factor(num_bits) + orig_device = q_w.device + + # q_w is torch.uint32 originally, but torch does not support lshift_cuda or lshift_cpu, we have to + # convert it to torch.int64 + q_w = q_w.to(torch.int64) + q_packed = torch.zeros( + (q_w.shape[0], q_w.shape[1] // pack_factor), + dtype=torch.int64, + device=q_w.device, + ) + + if group_size == size_k: + for i in range(pack_factor): + q_packed |= (q_w[:, i::pack_factor] & 0xF) << (num_bits * i) + else: + for i in range(pack_factor): + q_packed |= q_w[:, i::pack_factor] << (num_bits * i) + + q_packed = q_packed.to(torch.int32).to(orig_device) + return q_packed + + +def _to_marlin_scales( + s_group: torch.Tensor, + s_channel: torch.Tensor, + size_k: int, + size_n: int, + num_bits: int, + group_size: int, +) -> Tuple[torch.Tensor, torch.Tensor]: + """Converts the per-group scale and the per-channel scale to the format necessary for marlin. + + Args: + s_group (torch.Tensor): The per-group quantization scale. + s_channel (torch.Tensor): The per-channel quantization scale. + size_k (int): The number of input features. + size_n (int): The number of output features. + num_bits (int): The number of bits used for quantization. + group_size (int): The group size of quantization. + Returns: + Tuple[torch.Tensor, torch.Tensor]: The scale tensors in the marlin format. + """ + if group_size == -1: + group_size = size_k + scale_perm, scale_perm_single = get_qqq_scale_perms(num_bits) + if group_size < size_k: + s_group = s_group.reshape((-1, len(scale_perm)))[:, scale_perm] + s_channel = s_channel.reshape((-1, len(scale_perm_single)))[ + :, scale_perm_single + ] + s_group = s_group.reshape((-1, size_n)).contiguous() + else: + s_channel = s_channel.reshape((-1, len(scale_perm_single)))[ + :, scale_perm_single + ] + s_channel = s_channel.reshape((-1, size_n)).contiguous() + + return s_group, s_channel + + +def unpack_from_marlin_qqq( + q_w: torch.Tensor, + s_group: torch.Tensor, + s_channel: torch.Tensor, + original_shape: torch.Size, + num_bits: int, + group_size: int, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """Unpacks the quantized weights and scales from the marlin format. + Args: + q_w (torch.Tensor): The packed quantized weights. + s_group (torch.Tensor): The per-group quantization scale. + s_channel (torch.Tensor): The per-channel quantization scale. + original_shape (torch.Size): The original shape of the weight tensor. + num_bits (int): The number of bits used for quantization. + group_size (int): The group size of quantization. + Returns: + Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: The unpacked quantized weights and scales. + """ + in_features, out_features = original_shape + + assert num_bits == 4, "Marlin QQQ only supports 4-bit for now." + + # Unpacks the scales + unpacked_s_group, unpacked_s_channel = _from_marlin_scales( + s_group, s_channel, in_features, out_features, num_bits, group_size + ) + + # Unpacks the weights + unpacked_q_w = _from_marlin_weights( + q_w, in_features, out_features, num_bits, group_size + ) + + return unpacked_q_w, unpacked_s_group, unpacked_s_channel + + +def _from_marlin_weights( + q_w: torch.Tensor, + size_k: int, + size_n: int, + num_bits: int, + group_size: int, +) -> torch.Tensor: + """Converts a weight tensor in the marlin format to a regular format. + Args: + q_w (torch.Tensor): The packed quantized weights. + size_k (int): The number of input features. + size_n (int): The number of output features. + num_bits (int): The number of bits used for quantization. + group_size (int): The group size of quantization. + Returns: + torch.Tensor: The unpacked quantized weights. + """ + if group_size == -1: + group_size = size_k + granularity = PerAxis(1) if group_size == size_k else PerGroup(group_size) + # Permute + perm = get_qqq_weight_reverse_perm(num_bits, granularity) + + orig_device = q_w.device + + wf = ( + torch.tensor(list(range(0, 32, num_bits)), dtype=torch.int32) + .unsqueeze(0) + .to(orig_device) + ) + # unpack weight + weight = torch.bitwise_right_shift( + torch.unsqueeze(q_w, 2).expand(-1, -1, 32 // num_bits), + wf.unsqueeze(0), + ) + weight = torch.bitwise_and(weight, (2**num_bits) - 1) + weight = weight.reshape(weight.shape[0], weight.shape[1] * weight.shape[2]) + q_w_comp = reverse_marlin_permute_weights(weight, size_k, size_n, perm) + + return q_w_comp + + +def _from_marlin_scales( + s_group: torch.Tensor, + s_channel: torch.Tensor, + size_k: int, + size_n: int, + num_bits: int, + group_size: int, +) -> Tuple[torch.Tensor, torch.Tensor]: + """Converts the quantization scales from the marlin format to their original format. + Args: + s_group (torch.Tensor): The per-group quantization scale in marlin format. + s_channel (torch.Tensor): The per-channel quantization scale in marlin format. + size_k (int): The number of input features. + size_n (int): The number of output features. + num_bits (int): The number of bits used for quantization. + group_size (int): The group size of quantization. + Returns: + Tuple[torch.Tensor, torch.Tensor]: The per-group quantization scale in the original format and + the per-channel quantization scale in the original format. + """ + if group_size == -1: + group_size = size_k + scale_perm, scale_perm_single = get_qqq_scale_reverse_perms(num_bits) + if group_size < size_k: + s_group = s_group.reshape((-1, len(scale_perm)))[:, scale_perm] + s_channel = s_channel.reshape((-1, len(scale_perm_single)))[ + :, scale_perm_single + ] + s_group = s_group.reshape((-1, size_n)).contiguous() + else: + s_channel = s_channel.reshape((-1, len(scale_perm_single)))[ + :, scale_perm_single + ] + s_channel = s_channel.reshape((-1, size_n)).contiguous() + + return s_group, s_channel diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/marlin_qqq/utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/marlin_qqq/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c1fe817dba7685fcbde1667e010851e68ade02cb --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/marlin_qqq/utils.py @@ -0,0 +1,198 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +from dataclasses import dataclass, field +from typing import List, Tuple + +import numpy +import torch + +from torchao.quantization.granularity import ( + Granularity, + PerAxis, +) + + +@dataclass(frozen=True) +class MarlinQQQConstants: + TILE: int = 16 + MIN_THREAD_N: int = 64 + MAX_PARALLEL: int = 16 + + SUPPORTED_NUM_BITS: List[int] = field(default_factory=lambda: [4]) + SUPPORTED_GROUP_SIZES: List[int] = field(default_factory=lambda: [-1, 128]) + + +const = MarlinQQQConstants() + + +def get_pack_factor(num_bits: int) -> int: + """Compute the packing factor for a given number of bits. + + Args: + num_bits (int): Number of bits to pack. + Returns: + int: The packing factor. + """ + assert 32 % num_bits == 0, f"Unsupported num_bits = {num_bits}" + return 32 // num_bits + + +def marlin_permute_weights( + q_w: torch.Tensor, + size_k: int, + size_n: int, + perm: torch.Tensor, + tile: int = const.TILE, +) -> torch.Tensor: + """Permute weights to 16x64 Marlin tiles. + + Args: + q_w (torch.Tensor): Quantized weights. + size_k (int): Number of input features. + size_n (int): Number of output features. + perm (torch.Tensor): The computed permutation tensor to be applied. + tile (int, optional): Tile size. Defaults to `TILE`. + Returns: + torch.Tensor: Weight tensor permuted to Marlin tiles. + """ + assert q_w.shape == (size_k, size_n) + assert size_k % tile == 0, f"size_k = {size_k}, tile = {tile}" + assert size_n % tile == 0, f"size_k = {size_n}, tile = {tile}" + + # Permute weights to 16x64 marlin tiles + q_w = q_w.reshape((size_k // tile, tile, size_n // tile, tile)) + q_w = q_w.permute((0, 2, 1, 3)) + q_w = q_w.reshape((size_k // tile, size_n * tile)) + + q_w = q_w.reshape((-1, perm.numel()))[:, perm].reshape(q_w.shape) + + return q_w + + +def reverse_marlin_permute_weights( + q_w_unpacked: torch.Tensor, + size_k: int, + size_n: int, + reverse_perm: torch.Tensor, + tile: int = const.TILE, +) -> torch.Tensor: + """Reverse permute weights from 16x64 Marlin tiles. + Args: + q_w_unpacked (torch.Tensor): Unpacked quantized weights. + size_k (int): Number of input features. + size_n (int): Number of output features. + reverse_perm (torch.Tensor): The computed reverse permutation tensor to be applied. + tile (int, optional): Tile size. Defaults to `TILE`. + Returns: + torch.Tensor: Weight tensor reverse permuted from Marlin tiles. + """ + + assert (q_w_unpacked.shape[0], size_n) == ( + size_k // tile, + q_w_unpacked.shape[1] // tile, + ) + assert size_k % tile == 0, f"size_k = {size_k}, tile = {tile}" + assert size_n % tile == 0, f"size_k = {size_n}, tile = {tile}" + + # Reverse permute weights to original shape + q_w_comp = q_w_unpacked.reshape((-1, reverse_perm.numel()))[ + :, reverse_perm + ].reshape(q_w_unpacked.shape) + q_w_comp = q_w_comp.reshape((size_k // tile, size_n // tile, tile, tile)) + q_w_comp = q_w_comp.permute((0, 2, 1, 3)) + q_w_comp = q_w_comp.reshape((size_k, size_n)) + + return q_w_comp + + +# NOTE(HandH1998): QQQ employs different perms for per-group and per-channel weight quantization. # noqa: E501 +def get_qqq_weight_perm(num_bits: int, granularity: Granularity) -> torch.Tensor: + """Precompute permutations for the marlin weight shuffling. + + Args: + num_bits (int): Number of bits to pack. + granularity (Granularity): The weight quantization granularity. + Returns: + torch.Tensor: The weight permutation tensor. + """ + perm_list: List[int] = [] + for i in range(32): + perm1: List[int] = [] + col = i // 4 + for block in [0, 1]: + for row in [ + 4 * (i % 4), + 4 * (i % 4) + 1, + 4 * (i % 4) + 2, + 4 * (i % 4) + 3, + ]: + perm1.append(16 * row + col + 8 * block) + for j in range(4): + perm_list.extend([p + 256 * j for p in perm1]) + + perm = numpy.array(perm_list) + + if num_bits == 4: + if isinstance(granularity, PerAxis): + interleave = numpy.array([4, 0, 5, 1, 6, 2, 7, 3]) + else: + interleave = numpy.array([0, 2, 4, 6, 1, 3, 5, 7]) + else: + raise Exception("num_bits must be 4, got {}".format(num_bits)) + + perm = perm.reshape((-1, len(interleave)))[:, interleave].ravel() + perm = torch.from_numpy(perm) + return perm + + +def get_qqq_scale_perms(num_bits: int) -> Tuple[List[int], List[int]]: + """Precompute permutations for the marlin scale shuffling. + Args: + num_bits (int): Number of bits to pack. + Returns: + Tuple[List[int], List[int]]: Scale permutation list and + scale permutation list for a single group. + """ + if num_bits != 4: + raise Exception("num_bits must be 4, got {}".format(num_bits)) + scale_perm: List[int] = [] + for i in range(8): + scale_perm.extend([i + 8 * j for j in range(8)]) + scale_perm_single: List[int] = [] + for i in range(4): + scale_perm_single.extend([2 * i + j for j in [0, 1, 8, 9, 16, 17, 24, 25]]) + return scale_perm, scale_perm_single + + +def get_qqq_weight_reverse_perm( + num_bits: int, granularity: Granularity +) -> torch.Tensor: + """Reverse permutation for Marlin weight shuffling from `get_qqq_weight_perm`. + Args: + num_bits (int): Number of bits to pack. + granularity (Granularity): The weight quantization granularity. + Returns: + torch.Tensor: The reversed weight permutation tensor. + """ + perm = get_qqq_weight_perm(num_bits, granularity) + perm = perm.argsort() + + return perm + + +def get_qqq_scale_reverse_perms(num_bits: int) -> Tuple[torch.Tensor, torch.Tensor]: + """Reverse permutation for Marlin scale shuffling from `get_qqq_scale_perms`. + Args: + num_bits (int): Number of bits to pack. + Returns: + Tuple[List[int], List[int]]: The reversed scale permutation list and + the reversed scale permutation list for a single group. + """ + scale_perm, scale_perm_single = get_qqq_scale_perms(num_bits) + scale_perm = torch.tensor(scale_perm).argsort() + scale_perm_single = torch.tensor(scale_perm_single).argsort() + + return scale_perm, scale_perm_single diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/README.md b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dbce4d48e16c6e82606814833f47aa87992c303d --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/README.md @@ -0,0 +1,3 @@ +Note: QAT has been moved to torchao/quantization/qat. +This is a legacy folder only for backward compatibility +and will be removed in the near future. diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa0084c6ea4c3ee4575999e6eecf177a172be4be --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/__init__.py @@ -0,0 +1,25 @@ +from torchao.quantization.qat import ( + ComposableQATQuantizer, + Int4WeightOnlyEmbeddingQATQuantizer, + Int4WeightOnlyQATQuantizer, + Int8DynActInt4WeightQATQuantizer, +) +from torchao.quantization.qat.linear import ( + Int8DynActInt4WeightQATLinear, + disable_4w_fake_quant, + disable_8da4w_fake_quant, + enable_4w_fake_quant, + enable_8da4w_fake_quant, +) + +__all__ = [ + "disable_4w_fake_quant", + "disable_8da4w_fake_quant", + "enable_4w_fake_quant", + "enable_8da4w_fake_quant", + "ComposableQATQuantizer", + "Int4WeightOnlyQATQuantizer", + "Int4WeightOnlyEmbeddingQATQuantizer", + "Int8DynActInt4WeightQATQuantizer", + "Int8DynActInt4WeightQATLinear", +] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/_module_swap_api.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/_module_swap_api.py new file mode 100644 index 0000000000000000000000000000000000000000..a0fbd877b2af1deeb60e0b72cefbb1cf52cb0641 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/_module_swap_api.py @@ -0,0 +1,30 @@ +# For backward compatibility only +# These will be removed in the future + +from torchao.quantization.qat.linear import ( + Int4WeightOnlyQATQuantizer as Int4WeightOnlyQATQuantizerModuleSwap, +) +from torchao.quantization.qat.linear import ( + Int8DynActInt4WeightQATQuantizer as Int8DynActInt4WeightQATQuantizerModuleSwap, +) +from torchao.quantization.qat.linear import ( + disable_4w_fake_quant as disable_4w_fake_quant_module_swap, +) +from torchao.quantization.qat.linear import ( + disable_8da4w_fake_quant as disable_8da4w_fake_quant_module_swap, +) +from torchao.quantization.qat.linear import ( + enable_4w_fake_quant as enable_4w_fake_quant_module_swap, +) +from torchao.quantization.qat.linear import ( + enable_8da4w_fake_quant as enable_8da4w_fake_quant_module_swap, +) + +__all__ = [ + "Int8DynActInt4WeightQATQuantizerModuleSwap", + "Int4WeightOnlyQATQuantizerModuleSwap", + "enable_8da4w_fake_quant_module_swap", + "disable_8da4w_fake_quant_module_swap", + "enable_4w_fake_quant_module_swap", + "disable_4w_fake_quant_module_swap", +] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/affine_fake_quantized_tensor.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/affine_fake_quantized_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..20d51912f0f424c02ad318c10a2101680f8ca1e3 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/affine_fake_quantized_tensor.py @@ -0,0 +1,9 @@ +from torchao.quantization.qat.affine_fake_quantized_tensor import ( + AffineFakeQuantizedTensor, + to_affine_fake_quantized, +) + +__all__ = [ + "AffineFakeQuantizedTensor", + "to_affine_fake_quantized", +] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/api.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/api.py new file mode 100644 index 0000000000000000000000000000000000000000..c2f1d6f8d7deaa51fdfb31133da3adaa257d330f --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/api.py @@ -0,0 +1,9 @@ +from torchao.quantization.qat.api import ( + ComposableQATQuantizer, + FakeQuantizeConfig, +) + +__all__ = [ + "ComposableQATQuantizer", + "FakeQuantizeConfig", +] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/embedding.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/embedding.py new file mode 100644 index 0000000000000000000000000000000000000000..98b4d05720eb16359ed30c4dace2cbfe52efa4c7 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/embedding.py @@ -0,0 +1,13 @@ +from torchao.quantization.qat.embedding import ( + FakeQuantizedEmbedding, + Int4WeightOnlyEmbedding, + Int4WeightOnlyEmbeddingQATQuantizer, + Int4WeightOnlyQATEmbedding, +) + +__all__ = [ + "FakeQuantizedEmbedding", + "Int4WeightOnlyEmbeddingQATQuantizer", + "Int4WeightOnlyEmbedding", + "Int4WeightOnlyQATEmbedding", +] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/fake_quantizer.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/fake_quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..3bbe1fb704469e98dbc1bf964d68e2e621bc581d --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/fake_quantizer.py @@ -0,0 +1,7 @@ +from torchao.quantization.qat.fake_quantizer import ( + FakeQuantizer, +) + +__all__ = [ + "FakeQuantizer", +] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/linear.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/linear.py new file mode 100644 index 0000000000000000000000000000000000000000..366ab3565cfcb40fed671a81a64a03d0d1079f53 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/prototype/qat/linear.py @@ -0,0 +1,23 @@ +from torchao.quantization.qat.linear import ( + FakeQuantizedLinear, + Int4WeightOnlyQATLinear, + Int4WeightOnlyQATQuantizer, + Int8DynActInt4WeightQATLinear, + Int8DynActInt4WeightQATQuantizer, + disable_4w_fake_quant, + disable_8da4w_fake_quant, + enable_4w_fake_quant, + enable_8da4w_fake_quant, +) + +__all__ = [ + "disable_4w_fake_quant", + "disable_8da4w_fake_quant", + "enable_4w_fake_quant", + "enable_8da4w_fake_quant", + "FakeQuantizedLinear", + "Int4WeightOnlyQATLinear", + "Int4WeightOnlyQATQuantizer", + "Int8DynActInt4WeightQATLinear", + "Int8DynActInt4WeightQATQuantizer", +] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/_affine_quantization.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/_affine_quantization.py new file mode 100644 index 0000000000000000000000000000000000000000..e02bee03ce9735164aad2c20f913c31ab45a1161 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/_affine_quantization.py @@ -0,0 +1,813 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# copied from https://github.com/pytorch/ao/blob/main/torchao/quantization/observer.py +# and https://github.com/pytorch/ao/blob/main/torchao/quantization/quant_primitives.py +# PLESE DON'T MODIFY THIS FILE SO THAT WE DON'T GET OUT OF SYNC +import logging +from abc import ABCMeta +from typing import Any, List, Optional, Union + +import torch + +from torchao.quantization.pt2e.observer import ( + AffineQuantizedObserverBase, + Granularity, + MappingType, + TorchAODType, + ZeroPointDomain, + get_block_size, +) + +ABC: Any = ABCMeta("ABC", (object,), {}) # compatible with Python 2 *and* 3: + +logger = logging.getLogger(__name__) + +FP8_TYPES = { + torch.float8_e4m3fn, + torch.float8_e5m2, + torch.float8_e4m3fnuz, + torch.float8_e5m2fnuz, +} +_SUB_BYTE_UINT_BOUNDS = { + torch.uint1: (0, 2**1 - 1), + torch.uint2: (0, 2**2 - 1), + torch.uint3: (0, 2**3 - 1), + torch.uint4: (0, 2**4 - 1), + torch.uint5: (0, 2**5 - 1), + torch.uint6: (0, 2**6 - 1), + torch.uint7: (0, 2**7 - 1), +} + +""" +Map from dtype to the bound value of integers +TODO: maybe can replace this with call to torch.iinfo +""" +_DTYPE_TO_QVALUE_BOUNDS: dict[Union[torch.dtype, TorchAODType], tuple[int, int]] = { + torch.uint8: (0, 255), + torch.int8: (-128, 127), + torch.int16: (-(2**15), 2**15 - 1), + torch.int32: (-(2**31), 2**31 - 1), +} +_DTYPE_TO_QVALUE_BOUNDS.update(_SUB_BYTE_UINT_BOUNDS) + + +def _is_float8_type(dtype: torch.dtype) -> bool: + fp8_types = { + torch.float8_e4m3fn, + torch.float8_e4m3fnuz, + torch.float8_e5m2, + torch.float8_e5m2fnuz, + } + return dtype in fp8_types + + +# TODO: decide on if we want to allow custom quant_min/quant_max here +def _get_and_check_qmin_qmax(dtype, quant_min, quant_max): + """Get quant_min and quant_max args based on dtype and also + verify that they are within the range of possible quant_min/quant_max + for dtype + """ + if dtype in FP8_TYPES: + quant_min_lower_bound, quant_max_upper_bound = ( + torch.finfo(dtype).min, + torch.finfo(dtype).max, + ) + elif dtype not in _DTYPE_TO_QVALUE_BOUNDS: + raise ValueError(f"Unsupported dtype: {dtype}") + else: + quant_min_lower_bound, quant_max_upper_bound = _DTYPE_TO_QVALUE_BOUNDS[dtype] + if quant_min is None: + quant_min = quant_min_lower_bound + if quant_max is None: + quant_max = quant_max_upper_bound + + assert quant_min >= quant_min_lower_bound, ( + "quant_min out of bound for dtype, " + f"quant_min_lower_bound: {quant_min_lower_bound} quant_min: {quant_min}" + ) + + assert quant_max <= quant_max_upper_bound, ( + "quant_max out of bound for dtype, " + f"quant_max_upper_bound: {quant_max_upper_bound} quant_max: {quant_max}" + ) + return quant_min, quant_max + + +def _get_reduction_params(block_size, input_size): + """Given block_size and input size find the parameters for reduction: + + Output: + shape_for_reduction: the shape we use to `view` input to prepare it for reduction + reduction_dims: the dims we'll do reduction over + + Example:: + Input: + block_size: (3, 3, 2, 10) + input_size: (3, 3, 10, 10) + + Output: + shape_for_reduction: (3, 3, 5, 2, 10) + reduction_dim: [0, 1, 3, 4] + """ + assert len(block_size) == len(input_size) + shape_for_reduction = [] + reduction_dims = [] + cur_dim = 0 + for i in range(len(block_size)): + if block_size[i] != input_size[i] and block_size[i] > 1: + assert input_size[i] % block_size[i] == 0, ( + f"Expecting input size at {i} dimension: " + f"{input_size[i]} to be divisible by block_size at {i} dimension: {block_size[i]}" + ) + shape_for_reduction.append(input_size[i] // block_size[i]) + shape_for_reduction.append(block_size[i]) + # reduce over the block_size[i] dim + reduction_dims.append(cur_dim + 1) + cur_dim += 2 + else: + # block_size[i] == input_size[i] or block_size[i] == 1 + shape_for_reduction.append(input_size[i]) + # we only need to reduce over the dimension if block_size is greater than 1 + # otherwise it's already the same as reduced dimension + if block_size[i] != 1: + reduction_dims.append(cur_dim) + cur_dim += 1 + return shape_for_reduction, reduction_dims + + +def choose_qparams_affine_with_min_max( + min_val: torch.Tensor, + max_val: torch.Tensor, + mapping_type: MappingType, + block_size: tuple[int, ...], + target_dtype: torch.dtype, + quant_min: Optional[int] = None, + quant_max: Optional[int] = None, + eps: Optional[float] = None, + scale_dtype: Optional[torch.dtype] = None, + zero_point_dtype: Optional[torch.dtype] = None, + preserve_zero: bool = True, + zero_point_domain: Optional[ZeroPointDomain] = ZeroPointDomain.INT, +) -> tuple[torch.Tensor, torch.Tensor]: + """A variant of :func:`~torchao.quantization.quant_primitives.choose_qparams_affine` + operator that pass in min_val and max_val directly instead of deriving these from a single input. + This is used for observers in static quantization where min_val and max_val may be obtained through + tracking all the data in calibration data set. + + Args: + Mostly same as :func:`~torchao.quantization.quant_primitives.choose_qparams_affine`. with one + difference: instead of passing in `input` Tensor and use that to calculate min_val/max_val + and then scale/zero_point, we pass in min_val/max_val directly + """ + return _choose_qparams_affine( + None, + mapping_type.name, + block_size, + target_dtype, + quant_min, + quant_max, + eps, + scale_dtype, + zero_point_dtype, + preserve_zero, + zero_point_domain.name if zero_point_domain is not None else None, + min_val, + max_val, + ) + + +def _choose_qparams_affine( + input: Optional[torch.Tensor], + mapping_type: str, + block_size: List[int], + target_dtype: torch.dtype, + quant_min: Optional[Union[int, float, bool]] = None, + quant_max: Optional[Union[int, float, bool]] = None, + eps: Optional[float] = None, + scale_dtype: Optional[torch.dtype] = None, + zero_point_dtype: Optional[torch.dtype] = None, + preserve_zero: bool = True, + zero_point_domain: Optional[str] = "INT", + min_val: Optional[torch.Tensor] = None, + max_val: Optional[torch.Tensor] = None, +) -> tuple[torch.Tensor, torch.Tensor]: + """op definition that has compatible signatures with custom op library + + The op does the following: + 1. figure out the dimension for reduction based on block_size + 2. find min_val/max_val based on the dimension for reduction + 3. calculate quantization parameters based on min_val/max_val based on args like `preserve_zero` + and `zero_point_domain` + """ + quant_min, quant_max = _get_and_check_qmin_qmax(target_dtype, quant_min, quant_max) + assert mapping_type in [ + MappingType.SYMMETRIC.name, + MappingType.SYMMETRIC_NO_CLIPPING_ERR.name, + MappingType.ASYMMETRIC.name, + ], f"Unsupported mapping type: {mapping_type}" + if target_dtype in FP8_TYPES: + assert mapping_type == MappingType.SYMMETRIC.name, ( + f"Only symmetric quantization is supported for FP8 types, got {mapping_type}" + ) + + if input is not None: + if scale_dtype is None: + scale_dtype = input.dtype + if zero_point_dtype is None: + zero_point_dtype = input.dtype + if eps is None: + eps = torch.finfo(input.dtype).eps + + assert len(block_size) == input.dim(), ( + f"Got input dim:{input.dim()}, block_size: {block_size}" + ) + shape_for_reduction, reduction_dims = _get_reduction_params( + block_size, input.size() + ) + input = input.view(shape_for_reduction) + + min_val = torch.amin(input, dim=reduction_dims, keepdim=False) + max_val = torch.amax(input, dim=reduction_dims, keepdim=False) + else: + assert min_val is not None and max_val is not None, ( + "Need to provide `min_val` and `max_val` when `input` is None, got: {min_val, max_val}" + ) + assert min_val.dtype == max_val.dtype, ( + "Expecting `min_val` and `max_val` to have the same dtype, got: {min_val.dtype, max_val.dtype}" + ) + + if scale_dtype is None: + scale_dtype = min_val.dtype + if zero_point_dtype is None: + zero_point_dtype = min_val.dtype + if eps is None: + eps = torch.finfo(min_val.dtype).eps + + if preserve_zero: + min_val_neg = torch.min(min_val, torch.zeros_like(min_val)) + max_val_pos = torch.max(max_val, torch.zeros_like(max_val)) + else: + min_val_neg = min_val + max_val_pos = max_val + + if ( + mapping_type == MappingType.SYMMETRIC.name + or mapping_type == MappingType.SYMMETRIC_NO_CLIPPING_ERR.name + ): + # scales + if mapping_type == MappingType.SYMMETRIC.name: + max_val_pos = torch.max(-min_val_neg, max_val_pos) + scale = max_val_pos / (float(quant_max - quant_min) / 2) + else: + assert mapping_type == MappingType.SYMMETRIC_NO_CLIPPING_ERR.name + # calculate smin and smax individually and choose the larger one. For example, if quant_min = -8 and + # quant_max = 7. + # - If smin is bigger: There would be coverage on negative values down to -8, and less rounding + # error than the existing SYMMETRIC case. + # - If smax is bigger: it covers the positive values up to 7. The round + # error may be bigger than the existing SYMMETRIC case. Either way, there's no out-of-range fp values after + # quantization. + smin = min_val_neg / float(quant_min) + smax = max_val_pos / float(quant_max) + mask = smin > smax + scale = torch.where(mask, smin, smax) + # zeros + if not preserve_zero: + raise ValueError( + "preserve_zero == False is not supported for symmetric quantization" + ) + if ( + zero_point_domain is not None + and zero_point_domain != ZeroPointDomain.INT.name + ): + raise ValueError( + "zero_point_domain != ZeroPointDomain.INT is not supported for symmetric quantization" + ) + scale = torch.clamp(scale, min=eps) + zero_point = torch.full_like(scale, int((quant_max + quant_min + 1) / 2)) + else: + assert mapping_type == MappingType.ASYMMETRIC.name + scale = (max_val_pos - min_val_neg) / float(quant_max - quant_min) + scale = torch.clamp(scale, min=eps) + if zero_point_domain == ZeroPointDomain.NONE.name: + zero_point = None + else: + if preserve_zero: + zero_point = quant_min - torch.round(min_val_neg / scale) + zero_point = torch.clamp(zero_point, quant_min, quant_max) + else: + assert zero_point_domain == ZeroPointDomain.FLOAT.name, ( + "if not preserve_zero, zero_point must be in FLOAT domain" + ) + mid_point = (quant_max + quant_min + 1) / 2 + zero_point = min_val_neg + scale * mid_point + + if zero_point is not None: + zero_point = zero_point.to(dtype=zero_point_dtype) + return scale.to(dtype=scale_dtype), zero_point + + +@torch.no_grad() +def quantize_affine( + input: torch.Tensor, + block_size: tuple[int, ...], + scale: torch.Tensor, + zero_point: Optional[torch.Tensor], + output_dtype: torch.dtype, + quant_min: Optional[Union[int, float]] = None, + quant_max: Optional[Union[int, float]] = None, + zero_point_domain: Optional[ZeroPointDomain] = ZeroPointDomain.INT, +) -> torch.Tensor: + """ + Args: + input (torch.Tensor): original float32, float16 or bfloat16 Tensor + block_size: (Tuple[int, ...]): granularity of quantization, + this means the size of the tensor elements that's sharing the same qparam + e.g. when size is the same as the input tensor dimension, we are using per tensor quantization + scale (float): quantization parameter for affine quantization + zero_point (int): quantization parameter for affine quantization + output_dtype (torch.dtype): requested dtype (e.g. torch.uint8) for output Tensor + quant_min (Optional[int]): minimum quantized value for output Tensor, if not specified, it will be derived from dtype + quant_max (Optional[int]): maximum quantized value for output Tensor, if not specified, it will be derived from dtype + zero_point_domain (ZeroPointDomain): the domain that zero_point is in, should be either integer or float + if zero_point is in integer domain, zero point is added to the quantized integer value during + quantization + if zero_point is in floating point domain, zero point is subtracted from the floating point (unquantized) + value during quantization + default is ZeroPointDomain.INT + + Note: + How can block_size represent different granularities? + let's say we have a Tensor of size: (3, 3, 10, 10), here is the table showing how block_size represents different + granularities: + + granularity type | block_size + per_tensor | (3, 3, 10, 10) + per_axis (axis=0) | (1, 3, 10, 10) + per_axis (axis=1) | (3, 1, 10, 10) + per_group (groupsize=2) | (3, 3, 10, 2) + per_group (groupsize=2) for axis = 3 | (3, 3, 2, 10) + + + Output: + quantized tensor with requested dtype + """ + return _quantize_affine( + input, + block_size, + scale, + zero_point, + output_dtype, + quant_min, + quant_max, + zero_point_domain.name if zero_point_domain is not None else None, + ) + + +def _quantize_affine( + input: torch.Tensor, + block_size: list[int], + scale: torch.Tensor, + zero_point: Optional[torch.Tensor], + output_dtype: torch.dtype, + quant_min: Optional[Union[int, float, bool]] = None, + quant_max: Optional[Union[int, float, bool]] = None, + zero_point_domain: Optional[str] = ZeroPointDomain.INT.name, +) -> torch.Tensor: + """op definition that has compatible signatures with custom op library + + Note: + zero_point_domain is optional specifies how we quantize the floating point to quantized data: + INT: quantized_val = (float_val / scale) (integer) + zero_point (integer) + FLOAT: quantized_val = (float_val - (zero_point (float) - scale * mid_point)) / scale + None: quantized_val = (float_val / scale) | this is primarily used for floatx quantization + Where we do not want to round values to nearest integer and instead scale and cast. + """ + quant_min, quant_max = _get_and_check_qmin_qmax(output_dtype, quant_min, quant_max) + # workaround for uintx dtypes, since we don't have native Uintx dtype connected with + # torch.uintx dtypes yet + if output_dtype in _SUB_BYTE_UINT_BOUNDS: + output_dtype = torch.uint8 + return _quantize_affine_no_dtype_cast( + input, + block_size, + scale, + zero_point, + quant_min, + quant_max, + zero_point_domain, + ).to(output_dtype) + + +def _quantize_affine_no_dtype_cast( + input: torch.Tensor, + block_size: list[int], + scale: torch.Tensor, + zero_point: Optional[torch.Tensor], + quant_min: Union[int, float], + quant_max: Union[int, float], + zero_point_domain: Optional[str] = ZeroPointDomain.INT.name, +) -> torch.Tensor: + """ + The op does the following: + 1. figure out the dimension for reduction based on block_size, also reshape the input to align with + the shape after reduction + 2. quantize the input based on the quantization parameters scale and zero_point and args like zero_point_domain + 3. reshape the quantized result to origianl shape + """ + # TODO: validations + # TODO: validate scale/zero_point dimensions are compatible with block_size + assert input.dtype in [ + torch.float32, + torch.float16, + torch.bfloat16, + ], f"Unsupported input dtype: {input.dtype}" + assert len(block_size) == input.dim(), ( + f"Got input dim:{input.dim()}, block_size: {block_size}" + ) + shape_for_reduction, reduction_dims = _get_reduction_params( + block_size, input.size() + ) + original_shape = input.shape + input = input.view(shape_for_reduction) + shape_after_reduction = shape_for_reduction + for i in reduction_dims: + shape_after_reduction[i] = 1 + scale = scale.view(shape_after_reduction) + if zero_point is not None: + zero_point = zero_point.view(shape_after_reduction) + + if zero_point_domain == ZeroPointDomain.INT.name: + quant = torch.clamp( + torch.round(input * (1.0 / scale)) + zero_point, quant_min, quant_max + ) + elif zero_point_domain == ZeroPointDomain.NONE.name: + assert zero_point is None, ( + "zero_point should be None when zero_point_domain is NONE" + ) + quant = torch.clamp(torch.round(input * (1.0 / scale)), quant_min, quant_max) + elif zero_point_domain is None: + # This case handles quantization for float8 we expect no zero point and no zero point domain + assert zero_point is None, ( + "zero_point should be None when zero_point_domain is None" + ) + quant = torch.clamp(input * scale.reciprocal(), quant_min, quant_max) + else: + assert zero_point_domain == ZeroPointDomain.FLOAT.name + mid_point = (quant_max + quant_min + 1) / 2 + min_val = zero_point - scale * mid_point + quant = torch.clamp( + torch.round((input - min_val) / scale), quant_min, quant_max + ) + quant = quant.view(original_shape) + + return quant + + +def dequantize_affine( + input: torch.Tensor, + block_size: tuple[int, ...], + scale: torch.Tensor, + zero_point: Optional[torch.Tensor], + input_dtype: torch.dtype, + quant_min: Optional[Union[int, float]] = None, + quant_max: Optional[Union[int, float]] = None, + zero_point_domain: ZeroPointDomain = ZeroPointDomain.INT, + *, + output_dtype: torch.dtype = torch.float32, +) -> torch.Tensor: + """ + Args: + input (torch.Tensor): quantized tensor, should match the dtype `dtype` argument + block_size: (List[int]): granularity of quantization, + this means the size of the tensor elements that's sharing the same qparam + e.g. when size is the same as the input tensor dimension, we are using per tensor quantization + scale (Tensor): quantization parameter for affine quantization + zero_point (Tensor): quantization parameter for affine quantization + input_dtype (torch.dtype): requested dtype (e.g. torch.uint8) for output Tensor + quant_min (Optional[int]): minimum quantized value for input Tensor + quant_max (Optional[int]): maximum quantized value for input Tensor + output_dtype (torch.dtype): dtype for output Tensor, default is fp32 + zero_point_domain (ZeroPointDomain): the domain that zero_point is in, should be either integer or float + if zero_point is in integer domain, zero point is added to the quantized integer value during + quantization + if zero_point is in floating point domain, zero point is subtracted from the floating point (unquantized) + value during quantization + default is ZeroPointDomain.INT + + Output: + dequantized Tensor, with requested dtype or fp32 + """ + return _dequantize_affine( + input, + block_size, + scale, + zero_point, + input_dtype, + quant_min, + quant_max, + zero_point_domain.name if zero_point_domain is not None else None, + output_dtype=output_dtype, + ) + + +def _dequantize_affine( + input: torch.Tensor, + block_size: list[int], + scale: torch.Tensor, + zero_point: Optional[torch.Tensor], + input_dtype: torch.dtype, + quant_min: Optional[Union[int, float, bool]] = None, + quant_max: Optional[Union[int, float, bool]] = None, + zero_point_domain: Optional[str] = ZeroPointDomain.INT.name, + output_dtype: torch.dtype = torch.float32, +) -> torch.Tensor: + """op definition that has compatible signatures with custom op library""" + # TODO: validate scale/zero_point dimensions are compatible with block_size + if input_dtype not in _SUB_BYTE_UINT_BOUNDS: + assert input.dtype == input_dtype, ( + f"Expected: {input_dtype}, got: {input.dtype}" + ) + assert output_dtype in [ + torch.float32, + torch.float16, + torch.bfloat16, + ], f"Unsupported output dtype: {output_dtype}" + quant_min, quant_max = _get_and_check_qmin_qmax(input_dtype, quant_min, quant_max) + return _dequantize_affine_no_dtype_check( + input, + block_size, + scale, + zero_point, + quant_min, + quant_max, + zero_point_domain, + output_dtype, + ) + + +def _dequantize_affine_no_dtype_check( + input: torch.Tensor, + block_size: list[int], + scale: torch.Tensor, + zero_point: Optional[torch.Tensor], + quant_min: Union[int, float], + quant_max: Union[int, float], + zero_point_domain: Optional[str] = ZeroPointDomain.INT.name, + output_dtype: torch.dtype = torch.float32, +) -> torch.Tensor: + """This function converts AQT tensors to their high precision floating point representation + + The op does the following: + 1. figure out the dimension for reduction based on block_size, also reshape the input to align with + the shape after reduction + 2. dequantize the input based on the quantization parameters scale and zero_point and args like zero_point_domain + 3. reshape the quantized result to origianl shape and change dtype to the output_dtype + """ + assert len(block_size) == input.dim(), ( + f"Got input dim:{input.dim()}, block_size: {block_size}" + ) + shape_for_reduction, reduction_dims = _get_reduction_params( + block_size, input.size() + ) + original_shape = input.shape + input = input.view(shape_for_reduction) + shape_after_reduction = shape_for_reduction + for i in reduction_dims: + shape_after_reduction[i] = 1 + scale = scale.view(shape_after_reduction) + + if zero_point is not None: + zero_point = zero_point.view(shape_after_reduction) + + if zero_point_domain == ZeroPointDomain.INT.name: + # Force a copy to avoid input modification due + # to upcoming in-place operations. + dequant = input.to(torch.int32, copy=True) + if zero_point is not None: + dequant = dequant - zero_point.to(torch.int32) + dequant = dequant.to(output_dtype) + dequant = dequant * scale + elif zero_point_domain == ZeroPointDomain.NONE.name: + assert zero_point is None, ( + "zero_point should be None when zero_point_domain is NONE" + ) + dequant = input.to(output_dtype) + dequant = dequant * scale + elif zero_point_domain is None: + # This case handles dequantization for float8 we expect no zero point and no zero point domain + assert zero_point is None, ( + "zero_point should be None when zero_point_domain is None" + ) + assert _is_float8_type(input.dtype), ( + f"dequantiztion with no zero point domain is only supported with FP8 types, got {input.dtype}" + ) + dequant = input.to(output_dtype) + dequant = dequant * scale + else: + assert zero_point_domain == ZeroPointDomain.FLOAT.name, ( + f"Unexpected zero point domain: {zero_point_domain}" + ) + # TODO: this seems to be a detail for tinygemm (converting from uint to int, probably need to refactor this) + mid_point = (quant_max + quant_min + 1) / 2 + # This should allocate new memory and avoid input modification + dequant = input - mid_point + dequant = dequant.to(output_dtype) + dequant *= scale + if zero_point is not None: + dequant += zero_point + + return dequant.view(original_shape).to(output_dtype) + + +class AffineQuantizedMinMaxObserver(AffineQuantizedObserverBase): + def forward(self, input: torch.Tensor): + if input.numel() == 0: + return input + + input_detached = input.detach() + self.original_dtype = input_detached.dtype + assert self.granularity is not None, "granularity is None" + self.block_size = get_block_size(input_detached.shape, self.granularity) + + shape_for_reduction, reduction_dims = _get_reduction_params( + self.block_size, input_detached.size() + ) + input_detached = input_detached.view(shape_for_reduction) + min_val = torch.amin(input_detached, dim=reduction_dims, keepdim=False) + max_val = torch.amax(input_detached, dim=reduction_dims, keepdim=False) + if not hasattr(self, "min_val") or not hasattr(self, "max_val"): + self.min_val = min_val + self.max_val = max_val + else: + assert self.min_val.shape == min_val.shape, ( + f"Can't update existing min_val - shape mismatch, self.min_val:{self.min_val.shape} != min_val:{min_val.shape}" + ) + assert self.max_val.shape == max_val.shape, ( + f"Can't update existing max_val - shape mismatch, self.max_val {self.max_val.shape} != max_val:{max_val.shape}" + ) + min_val = torch.min(self.min_val, min_val) + max_val = torch.max(self.max_val, max_val) + self.min_val.copy_(min_val) + self.max_val.copy_(max_val) + # returning original input + return input + + def calculate_qparams(self) -> tuple[torch.Tensor, torch.Tensor]: + assert hasattr(self, "min_val") and hasattr(self, "max_val"), ( + "Expecting the observer has min_val and max_val, please run the observer before calling calculate_qparams" + ) + return choose_qparams_affine_with_min_max( + self.min_val, + self.max_val, + self.mapping_type, + [], # BlockSize is not needed because the min/max are already reduced + self.target_dtype, + self.quant_min, + self.quant_max, + self.eps, + self.scale_dtype, + self.zero_point_dtype, + self.preserve_zero, + self.zero_point_domain, + ) + + +class AffineQuantizedMovingAverageMinMaxObserver(AffineQuantizedObserverBase): + def __init__( + self, + mapping_type: MappingType, + target_dtype: torch.dtype, + granularity: Granularity, + averaging_constant=0.01, + quant_min: Optional[int] = None, + quant_max: Optional[int] = None, + eps: Optional[float] = None, + is_dynamic=False, + scale_dtype: Optional[torch.dtype] = None, + zero_point_dtype: Optional[torch.dtype] = None, + preserve_zero: bool = True, + zero_point_domain: Optional[ZeroPointDomain] = ZeroPointDomain.INT, + # there could be some extra args that's ignored + **kwargs, + ): + self.is_dynamic = is_dynamic + self.averaging_constant = averaging_constant + if is_dynamic and self.averaging_constant != 1: + raise NotImplementedError( + "MovingAverageMinMaxObserver doesn't support dynamic quantization for " + f"averaging constant of {self.averaging_constant}" + ) + + super().__init__( + mapping_type=mapping_type, + target_dtype=target_dtype, + granularity=granularity, + quant_min=quant_min, + quant_max=quant_max, + eps=eps, + scale_dtype=scale_dtype, + zero_point_dtype=zero_point_dtype, + preserve_zero=preserve_zero, + zero_point_domain=zero_point_domain, + ) + + def forward(self, input: torch.Tensor): + if input.numel() == 0: + return input + + input_detached = input.detach() + self.original_dtype = input_detached.dtype + assert self.granularity is not None, "granularity is None" + self.block_size = get_block_size(input_detached.shape, self.granularity) + + shape_for_reduction, reduction_dims = _get_reduction_params( + self.block_size, input_detached.size() + ) + input_detached = input_detached.view(shape_for_reduction) + min_val = torch.amin(input_detached, dim=reduction_dims, keepdim=False) + max_val = torch.amax(input_detached, dim=reduction_dims, keepdim=False) + if not hasattr(self, "min_val") or not hasattr(self, "max_val"): + self.min_val = min_val + self.max_val = max_val + else: + assert self.min_val.shape == min_val.shape, ( + f"Can't update existing min_val - shape mismatch, self.min_val:{self.min_val.shape} != min_val:{min_val.shape}" + ) + assert self.max_val.shape == max_val.shape, ( + f"Can't update existing max_val - shape mismatch, self.max_val {self.max_val.shape} != max_val:{max_val.shape}" + ) + min_val = self.min_val + self.averaging_constant * (min_val - self.min_val) + max_val = self.max_val + self.averaging_constant * (max_val - self.max_val) + self.min_val.copy_(min_val) + self.max_val.copy_(max_val) + + # returning original input + return input + + def calculate_qparams(self) -> tuple[torch.Tensor, torch.Tensor]: + assert hasattr(self, "min_val") and hasattr(self, "max_val"), ( + "Expecting the observer has min_val and max_val, please run the observer before calling calculate_qparams" + ) + + return choose_qparams_affine_with_min_max( + self.min_val, + self.max_val, + self.mapping_type, + [], # BlockSize is not needed because the min/max are already reduced + self.target_dtype, + self.quant_min, + self.quant_max, + self.eps, + self.scale_dtype, + self.zero_point_dtype, + self.preserve_zero, + self.zero_point_domain, + ) + + +class AffineQuantizedPlaceholderObserver(AffineQuantizedObserverBase): + def __init__( + self, + mapping_type: MappingType, + target_dtype: torch.dtype, + granularity: Granularity, + quant_min: Optional[int] = None, + quant_max: Optional[int] = None, + eps: Optional[float] = None, + is_dynamic=False, + scale_dtype: Optional[torch.dtype] = None, + zero_point_dtype: Optional[torch.dtype] = None, + preserve_zero: bool = True, + zero_point_domain: Optional[ZeroPointDomain] = ZeroPointDomain.INT, + # there could be some extra args that's ignored + **kwargs, + ): + self.is_dynamic = is_dynamic + + super().__init__( + mapping_type=mapping_type, + target_dtype=target_dtype, + granularity=granularity, + quant_min=quant_min, + quant_max=quant_max, + eps=eps, + scale_dtype=scale_dtype, + zero_point_dtype=zero_point_dtype, + preserve_zero=preserve_zero, + zero_point_domain=zero_point_domain, + ) + + def forward(self, input): + self.block_size = get_block_size(input.shape, self.granularity) + self.original_dtype = input.dtype + return input + + def calculate_qparams(self): + raise Exception( # noqa: TRY002 + "calculate_qparams should not be called for PlaceholderObserver" + ) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/_numeric_debugger.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/_numeric_debugger.py new file mode 100644 index 0000000000000000000000000000000000000000..03469813914b5776d81d04e540af0cea46011e0c --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/_numeric_debugger.py @@ -0,0 +1,421 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +import copy +import logging +from collections.abc import Sequence +from dataclasses import dataclass +from typing import Callable, Optional + +import torch +from torch.ao.ns.fx.utils import compute_sqnr +from torch.export import ExportedProgram +from torch.fx import GraphModule, Node +from torch.nn import functional as F + +from torchao.utils import TORCH_VERSION_AT_LEAST_2_6 + +if TORCH_VERSION_AT_LEAST_2_6: + from torch.fx.traceback import NodeSource + +from .graph_utils import bfs_trace_with_node_process + +NUMERIC_DEBUG_HANDLE_KEY = "numeric_debug_handle" +CUSTOM_KEY = "custom" +FROM_NODE_KEY = "from_node" + +log = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class NodeSourceDebugInfo: + """ + Contains node source information for locating the node in the original graph. + This replaces the numeric debug handle approach with direct node source info. + """ + + # The name of the node in the graph, e.g. "conv2d" + name: str + + # The unique id of the graph that the node belongs to. + graph_id: int + + +# This function is no longer used for torchao debug flow, but is kept here for backward compatibility. +def generate_numeric_debug_handle(ep: ExportedProgram) -> None: + """ + Attach numeric_debug_handle_id for all nodes in the graph module of the given + ExportedProgram, like conv2d, squeeze, conv1d, etc, except for placeholder. + Notice that nodes like getattr are out of scope since they are not in the graph. + + The graph nodes of input exported program are modified inplace. + + Here's an example of using debug handle quantize flow:: + + ep = export_for_training(eager_model, example_inputs) + generate_numeric_debug_handle(ep) + + m = ep.module() + quantizer = XNNPACKQuantizer() + m = prepare_pt2e(m, quantizer) + m = convert_pt2e(m) + """ + + # Sanity check the input data type + if not isinstance(ep, ExportedProgram): + raise ValueError( + f"Expected ep to be ExportedProgram, got {type(ExportedProgram)}" + ) + + unique_id = 0 + + def _find_max_id(node: torch.fx.Node) -> None: + nonlocal unique_id + unique_id = max( + unique_id, node.meta.get(CUSTOM_KEY, {}).get(NUMERIC_DEBUG_HANDLE_KEY, 0) + ) + + def _assign_debug_handle(node: torch.fx.Node) -> None: + nonlocal unique_id + if CUSTOM_KEY not in node.meta: + node.meta[CUSTOM_KEY] = {} + + if NUMERIC_DEBUG_HANDLE_KEY not in node.meta[CUSTOM_KEY]: + node.meta[CUSTOM_KEY][NUMERIC_DEBUG_HANDLE_KEY] = unique_id + unique_id += 1 + + # Find the max ID that exists in the graph first, in case part of the graph + # has already been annotated. This way we guarantee there are no duplicate + # handle IDs. + bfs_trace_with_node_process(ep, _find_max_id) + + unique_id += 1 + + # Assign debug handles to all nodes in the graph that don't have one based on the + # max ID found in the previous step. + bfs_trace_with_node_process(ep, _assign_debug_handle) + + +def _extract_node_source_debug_info(node: Node) -> Optional[NodeSourceDebugInfo]: + """ + Extract node source debug info from a node, or return None if the node + does not need to be traced. + + Returns NodeSourceDebugInfo containing the name and graph_id from the + node's greatest ancestor node source, or None if the node is not in + the original graph. + """ + + def _get_greatest_ancestor_node_source(node: Node) -> "NodeSource": + node_source = node.meta.get(FROM_NODE_KEY)[-1] + + while len(node_source.from_node) > 0: + node_source = node_source.from_node[-1] + + return node_source + + def _is_node_in_original_graph(node: Node) -> bool: + if ( + FROM_NODE_KEY not in node.meta + or node.meta[FROM_NODE_KEY] is None + or node.meta[FROM_NODE_KEY][-1].pass_name + == "ExportedProgram.module().unlift()" + ): + # This node is not part of the ExportedProgram.module().graph, so it doesn't have a debug handle + return False + + return True + + if node.op == "placeholder" or node.op == "output": + # placeholder and output nodes don't have debug info + return None + + if not _is_node_in_original_graph(node): + return None + + greatest_ancestor_node_source = _get_greatest_ancestor_node_source(node) + + return NodeSourceDebugInfo( + name=greatest_ancestor_node_source.name, + graph_id=greatest_ancestor_node_source.graph_id, + ) + + +def _detach(x: object) -> object: + detached: object = None + if isinstance(x, torch.Tensor): + detached = x.detach() + elif isinstance(x, (list, tuple)): + detached = type(x)([_detach(e) for e in x]) + elif isinstance(x, dict): + detached = {k: _detach(e) for k, e in x.items()} + else: + detached = x + return detached + + +def _tensor_shape_equals(x: object, y: object) -> bool: + if isinstance(x, torch.Tensor) and isinstance(y, torch.Tensor): + return x.shape == y.shape + elif isinstance(x, (list, tuple)) and isinstance(y, (list, tuple)): + return all(_tensor_shape_equals(e1, e2) for e1, e2 in zip(x, y)) + elif isinstance(x, dict) and isinstance(y, dict): + all_equal = True + for k in x: + all_equal = all_equal and k in y and (_tensor_shape_equals(x[k], y[k])) + return all_equal + else: + log.debug("Comparing non Tensors: %s and %s, they must be equal", x, y) + return type(x) == type(y) and x == y + + +def _loss_fn( + loss: Callable[[torch.Tensor, torch.Tensor], torch.Tensor], x: object, y: object +) -> object: + """The returned loss will have the same structure as `x` and `y`, e.g. + if both are Tensor, we'll return a Tensor + if both are list, we'll return a list of Tensors + if both are dict, we'll return a dict with the same key, and value being the loss between the + two Tensors + """ + if isinstance(x, torch.Tensor) and isinstance(y, torch.Tensor): + return loss(x.to(torch.float32), y.to(torch.float32)) + elif isinstance(x, (list, tuple)) and isinstance(y, (list, tuple)): + return type(x)([_loss_fn(loss, e1, e2) for e1, e2 in zip(x, y)]) + elif isinstance(x, dict) and isinstance(y, dict): + return {k: _loss_fn(loss, e, y[k]) for k, e in x.items()} + else: + return None + + +class OutputLogger(torch.nn.Module): + """ + Base class for capturing output values for nodes in a GraphModule, it only captures + Tensor output currently, but we can extend it to work for other types of inputs later if needed + """ + + # Mark as impure so that calls to it will not be removed during DCE. + _is_impure = True + + def __init__( + self, + debug_info: NodeSourceDebugInfo, + node_name: Optional[str] = None, + nn_module_stack: Optional[object] = None, + ) -> None: + super().__init__() + self.node_name = node_name + self.nn_module_stack = nn_module_stack + self.debug_info = debug_info + self.stats: list[object] = [] + + def forward(self, x: object) -> object: + self.stats.append(_detach(x)) + return x + + def __extra_repr__(self) -> str: + return ( + f"debug_info={self.debug_info}, node_name={self.node_name}, " + "nn_module_stack={self.nn_module_stack}, num_stats={len(self.stats)})" + ) + + +def _insert_logger( + model: GraphModule, node: Node, debug_info: NodeSourceDebugInfo +) -> Node: + """For a given node, adds an OutputLogger that observes the output of that node, + and all its users use the OutputLogger output instead. + The OutputLogger will contain the debug_info which can be used to compare + graphs after transforms""" + + # to avoid circular dep + from torchao.quantization.pt2e.utils import get_new_attr_name_with_prefix + + # add a logger after the node + with model.graph.inserting_after(node): + get_new_attr_name = get_new_attr_name_with_prefix(f"{node.name}_logger") + logger_name = get_new_attr_name(model) + setattr( + model, + logger_name, + OutputLogger(debug_info, node.name, node.meta.get("nn_module_stack")), + ) + logger_node = model.graph.call_module(logger_name, (node,), {}) + + orig_users = list(node.users.keys()) + for user_node in orig_users: + if user_node is logger_node: + continue + user_node.replace_input_with(node, logger_node) + + return logger_node + + +def prepare_for_propagation_comparison(model: GraphModule) -> GraphModule: + """Add output loggers to unlifted node + + Args: + model (GraphModule): original model + Returns: + a model with output loggers for all unlifted nodes + """ + if not TORCH_VERSION_AT_LEAST_2_6: + log.warning( + "prepare_for_propagation_comparison is only supported for PyTorch 2.6+" + ) + return model + + # don't change the original model + model = copy.deepcopy(model) + for n in model.graph.nodes: + if (debug_info := _extract_node_source_debug_info(n)) is not None: + _insert_logger(model, n, debug_info) + + model.recompile() + return model + + +@dataclass(frozen=True) +class QuantizationComparisonResult: + actual: torch.Tensor + ref: torch.Tensor + + @property + def mse_loss(self) -> object: + return self.loss(F.mse_loss) + + @property + def sqnr(self) -> object: + return self.loss(compute_sqnr) + + def loss( + self, loss_function: Callable[[torch.Tensor, torch.Tensor], torch.Tensor] + ) -> object: + return _loss_fn(loss_function, self.actual, self.ref) + + def __repr__(self) -> str: + # Don't include the tensors themselves as they are quite large to print + # out. + return ( + f"QuantizationComparisonResult(mse_loss={self.mse_loss}, sqnr={self.sqnr})" + ) + + def __post_init__(self) -> None: + if not isinstance(self.actual, (torch.Tensor, list, tuple, dict)): + raise ValueError( + f"`self.actual` value must be a Tensor, list, tuple or dict, got: {self.actual}" + ) + + if not isinstance(self.ref, (torch.Tensor, list, tuple, dict)): + raise ValueError( + f"`self.ref` value must be a Tensor, list, tuple or dict, got: {self.ref}" + ) + + if not _tensor_shape_equals(self.ref, self.actual): + raise ValueError( + f"Cannot compare tensors with different shapes: ref={self.ref} vs actual={self.actual}" + ) + + +@dataclass(frozen=True) +class NodeAccuracySummary: + debug_info: NodeSourceDebugInfo + actual_node_name: str + actual_module_stack: str + ref_node_name: str + ref_module_stack: str + results: Sequence[QuantizationComparisonResult] + + +def _module_stack_to_str(module_stack: object) -> str: + """Simplifies the stack from ("mod", "mod.foo", "mod.foo.0", "mod.foo.0.linear") + to "mod.foo.0.linear" + """ + if not isinstance(module_stack, dict): + return str(module_stack) + module_values_list = list(module_stack.values()) + if len(module_values_list) > 0: + owning_module = module_values_list[-1][0] + return str(owning_module) + else: + return str(module_stack) + + +def extract_results_from_loggers( + model: GraphModule, +) -> dict[NodeSourceDebugInfo, tuple[Optional[str], object, list[object]]]: + """For a given model, extract the tensors stats and related information for each debug info. + The reason we have a list of object, instead of Tensor is because the output of node may not be + a Tensor, it could be (nested) list, tuple or dict as well. + + Returns: + A dict is keyed by the NodeSourceDebugInfo and the values are a list of object recorded + in loggers + + """ + # Results maps debug info to a tensor list for each model being compared. + handles: dict[NodeSourceDebugInfo, tuple[Optional[str], object, list[object]]] = {} + for _, module in model.named_children(): + if isinstance(module, OutputLogger) and len(module.stats) > 0: + handles[module.debug_info] = ( + module.node_name, + module.nn_module_stack, + module.stats, + ) + + return handles + + +def compare_results( + ref_results: dict[ + NodeSourceDebugInfo, tuple[Optional[str], object, list[torch.Tensor]] + ], + actual_results: dict[ + NodeSourceDebugInfo, tuple[Optional[str], object, list[torch.Tensor]] + ], +) -> dict[NodeSourceDebugInfo, NodeAccuracySummary]: + """Given two dict mapping from `NodeSourceDebugInfo` to list of tensors + return a map from `NodeSourceDebugInfo` to `NodeAccuracySummary` that contains + comparison information like SQNR, MSE etc. + + Args: + ref_results (Dict[NodeSourceDebugInfo, Tuple[str, object, List[torch.Tensor]]]): reference results for each debug info + actual_results (Dict[NodeSourceDebugInfo, Tuple[str, object, List[torch.Tensor]]]): actual results for each debug info + + Returns: + Dict[NodeSourceDebugInfo, NodeAccuracySummary] + """ + comparisons = {} + for debug_info, (ref_name, ref_stack, ref_stats) in ref_results.items(): + if debug_info not in actual_results: + log.debug( + "Cannot compare for debug info %s because it wasn't found in the transformed model", + debug_info, + ) + continue + actual_name, actual_stack, actual_stats = actual_results[debug_info] + try: + results = [ + QuantizationComparisonResult(actual=a, ref=b) + for a, b in zip(actual_stats, ref_stats) + ] + except Exception as e: + # Add extra information for an exception from QuantizationComparisonResult + # if the shapes didn't match, to include the debug info and the node names. + raise ValueError( + f"For debug_info={debug_info} from ref node {ref_name} and actual node {actual_name}" + ) from e + + comparisons[debug_info] = NodeAccuracySummary( + debug_info=debug_info, + actual_node_name=actual_name or "", + actual_module_stack=_module_stack_to_str(actual_stack), + ref_node_name=ref_name or "", + ref_module_stack=_module_stack_to_str(ref_stack), + results=results, + ) + + return comparisons diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/inductor_passes/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/inductor_passes/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/inductor_passes/x86.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/inductor_passes/x86.py new file mode 100644 index 0000000000000000000000000000000000000000..4ccb2a1f316fb85bc849131d59b57907fff28b27 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/inductor_passes/x86.py @@ -0,0 +1,2852 @@ +# mypy: allow-untyped-decorators +# mypy: allow-untyped-defs +import copy +import functools +import itertools +from typing import Any + +import torch +from torch._dynamo.utils import counters +from torch._inductor.fx_passes.freezing_patterns import register_freezing_graph_pattern +from torch._inductor.pattern_matcher import ( + Arg, + CallFunction, + KeywordArg, + Match, + filter_nodes, +) +from torch.fx.experimental.symbolic_shapes import has_free_symbols +from torch.fx.node import map_arg + +aten = torch.ops.aten +prims = torch.ops.prims +quantized_decomposed = torch.ops.quantized_decomposed +quantized = torch.ops.quantized + +# Only for per tensor quant since permute may changes the channel idx +_PER_TENSOR_QUANTIZE_OPS = [ + quantized_decomposed.quantize_per_tensor.default, + quantized_decomposed.quantize_per_tensor.tensor, +] + +_VIEW_OPS = [ + aten.transpose.int, + aten.permute.default, + aten.view.default, +] + +""" +The quantization.py file primarily incorporates passes related to quantization fusion +in inductor, includes: +1. Dequant Promotion; +2. Conv/GEMM weight prepack with oneDNN Library; +3. Conv/GEMM quantization fusion with output quant node (if have); +4. Other pointwise operators' quantization fusion like: qmaxpool2d, qcat and more; + +It also involves int8-mixed-fp32 and int8-mixed-bf16 quantization. The main difference +of patterns for int8-mixed-bf16, comparing with int8-mixed-fp32, is +1. There is to(dtype=torch.bfloat16) node at the inputs of activation and weight for Conv/GEMM. +2. There is to(dtype=torch.float32) node at the outputs of Conv/GEMM before inputs to next quant node. +Refer to: https://github.com/pytorch/pytorch/issues/111640 for detail design of int8-mixed-bf16 +quantization. +""" + + +def _get_pattern_output_dtype(match: Match): + """ + Get the pattern's output dtype from node's meta + Assume only 1 output node in this matched pattern. + """ + pattern_output_nodes = match.output_nodes() + assert len(pattern_output_nodes) == 1 + output_node = pattern_output_nodes[0] + assert isinstance(output_node, torch.fx.Node) + output_dtype = output_node.meta["val"].dtype + assert output_dtype in [torch.int8, torch.uint8, torch.float32, torch.bfloat16] + return output_dtype + + +def _may_generate_pattern_with_dtype_convert( + pattern, dtype=Arg(), with_dtype_convert=True, users=1 +): + if with_dtype_convert: + return CallFunction( + prims.convert_element_type.default, + pattern, + dtype, + _users=users, + ) + else: + return pattern + + +def _may_generate_pattern_with_reshape(pattern, reshape_size=Arg(), with_reshape=True): + if with_reshape: + return CallFunction( + torch.ops.aten.reshape.default, + pattern, + reshape_size, + ) + else: + return pattern + + +def _generate_linear_t_pattern( + _dequant_per_channel_pattern, + dtype, +): + assert dtype in [torch.float32, torch.bfloat16] + t_pattern = CallFunction( + aten.permute.default, + _may_generate_pattern_with_dtype_convert( + _dequant_per_channel_pattern, + KeywordArg("autocast_wgt_dtype"), + dtype == torch.bfloat16, + ), + KeywordArg("permute_axes"), + ) + return t_pattern + + +def _unary_fusion_pattern(unary_fusion, call_fn, users, is_bf16): + # only insert to_dtype if is_bf16 is True + computation_call = _may_generate_pattern_with_dtype_convert( + call_fn, dtype=KeywordArg("to_float"), with_dtype_convert=is_bf16, users=users + ) + return unary_fusion(computation_call) + + +def get_dequantize_per_tensor_activation_pattern(is_tensor_overload=False): + dequantize_per_tensor_activation_pattern = CallFunction( + quantized_decomposed.dequantize_per_tensor.tensor + if is_tensor_overload + else quantized_decomposed.dequantize_per_tensor.default, + KeywordArg("x"), + KeywordArg("x_scale"), + KeywordArg("x_zp"), + KeywordArg("x_quant_min"), + KeywordArg("x_quant_max"), + KeywordArg("x_dq_dtype"), + ) + return dequantize_per_tensor_activation_pattern + + +dequantize_per_channel_weight_pattern = CallFunction( + quantized_decomposed.dequantize_per_channel.default, + KeywordArg("q_weight"), + KeywordArg("w_scale"), + KeywordArg("w_zp"), + KeywordArg("w_axis"), + KeywordArg("w_quant_min"), + KeywordArg("w_quant_max"), + KeywordArg("w_dtype"), +) + +dequantize_per_channel_to_bf16_weight_pattern = ( + _may_generate_pattern_with_dtype_convert( + dequantize_per_channel_weight_pattern, + KeywordArg("autocast_wgt_dtype"), + ) +) + +dequantize_per_channel_clone_weight_pattern = CallFunction( + aten.clone.default, + dequantize_per_channel_weight_pattern, + memory_format=KeywordArg("memory_format"), +) + +dequantize_per_channel_to_bf16_clone_weight_pattern = CallFunction( + aten.clone.default, + dequantize_per_channel_to_bf16_weight_pattern, + memory_format=KeywordArg("memory_format"), +) + + +def get_qconv_pt2e_pattern(users=1): + return CallFunction( + torch.ops.onednn.qconv_pointwise.default, + KeywordArg("x"), + KeywordArg("x_scale"), + KeywordArg("x_zp"), + KeywordArg("packed_weight"), + KeywordArg("w_scale"), + KeywordArg("w_zp"), + KeywordArg("b"), + KeywordArg("stride"), + KeywordArg("padding"), + KeywordArg("dilation"), + KeywordArg("groups"), + KeywordArg("output_scale"), + KeywordArg("output_zero_point"), + KeywordArg("output_dtype"), + KeywordArg("postop_name"), + KeywordArg("postop_args"), + KeywordArg("postop_algorithm"), + _users=users, + ) + + +def get_qconv2d_binary_pt2e_pattern(users=1): + return CallFunction( + torch.ops.onednn.qconv2d_pointwise.binary, + KeywordArg("x"), + KeywordArg("x_scale"), + KeywordArg("x_zp"), + KeywordArg("packed_weight"), + KeywordArg("w_scale"), + KeywordArg("w_zp"), + KeywordArg("accum"), + KeywordArg("b"), + KeywordArg("stride"), + KeywordArg("padding"), + KeywordArg("dilation"), + KeywordArg("groups"), + KeywordArg("output_scale"), + KeywordArg("output_zero_point"), + KeywordArg("output_dtype"), + KeywordArg("accum_scale"), + KeywordArg("accum_zero_point"), + KeywordArg("binary_op_name"), + KeywordArg("alpha"), + KeywordArg("unary_op_name"), + KeywordArg("unary_op_args"), + KeywordArg("unary_op_algorithm"), + _users=users, + ) + + +def get_qlinear_pt2e_pattern(x_scale_zp_are_tensors, users=1): + qlinear_op = ( + torch.ops.onednn.qlinear_pointwise.tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qlinear_pointwise.default + ) + return CallFunction( + qlinear_op, + KeywordArg("x"), + KeywordArg("x_scale"), + KeywordArg("x_zp"), + KeywordArg("packed_weight"), + KeywordArg("w_scale"), + KeywordArg("w_zp"), + KeywordArg("b"), + KeywordArg("output_scale"), + KeywordArg("output_zero_point"), + KeywordArg("output_dtype"), + KeywordArg("postop_name"), + KeywordArg("postop_args"), + KeywordArg("postop_algorithm"), + _users=users, + ) + + +def get_qlinear_binary_pt2e_pattern(x_scale_zp_are_tensors, users=1): + qlinear_op = ( + torch.ops.onednn.qlinear_pointwise.binary_tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qlinear_pointwise.binary + ) + return CallFunction( + qlinear_op, + KeywordArg("x"), + KeywordArg("x_scale"), + KeywordArg("x_zp"), + KeywordArg("packed_weight"), + KeywordArg("w_scale"), + KeywordArg("w_zp"), + KeywordArg("x_2"), + KeywordArg("b"), + KeywordArg("output_scale"), + KeywordArg("output_zero_point"), + KeywordArg("output_dtype"), + KeywordArg("x2_scale"), + KeywordArg("x2_zp"), + KeywordArg("binary_op_name"), + KeywordArg("alpha"), + KeywordArg("unary_op_name"), + KeywordArg("unary_op_args"), + KeywordArg("unary_op_algorithm"), + _users=users, + ) + + +dequantize_accum_pattern = CallFunction( + quantized_decomposed.dequantize_per_tensor.default, + KeywordArg("accum"), + KeywordArg("accum_scale"), + KeywordArg("accum_zp"), + Arg(), + Arg(), + KeywordArg("accum_dq_dtype"), +) + + +def generate_pattern_with_binary( + binary_post_op, + computation_call, + extra_input_pattern, + dtype_convert=False, + swap_inputs=False, +): + binary_pattern = ( + CallFunction( + binary_post_op, + extra_input_pattern, + computation_call, + ) + if swap_inputs + else CallFunction( + binary_post_op, + computation_call, + extra_input_pattern, + ) + ) + return _may_generate_pattern_with_dtype_convert( + binary_pattern, + KeywordArg("convert_dtype_after_inplace_add"), + dtype_convert, + ) + + +def generate_pattern_with_unary(computation_call, unary_post_op): + if unary_post_op is not None: + return CallFunction( + unary_post_op, + computation_call, + ) + return computation_call + + +def generate_pattern_with_output_quant(computation_call, with_dtype_convert=False): + quantized_op_output_pattern_pt2e = CallFunction( + quantized_decomposed.quantize_per_tensor.default, + _may_generate_pattern_with_dtype_convert( + computation_call, + Arg(), + with_dtype_convert, + ), + KeywordArg("o_inv_scale"), + KeywordArg("o_zp"), + KeywordArg("o_qmin"), + KeywordArg("o_qmax"), + KeywordArg("o_dtype"), + ) + return quantized_op_output_pattern_pt2e + + +def _check_node_kwarg_arg_value(check_node, kwarg_name, args_index, expected_value): + if kwarg_name in check_node.kwargs: + actual_value = check_node.kwargs[kwarg_name] + return actual_value == expected_value + else: + assert len(check_node.args) >= (args_index + 1) + actual_value = check_node.args[args_index] + return actual_value == expected_value + + +def _is_valid_quantized_conv_optimization_pattern(): + def fn(match): + output_dtype = _get_pattern_output_dtype(match) + if output_dtype in [torch.float32, torch.bfloat16]: + # Only keep matched pattern with same output_dtype + qconv_node_after_weight_prepack = filter_nodes( + match.nodes, torch.ops.onednn.qconv_pointwise + )[0] + return _check_node_kwarg_arg_value( + qconv_node_after_weight_prepack, "output_dtype", 13, output_dtype + ) + return True + + return fn + + +def _is_valid_qconv_post_op_fusion_pattern(has_binary_post_op=False): + return ( + _is_valid_qconv_binary_optimization_pattern() + if has_binary_post_op + else _is_valid_quantized_conv_optimization_pattern() + ) + + +def _is_valid_quantized_linear_optimization_pattern(): + def fn(match): + output_dtype = _get_pattern_output_dtype(match) + if output_dtype in [torch.float32, torch.bfloat16]: + # Only keep matched pattern with same output_dtype + qlinear_node_after_weight_prepack = filter_nodes( + match.nodes, torch.ops.onednn.qlinear_pointwise + )[0] + return _check_node_kwarg_arg_value( + qlinear_node_after_weight_prepack, "output_dtype", 9, output_dtype + ) + return True + + return fn + + +def _is_valid_qlinear_post_op_fusion_pattern(has_binary_post_op=False): + return ( + _is_valid_qlinear_binary_optimization_pattern() + if has_binary_post_op + else _is_valid_quantized_linear_optimization_pattern() + ) + + +def _is_valid_qconv_binary_optimization_pattern(): + return _is_valid_quantized_op_binary_optimization_pattern( + torch.ops.onednn.qconv_pointwise + ) + + +def _is_valid_qlinear_binary_optimization_pattern(): + return _is_valid_quantized_op_binary_optimization_pattern( + torch.ops.onednn.qlinear_pointwise, + # we don't insert q-dq for extra input due to accuracy issues + extra_input_from_dequant=False, + ) + + +def _is_valid_quantized_op_binary_optimization_pattern( + qop, extra_input_from_dequant=True +): + # Check if it's a valid Binary Pattern for qconv2d and qlinear: + # * qop_pointwise should only has one users + # * If extra_input_from_dequant is True, extra input of binary node should come from dequant pattern + # * the two inputs of binary node should have attribute "meta" and should be tensors + # * the two inputs of binary node should have the same shape + # * All users of the extra input in this pattern should be + # ancestor nodes of the compute node, except for the binary node + # connected to the compute node. + def fn(match): + output_dtype = _get_pattern_output_dtype(match) + compute_node = filter_nodes(match.nodes, qop)[0] + # qop_pointwise should only have one user + if len(compute_node.users) != 1: + return False + binary_node_inputs = next(iter(compute_node.users)).args + assert len(binary_node_inputs) == 2, "Expects binary node with 2 inputs" + if output_dtype in [torch.float32, torch.bfloat16]: + extra_input_of_binary_node = None + for arg in binary_node_inputs: + if arg != compute_node: + extra_input_of_binary_node = arg + break + assert extra_input_of_binary_node is not None + # Extra input of binary node comes from dequant pattern + if extra_input_from_dequant and ( + (not isinstance(extra_input_of_binary_node, torch.fx.Node)) + or ( + extra_input_of_binary_node.target + != quantized_decomposed.dequantize_per_tensor.default + ) + ): + return False + + # the two inputs of binary node should have attribute "meta" and should be tensors + if not ( + hasattr(binary_node_inputs[0], "meta") + and isinstance(binary_node_inputs[0].meta.get("val", None), torch.Tensor) # type: ignore[union-attr] + ) or not ( + hasattr(binary_node_inputs[1], "meta") + and isinstance(binary_node_inputs[1].meta.get("val", None), torch.Tensor) # type: ignore[union-attr] + ): + return False + # the two inputs of binary node should have the same shape + if ( + binary_node_inputs[0].meta["val"].size() # type: ignore[union-attr] + != binary_node_inputs[1].meta["val"].size() # type: ignore[union-attr] + ): + return False + + # All users of the extra input in this pattern should be + # ancestor nodes of the compute node, except for the binary node + # connected to the compute node. + + from torch._inductor.fx_passes.mkldnn_fusion import _get_remaining_users + + extra_input_of_pattern = ( + match.kwargs["other"] + if "other" in match.kwargs + else ( + match.kwargs["accum"] + if (output_dtype in [torch.uint8, torch.int8]) + or (not extra_input_from_dequant) + else match.kwargs["accum_after_dequant"] + ) + ) + if ( + len(_get_remaining_users(extra_input_of_pattern, compute_node)) > 1 + or extra_input_of_pattern == compute_node.args[0] + ): + return False + return True + + return fn + + +def _is_valid_dequant_promotion_pattern(dtype=torch.float32): + def _inner(match): + assert dtype in [torch.float32, torch.bfloat16] + dequant_pattern_end_node = match.output_node() + if dequant_pattern_end_node.target not in [ + quantized_decomposed.dequantize_per_tensor.default, + quantized_decomposed.dequantize_per_tensor.tensor, + prims.convert_element_type.default, + aten.reshape.default, + ]: + return False + + if dequant_pattern_end_node.target is aten.reshape.default: + dequant_node = ( + dequant_pattern_end_node.args[ + 0 + ] # pattern: linear <- reshape <- dequant + if dtype == torch.float32 + else dequant_pattern_end_node.args[0].args[ + 0 + ] # pattern: linear <- reshape <- to_bf16 <- dequant + ) + else: + dequant_node = ( + dequant_pattern_end_node # pattern: linear <- dequant + if dtype == torch.float32 + else dequant_pattern_end_node.args[ + 0 + ] # pattern: linear <- to_bf16 <- dequant + ) + + if ( + dequant_node.target + in [ + quantized_decomposed.dequantize_per_tensor.default, + quantized_decomposed.dequantize_per_tensor.tensor, + ] + and len(list(dequant_pattern_end_node.users)) > 1 + ): + # If dequant pattern has more than 1 users, then do dequant promoted + return True + return False + + return _inner + + +def _register_dequant_promotion_pass(pattern, pass_number, dtype=torch.float32): + @register_freezing_graph_pattern( + pattern, + extra_check=_is_valid_dequant_promotion_pattern(dtype), + pass_number=pass_number, + ) + def dequant_promotion(match: Match, *args, **kwargs): + # Dequant_promotion will transform + # graph 1: + # quant + # + - - - | - - - + + # | dequant | + # | / \ | + # | node1 node2 | + # + - | - - - | - + + # quant quant + # into: + # graph 2: + # quant + # + - - / - \ - - + + # |dequant dequant| + # | | | | + # | node1 node2 | + # + - | - - - | - + + # quant quant + # In graph 1, the dequant node is shared by node1 and node2, + # as a result, neither node1 nor node2 could form an int8 + # fusion pattern. + # After this transformation, the graph 2 could hit the int8 + # fusion pattern: dequant-node-quant, respectively for + # node1 and node2. + assert dtype in [torch.float32, torch.bfloat16] + + def clone_to_new_node(graph, source_node, user_node): + # Clone the source_node to a new node + # Replace user_node's input from source_node to new_node + assert source_node.op == "call_function", ( + "clone_to_new_node only support node.op call_function" + ) + with graph.inserting_before(user_node): + new_node = graph.call_function( + source_node.target, + args=source_node.args, + kwargs=source_node.kwargs, + ) + new_node.meta = copy.copy(source_node.meta) + user_node.replace_input_with(source_node, new_node) + return new_node + + # Find the start node and end node of a dequant pattern + # * End node should be the match.output_node() + # * Start node should be the node of dequantize_per_tensor + dequant_pattern_end_node = match.output_node() + assert dequant_pattern_end_node.target in [ + quantized_decomposed.dequantize_per_tensor.default, + quantized_decomposed.dequantize_per_tensor.tensor, + prims.convert_element_type.default, + aten.reshape.default, + ] + + # For a dequant pattern, we should expect see the node list as: + # * OPT(aten.reshape.default) + # * OPT(prims.convert_element_type.default) (to_bf16) + # * dequantize_per_tensor + def _find_first_node_in_dequant_pattern(_node): + if _node.target in [ + quantized_decomposed.dequantize_per_tensor.default, + quantized_decomposed.dequantize_per_tensor.tensor, + ]: + # For a dequant pattern, we expect the start node is a dequantize_per_tensor node + return _node + else: + assert len(_node.args) >= 1, ( + "In in dequant pattern, each node should have more than 1 arg." + ) + return _find_first_node_in_dequant_pattern(_node.args[0]) + + dequant_pattern_start_node = _find_first_node_in_dequant_pattern( + dequant_pattern_end_node + ) + + assert dequant_pattern_start_node.target in [ + quantized_decomposed.dequantize_per_tensor.default, + quantized_decomposed.dequantize_per_tensor.tensor, + ] + + # Clone the dequant pattern for each user node + graph = match.graph + user_node_list = list(dequant_pattern_end_node.users) + for user_node in user_node_list[1:]: + _source_node = dequant_pattern_end_node + _user_node = user_node + while _source_node != dequant_pattern_start_node.args[0]: + _user_node = clone_to_new_node(graph, _source_node, _user_node) + _source_node = _source_node.args[0] # type: ignore[assignment] + + counters["inductor"]["dequant_promotion_matcher_count"] += 1 + counters["inductor"]["dequant_promotion_matcher_nodes"] += len(match.nodes) + + +def _is_valid_dequant_conv_pattern(dtype): + def _inner(match): + # Here we do some further check to ensure: + # 1. It's a conv2d node with dim of 4, since we only support lowering of conv2d now. + # 2. The dequant pattern has only 1 user of conv2d node. + # If these conditions don't meet, we will not + # insert weight prepack node into the matched pattern. + conv_node = match.output_node() + assert conv_node.target is aten.convolution.default + input_meta_value = conv_node.args[0].meta.get("val") + weight_meta_value = conv_node.args[1].meta.get("val") + for meta_value in [input_meta_value, weight_meta_value]: + if ( + meta_value is None + or (meta_value.device.type != "cpu" and meta_value.device.type != "xpu") + or meta_value.dim() not in [3, 4] + ): + # Only support conv1d/2d now + return False + + assert dtype in [torch.float32, torch.bfloat16] + + if dtype == torch.float32: + dequant_node = conv_node.args[0] + else: + convert_to_bf16 = conv_node.args[0] + dequant_node = convert_to_bf16.args[0] + + if len(list(dequant_node.users)) != 1: + # Ensure the dequant pattern only has 1 user + # since we will delete the dequant pattern here + return False + return True + + return _inner + + +def _register_qconv_weight_prepack_pass(pattern, pass_number, dtype=torch.float32): + @register_freezing_graph_pattern( + pattern, + extra_check=_is_valid_dequant_conv_pattern(dtype), + pass_number=pass_number, + ) + def qconv_weight_prepack(match: Match, *args, **kwargs): + """ + Match the pattern: + int8 activation + | + dequant_per_tensor + | + Conv2d <- optional(aten.clone.default) <- dequant_per_channel <- int8_weight + + Insert weight prepack node and change the pattern to: + int8 activation + | + onednn.qconv_pointwise <- onednn.qconv_prepack <- int8_weight + """ + assert dtype in [torch.float32, torch.bfloat16] + conv_node = match.output_node() + assert conv_node.target is aten.convolution.default + if dtype == torch.float32: + dequant_node = conv_node.args[0] + else: + convert_to_bf16 = conv_node.args[0] + dequant_node = convert_to_bf16.args[0] # type: ignore[union-attr] + has_clone_to_channel_last_node_in_pattern = ( + conv_node.args[1].target is aten.clone.default # type: ignore[union-attr] + ) + clone_node = ( + conv_node.args[1] if has_clone_to_channel_last_node_in_pattern else None + ) + + if dtype == torch.float32: + dequant_per_channel = ( + clone_node.args[0] # type: ignore[union-attr] + if has_clone_to_channel_last_node_in_pattern + else conv_node.args[1] + ) + else: + weight_to_bf16_node = ( + clone_node.args[0] # type: ignore[union-attr] + if has_clone_to_channel_last_node_in_pattern + else conv_node.args[1] + ) + dequant_per_channel = weight_to_bf16_node.args[0] # type: ignore[union-attr] + + assert ( + dequant_per_channel.target # type: ignore[union-attr] + is quantized_decomposed.dequantize_per_channel.default + ) + + # Activation QParams + qx, x_zp, x_scale = ( + kwargs["x"], + kwargs["x_zp"], + kwargs["x_scale"], + ) + + # Weight QParams + qw, w_scale, w_zp = ( + kwargs["q_weight"], + kwargs["w_scale"], + kwargs["w_zp"], + ) + + # Conv Params + bias, stride, padding, dilation, groups = ( + kwargs["b"], + kwargs["stride"], + kwargs["padding"], + kwargs["dilation"], + kwargs["groups"], + ) + + x_shape = qx.meta.get("tensor_meta").shape + if has_free_symbols(x_shape): + # For dynamic shape case, we can't get activation shape ahead of runtime. + x_shape = None + graph = match.graph + with graph.inserting_before(conv_node): + # Insert weight prepack node and the QConv node + packed_weight_inputs = ( + qw, + w_scale, + x_scale, + x_zp, + stride, + padding, + dilation, + groups, + x_shape, + ) + packed_weight_op = torch.ops.onednn.qconv_prepack + prepack_weight_node = graph.call_function( + packed_weight_op, args=packed_weight_inputs + ) + + new_args: tuple[Any, ...] = ( + qx, + x_scale, + x_zp, + prepack_weight_node, + w_scale, + w_zp, + bias, + stride, + padding, + dilation, + groups, + 1.0, # output_scale + 0, # output_zero_point + dtype, # output_dtype + "none", # attr + [], # scalars + "", # algorithm + ) + new_conv_node = graph.call_function( + torch.ops.onednn.qconv_pointwise.default, args=new_args + ) + conv_node.replace_all_uses_with(new_conv_node) + new_conv_node.meta.update(conv_node.meta) + + # Erase the original conv node + graph.erase_node(conv_node) + # Erase the dequant pattern + if dtype == torch.bfloat16: + graph.erase_node(convert_to_bf16) # type: ignore[possibly-undefined, arg-type] + graph.erase_node(dequant_node) # type: ignore[arg-type] + # Erase the dequant per channel pattern + if clone_node is not None: + graph.erase_node(clone_node) # type: ignore[arg-type] + if dtype == torch.bfloat16: + graph.erase_node(weight_to_bf16_node) # type: ignore[possibly-undefined, arg-type] + graph.erase_node(dequant_per_channel) # type: ignore[arg-type] + counters["inductor"]["qconv_weight_prepack_matcher_count"] += 1 + counters["inductor"]["qconv_weight_prepack_matcher_nodes"] += len( + match.nodes + ) + + +def _generate_dequant_convolution_node_pattern( + _dequant_per_channel_pattern, dtype=torch.float32 +): + assert dtype in [torch.float32, torch.bfloat16] + dequant_convolution_node_pattern = CallFunction( + aten.convolution.default, + _may_generate_pattern_with_dtype_convert( + get_dequantize_per_tensor_activation_pattern(), + KeywordArg("autocast_act_dtype"), + dtype == torch.bfloat16, + ), + _dequant_per_channel_pattern, + KeywordArg("b"), + KeywordArg("stride"), + KeywordArg("padding"), + KeywordArg("dilation"), + KeywordArg("is_transposed"), + KeywordArg("out_padding"), + KeywordArg("groups"), + ) + return dequant_convolution_node_pattern + + +def _generate_qconv_weight_prepack_patterns(dtype=torch.float32): + assert dtype in [torch.float32, torch.bfloat16] + return ( + _generate_dequant_convolution_node_pattern( + dequantize_per_channel_weight_pattern + if dtype == torch.float32 + else dequantize_per_channel_to_bf16_weight_pattern, + dtype, + ), + # There is another pattern due to the pass of convert_conv_weights_to_channels_last + # https://github.com/pytorch/pytorch/blob/07107919297db3f8ab37f11c12666b6d6d5f692e/torch/_inductor/freezing.py#L338-L362. + # Depend on some heuristics, it may or may not insert to(channel_last) node + # between convolution and dequant_per_channel node + _generate_dequant_convolution_node_pattern( + dequantize_per_channel_clone_weight_pattern + if dtype == torch.float32 + else dequantize_per_channel_to_bf16_clone_weight_pattern, + dtype, + ), + ) + + +def _get_linear_node(match, input_dim_exceeds_two, input_contiguous): + output_reshape_node = None + if input_dim_exceeds_two: + if input_contiguous: + output_reshape_node = match.output_node() + assert output_reshape_node.target is aten.reshape.default + linear_node = output_reshape_node.args[0] + else: + linear_nodes = filter_nodes(match.nodes, aten.bmm.default) + assert len(linear_nodes) == 1 + linear_node = linear_nodes[0] + else: + linear_node = match.output_node() + + assert linear_node.target in ( + aten.addmm.default, + aten.mm.default, + aten.bmm.default, + ) + return linear_node, output_reshape_node + + +def _get_linear_dq_node( + linear_node, input_index, dtype, input_dim_exceeds_two, input_contiguous +): + act_reshape_node = None + activation_to_bf16_node = None + act_expand_node = None + if input_dim_exceeds_two: + if input_contiguous: + act_reshape_node = linear_node.args[input_index] + assert act_reshape_node.target is aten.reshape.default + if dtype == torch.float32: + # pattern: linear -> reshape -> dequant + dequant_node = act_reshape_node.args[0] + else: + # pattern: linear -> reshape -> to_bf16 -> dequant + activation_to_bf16_node = act_reshape_node.args[0] + dequant_node = activation_to_bf16_node.args[0] + else: + # bmm pattern decomposed from linear when input dim exceeds 2 and not contiguous + act_expand_node = linear_node.args[input_index] + assert act_expand_node.target is aten.expand.default + if dtype == torch.float32: + dequant_node = act_expand_node.args[0] + else: + activation_to_bf16_node = act_expand_node.args[0] + dequant_node = activation_to_bf16_node.args[0] + else: + if dtype == torch.float32: + # pattern: linear -> dequant + dequant_node = linear_node.args[input_index] + else: + # pattern: linear -> to_bf16 -> dequant + activation_to_bf16_node = linear_node.args[input_index] + dequant_node = activation_to_bf16_node.args[0] + return dequant_node, act_reshape_node, activation_to_bf16_node, act_expand_node + + +def _is_valid_dequant_linear_pattern(dtype, input_dim_exceeds_two, input_contiguous): + def _inner(match): + # Check dequant pattern has only 1 user. + ( + linear_node, + _, + ) = _get_linear_node(match, input_dim_exceeds_two, input_contiguous) + + input_index = 1 if linear_node.target is aten.addmm.default else 0 + assert dtype in [torch.float32, torch.bfloat16] + ( + dequant_node, + _, + _, + _, + ) = _get_linear_dq_node( + linear_node, input_index, dtype, input_dim_exceeds_two, input_contiguous + ) + + assert dequant_node.target in [ + quantized_decomposed.dequantize_per_tensor.default, + quantized_decomposed.dequantize_per_tensor.tensor, + ] + + if len(list(dequant_node.users)) != 1: + # Ensure the dequant pattern only has 1 user + # since we will delete the dequant pattern here + return False + + # Extra check for bmm pattern + if input_dim_exceeds_two and not input_contiguous: + # Check for act + # Act expand size should be exactly same as act size + act_expand_size = match.kwargs["act_expand_size"] + act_node = match.kwargs["x"] + if not ( + hasattr(act_node, "meta") + and isinstance(act_node.meta.get("val", None), torch.Tensor) + and (act_node.meta["val"].size() == torch.Size(act_expand_size)) + ): + return False + + # Check for wgt + # wgt permute dims should be [1, 0] + wgt_permute_dims = match.kwargs["permute_axes"] + if wgt_permute_dims != [1, 0]: + return False + + # Check below wgt size items: + # wgt before expand should with dim 2 + # Expand size should with dim 3 + # Expand size[0] should same as act size[0] + # Expand size[1] should same as wgt size[1] + # Expand size[2] should same as wgt size[0] + qweight_node = match.kwargs["q_weight"] + wgt_expand_size = match.kwargs["wgt_expand_size"] + if not ( + hasattr(qweight_node, "meta") + and isinstance(qweight_node.meta.get("val", None), torch.Tensor) + and len(qweight_node.meta["val"].size()) == 2 + and len(wgt_expand_size) == 3 + and wgt_expand_size[0] == act_node.meta["val"].size()[0] + and wgt_expand_size[1] == qweight_node.meta["val"].size()[1] + and wgt_expand_size[2] == qweight_node.meta["val"].size()[0] + ): + return False + + return True + + return _inner + + +def _register_qlinear_weight_prepack_pass( + pattern, + pass_number, + dtype=torch.float32, + input_dim_exceeds_two=False, + input_contiguous=True, +): + @register_freezing_graph_pattern( + pattern, + extra_check=_is_valid_dequant_linear_pattern( + dtype, input_dim_exceeds_two, input_contiguous + ), + pass_number=pass_number, + ) + def qlinear_weight_prepack(match: Match, *args, **kwargs): + """ + Match the pattern: + int8 activation + | + dequant_per_tensor + | + mm/addmm <- t <- dequant_per_channel <- int8_weight + + Insert weight prepack node and change the pattern to: + int8 activation + | + onednn.qlinear_pointwise <- onednn.qlinear_prepack <- int8_weight + """ + assert dtype in [torch.float32, torch.bfloat16] + ( + linear_node, + output_reshape_node, + ) = _get_linear_node(match, input_dim_exceeds_two, input_contiguous) + input_index = 1 if linear_node.target is aten.addmm.default else 0 + weight_index = input_index + 1 + + ( + dequant_node, + act_reshape_node, + activation_to_bf16_node, + act_expand_node, + ) = _get_linear_dq_node( + linear_node, input_index, dtype, input_dim_exceeds_two, input_contiguous + ) + + if input_dim_exceeds_two and not input_contiguous: + wgt_expand_node = linear_node.args[weight_index] + assert wgt_expand_node.target is aten.expand.default + t_node = wgt_expand_node.args[0] + else: + t_node = linear_node.args[weight_index] + + if dtype == torch.float32: + dequant_per_channel = t_node.args[0] + else: + weight_to_bf16_node = t_node.args[0] + dequant_per_channel = weight_to_bf16_node.args[0] + assert ( + dequant_per_channel.target + is quantized_decomposed.dequantize_per_channel.default + ) + + # Activation QParams + qx, x_zp, x_scale = ( + kwargs["x"], + kwargs["x_zp"], + kwargs["x_scale"], + ) + + # Weight QParams + qw, w_scale, w_zp = ( + kwargs["q_weight"], + kwargs["w_scale"], + kwargs["w_zp"], + ) + + # Params + bias = kwargs["b"] if "b" in kwargs else None + + x_shape = qx.meta.get("tensor_meta").shape + if has_free_symbols(x_shape): + # For dynamic shape case, we can't get activation shape ahead of runtime. + x_shape = None + graph = match.graph + with graph.inserting_before(linear_node): + # Insert weight prepack node and the qlinear node + packed_weight_inputs = ( + qw, + x_shape, + ) + packed_weight_op = torch.ops.onednn.qlinear_prepack + prepack_weight_node = graph.call_function( + packed_weight_op, args=packed_weight_inputs + ) + + new_args: tuple[Any, ...] = ( + qx, + x_scale, + x_zp, + prepack_weight_node, + w_scale, + w_zp, + bias, + 1.0, # output_scale + 0, # output_zero_point + dtype, # output_dtype + "none", # post op name + [], # post op args + "", # post op algorithm + ) + Node = torch.fx.node.Node + if isinstance(x_scale, Node) and isinstance(x_zp, Node): + new_linear_node = graph.call_function( + torch.ops.onednn.qlinear_pointwise.tensor, args=new_args + ) + else: + new_linear_node = graph.call_function( + torch.ops.onednn.qlinear_pointwise.default, args=new_args + ) + if input_dim_exceeds_two: + if input_contiguous: + output_reshape_node.replace_all_uses_with(new_linear_node) + new_linear_node.meta.update(output_reshape_node.meta) + else: + if bias: + output_add_node_for_bias = match.output_node() + assert output_add_node_for_bias.target is aten.add.Tensor + output_add_node_for_bias.replace_all_uses_with(new_linear_node) + new_linear_node.meta.update(output_add_node_for_bias.meta) + else: + linear_node.replace_all_uses_with(new_linear_node) + new_linear_node.meta.update(linear_node.meta) + else: + linear_node.replace_all_uses_with(new_linear_node) + new_linear_node.meta.update(linear_node.meta) + + # Erase the original linear node + if input_dim_exceeds_two: + if input_contiguous: + graph.erase_node(output_reshape_node) + elif not input_contiguous and bias: + graph.erase_node(output_add_node_for_bias) # type: ignore[possibly-undefined] + graph.erase_node(linear_node) + if input_dim_exceeds_two: + if input_contiguous: + graph.erase_node(act_reshape_node) + else: + graph.erase_node(act_expand_node) + graph.erase_node(wgt_expand_node) # type: ignore[possibly-undefined] + if dtype == torch.bfloat16: + graph.erase_node(activation_to_bf16_node) + # Erase the dequant pattern + graph.erase_node(dequant_node) + # Erase the dequant per channel pattern + graph.erase_node(t_node) + if dtype == torch.bfloat16: + graph.erase_node(weight_to_bf16_node) # type: ignore[possibly-undefined] + graph.erase_node(dequant_per_channel) + + counters["inductor"]["qlinear_weight_prepack_matcher_count"] += 1 + counters["inductor"]["qlinear_weight_prepack_matcher_nodes"] += len( + match.nodes + ) + + +def _generate_dequant_linear_node_pattern( + _dequant_per_channel_pattern, + dtype=torch.float32, + input_dim_exceeds_two=False, + is_tensor_overload=False, +): + assert dtype in [torch.float32, torch.bfloat16] + t_pattern = _generate_linear_t_pattern(_dequant_per_channel_pattern, dtype) + dequant_linear_bias_pattern = _may_generate_pattern_with_reshape( + CallFunction( + aten.addmm.default, + KeywordArg("b"), + _may_generate_pattern_with_reshape( + _may_generate_pattern_with_dtype_convert( + get_dequantize_per_tensor_activation_pattern(is_tensor_overload), + KeywordArg("autocast_act_dtype"), + dtype == torch.bfloat16, + ), + KeywordArg("act_reshape_size"), + input_dim_exceeds_two, + ), + t_pattern, + ), + KeywordArg("output_reshape_size"), + input_dim_exceeds_two, + ) + dequant_linear_no_bias_pattern = _may_generate_pattern_with_reshape( + CallFunction( + aten.mm.default, + _may_generate_pattern_with_reshape( + _may_generate_pattern_with_dtype_convert( + get_dequantize_per_tensor_activation_pattern(is_tensor_overload), + KeywordArg("autocast_act_dtype"), + dtype == torch.bfloat16, + ), + KeywordArg("act_reshape_size"), + input_dim_exceeds_two, + ), + t_pattern, + ), + KeywordArg("output_reshape_size"), + input_dim_exceeds_two, + ) + return dequant_linear_bias_pattern, dequant_linear_no_bias_pattern + + +def _generate_dequant_bmm_node_pattern( + _dequant_per_channel_pattern, + dtype=torch.float32, + with_bias=False, + is_tensor_overload=False, +): + # When activation of linear dim exceed 2 and not contiguous + t_pattern = _generate_linear_t_pattern(_dequant_per_channel_pattern, dtype) + + assert dtype in [torch.float32, torch.bfloat16] + dequant_bmm_pattern = CallFunction( + aten.bmm.default, + CallFunction( + aten.expand.default, + _may_generate_pattern_with_dtype_convert( + get_dequantize_per_tensor_activation_pattern(is_tensor_overload), + KeywordArg("autocast_act_dtype"), + dtype == torch.bfloat16, + ), + KeywordArg("act_expand_size"), + ), + CallFunction( + aten.expand.default, + t_pattern, + KeywordArg("wgt_expand_size"), + ), + ) + + def _generate_pattern_with_output_add(_dequant_bmm_pattern, _with_bias): + if _with_bias: + return CallFunction( + aten.add.Tensor, + _dequant_bmm_pattern, + KeywordArg("b"), + ) + else: + return _dequant_bmm_pattern + + return _generate_pattern_with_output_add(dequant_bmm_pattern, with_bias) + + +def _generate_qlinear_weight_prepack_patterns( + dtype=torch.float32, + input_dim_exceeds_two=False, + input_contiguous=True, + with_bias=False, + is_tensor_overload=False, +): + if input_dim_exceeds_two and not input_contiguous: + return _generate_dequant_bmm_node_pattern( + dequantize_per_channel_weight_pattern, + dtype, + with_bias, + is_tensor_overload, + ) + else: + return _generate_dequant_linear_node_pattern( + dequantize_per_channel_weight_pattern, + dtype, + input_dim_exceeds_two, + is_tensor_overload, + ) + + +def _generate_linear_dynamic_fp16_pattern( + _dequant_weight_pattern, + input_dim_exceeds_two=False, + input_contiguous=True, + relu_fused=False, +): + dtype = torch.float32 + t_pattern = _generate_linear_t_pattern(_dequant_weight_pattern, dtype) + + if input_dim_exceeds_two and not input_contiguous: + # pattern is + # x -> expand -> bmm (-> add) (-> relu) + # w -> dequant -> permute -> expand / + pattern_no_bias = CallFunction( + aten.bmm.default, + CallFunction( + aten.expand.default, + KeywordArg("x"), + KeywordArg("act_expand_size"), + ), + CallFunction( + aten.expand.default, + t_pattern, + KeywordArg("wgt_expand_size"), + ), + ) + pattern_with_bias = CallFunction( + aten.add.Tensor, + pattern_no_bias, + KeywordArg("b"), + ) + if relu_fused: + pattern_with_bias = CallFunction(aten.relu.default, pattern_with_bias) + pattern_no_bias = CallFunction(aten.relu.default, pattern_no_bias) + return pattern_with_bias, pattern_no_bias + + x_pattern_with_reshape = _may_generate_pattern_with_reshape( + KeywordArg("x"), + KeywordArg("act_reshape_size"), + input_dim_exceeds_two, + ) + dequant_linear_bias_pattern = generate_pattern_with_unary( + _may_generate_pattern_with_reshape( + CallFunction( + aten.addmm.default, + KeywordArg("b"), + x_pattern_with_reshape, + t_pattern, + ), + KeywordArg("output_reshape_size"), + input_dim_exceeds_two, + ), + aten.relu.default if relu_fused else None, + ) + dequant_linear_no_bias_pattern = generate_pattern_with_unary( + _may_generate_pattern_with_reshape( + CallFunction( + aten.mm.default, + x_pattern_with_reshape, + t_pattern, + ), + KeywordArg("output_reshape_size"), + input_dim_exceeds_two, + ), + aten.relu.default if relu_fused else None, + ) + return dequant_linear_bias_pattern, dequant_linear_no_bias_pattern + + +def _register_dequant_promotion(): + dequant_pattern_cases = itertools.product( + [torch.float32, torch.bfloat16], [True, False], [True, False] + ) + for dtype, input_dim_exceeds_two, is_tensor_overload in dequant_pattern_cases: + # 4 dequantization patterns will be matched based on the dtype and input dimension size. + # Case 1: int8-mixed-fp32, input dim size is 2 + # Case 2: int8-mixed-fp32, input dim size exceeds 2 + # Case 3: int8-mixed-bf16, input dim size is 2 + # Case 4: int8-mixed-bf16, input dim size exceeds 2 + # quant + # + - - - - | - - - - + + # | dequant | + # | | | + # | OPT(to_bf16) | + # | | | + # | OPT(reshape) | + # | / \ | + # | node1 node2 | + # + - - | - - - | - - + + # OPT(reshape) OPT(reshape) + # + - - | - - - | - - + + # OPT(to_fp32) OPT(to_fp32) + # + - - | - - - | - - + + # quant quant + _register_dequant_promotion_pass( + _may_generate_pattern_with_reshape( + _may_generate_pattern_with_dtype_convert( + get_dequantize_per_tensor_activation_pattern( + is_tensor_overload=is_tensor_overload + ), + KeywordArg("autocast_act_dtype"), + dtype == torch.bfloat16, + ), + KeywordArg("act_reshape_size"), + with_reshape=input_dim_exceeds_two, + ), + pass_number=0, + dtype=dtype, + ) # pass_number=0 to run before weight prepack + + +def _register_qconv_weight_prepack(): + for dtype in [torch.float32, torch.bfloat16]: + weight_prepack_patterns = _generate_qconv_weight_prepack_patterns(dtype) + for weight_prepack_pattern in weight_prepack_patterns: + # Register to pass_number 1, so we can do dequant promotion in pass_number 0. + _register_qconv_weight_prepack_pass( + weight_prepack_pattern, pass_number=1, dtype=dtype + ) + + +def _register_qlinear_weight_prepack(): + # 6 Linear related patterns will be matched based on the dtype, input dimension size and input contiguous. + # Then convert the pattern into a QLinear node with int8_fp32/bf16. + # Case 1: int8-mixed-fp32, input dim size is 2 + # Case 2: int8-mixed-fp32, input dim size exceeds 2 and contiguous + # Case 3: int8-mixed-bf16, input dim size is 2 + # Case 4: int8-mixed-bf16, input dim size exceeds 2 and contiguous + + # + - - - - | - - - - - - | - - - - - + + # | dq_per_tensor dq_per_channel | + # | | | | + # | OPT(to_bf16) OPT(to_bf16) | + # | | | | + # | OPT(reshape) permute | + # | \ / | + # | addmm/mm | + # | | | + # | OPT(reshape) | + + # Case 5: int8-mixed-fp32, input dim size exceeds 2 and not contiguous + # Case 6: int8-mixed-bf16, input dim size exceeds 2 and not contiguous + + # + - - - - | - - - - - - | - - - - - + + # | dq_per_tensor dq_per_channel | + # | | | | + # | OPT(to_bf16) OPT(to_bf16) | + # | | | | + # | expand permute | + # | \ | | + # | expand | + # | / | + # | bmm | + # | | | + # | OPT(add) | + + linear_weight_prepack_cases = itertools.product( + [torch.float32, torch.bfloat16], [True, False], [True, False] + ) + + # Step 1: register patterns from mm and addmm + for dtype, input_dim_exceeds_two, is_tensor_overload in linear_weight_prepack_cases: + weight_prepack_patterns = _generate_qlinear_weight_prepack_patterns( + dtype, + input_dim_exceeds_two, + is_tensor_overload=is_tensor_overload, + ) + for weight_prepack_pattern in weight_prepack_patterns: + # Register to pass_number 1, so we can do dequant promotion in pass_number 0. + _register_qlinear_weight_prepack_pass( + weight_prepack_pattern, + pass_number=1, + dtype=dtype, + input_dim_exceeds_two=input_dim_exceeds_two, + ) + + # Step 2: register patterns from bmm + # Linear might be decomposed into bmm when input dim exceeds 2 and not contiguous + # refer to: + # https://github.com/pytorch/pytorch/blob/ + # 80c07df659362a95da7cd4f3ec367abfdace38c4/torch/_decomp/decompositions.py#L3965-L3968 + # in this case, we can convert it back to qlinear + for dtype, with_bias, is_tensor_overload in itertools.product( + [torch.float32, torch.bfloat16], [True, False], [True, False] + ): + bmm_pattern = _generate_qlinear_weight_prepack_patterns( + dtype=dtype, + input_dim_exceeds_two=True, + input_contiguous=False, + with_bias=with_bias, + is_tensor_overload=is_tensor_overload, + ) + _register_qlinear_weight_prepack_pass( + bmm_pattern, + pass_number=1 + if with_bias + else 2, # if with_bias, there is an output add, so we should try to match it firstly + dtype=dtype, + input_dim_exceeds_two=True, + input_contiguous=False, + ) + + +def _register_linear_dynamic_fp16_weight_prepack_pass( + pattern, + pass_number, + input_dim_exceeds_two=False, + input_contiguous=True, + relu_fused=False, +): + def _extra_check_fn(match: Match): + return match.kwargs["dtype_fp16"] == torch.float16 + + @register_freezing_graph_pattern( + pattern, + extra_check=_extra_check_fn, + pass_number=pass_number, + ) + def linear_dynamic_fp16_weight_prepack(match: Match, *args, **kwargs): + """ + Match the pattern: + fp32 activation + | + mm/addmm <- t <- to_fp32 <- to_fp16 <- weight + | + (reshape) <- (relu) + + OR + + fp32 activation + | + expand + | + bmm <- expand <- t <- to_fp32 <- to_fp16 <- weight + | + (add) <- (relu) + + Insert weight prepack node and change the pattern to: + fp32 activation + | + onednn.linear_dynamic_fp16 <- onednn.linear_prepack_fp16 <- weight + (or onednn.linear_relu_dynamic_fp16) + """ + # find params + x = kwargs["x"] + w = kwargs["w"] + bias = kwargs["b"] if "b" in kwargs else None + + # find linear node + nodes_to_find = [aten.addmm.default, aten.mm.default, aten.bmm.default] + linear_nodes = [] + for node in nodes_to_find: + linear_nodes.extend(filter_nodes(match.nodes, node)) + assert len(linear_nodes) == 1 + linear_node = linear_nodes[0] + assert isinstance(linear_node, torch.fx.node.Node) + input_index = 1 if linear_node.target is aten.addmm.default else 0 + weight_index = input_index + 1 + + # find relu node + relu_node = None + if relu_fused: + relu_node = match.output_node() + assert isinstance(relu_node, torch.fx.node.Node) + + # find reshape node, expand node and add node + ( + act_reshape_node, + output_reshape_node, + expand_x_node, + expand_w_node, + add_bias_node, + ) = (None, None, None, None, None) + t_node = None + if input_dim_exceeds_two: + if input_contiguous: + act_reshape_node = linear_node.args[input_index] + t_node = linear_node.args[weight_index] + output_reshape_node = next(iter(linear_node.users)) + assert output_reshape_node.target is aten.reshape.default + else: + expand_x_node = linear_node.args[input_index] + expand_w_node = linear_node.args[weight_index] + assert isinstance(expand_w_node, torch.fx.node.Node) + t_node = expand_w_node.args[0] + if bias: + add_bias_node = next(iter(linear_node.users)) + assert add_bias_node.target is aten.add.Tensor + else: + t_node = linear_node.args[weight_index] + assert isinstance(t_node, torch.fx.node.Node) + + w_to_fp32_node = t_node.args[0] + assert ( + isinstance(w_to_fp32_node, torch.fx.node.Node) + and w_to_fp32_node.target + is quantized_decomposed.convert_element_type.no_fuse + ) + w_to_fp16_node = w_to_fp32_node.args[0] + assert ( + isinstance(w_to_fp16_node, torch.fx.node.Node) + and w_to_fp16_node.target + is quantized_decomposed.convert_element_type.no_fuse + ) + + x_shape = x.meta.get("tensor_meta").shape + if has_free_symbols(x_shape): + # For dynamic shape case, we can't get activation shape ahead of runtime. + x_shape = None + graph = match.graph + with graph.inserting_before(linear_node): + # Insert weight prepack node and the qlinear node + packed_weight_inputs = ( + w, + x_shape, + ) + packed_weight_op = torch.ops.onednn.linear_prepack_fp16 + prepack_weight_node = graph.call_function( + packed_weight_op, args=packed_weight_inputs + ) + + # create new linear node and insert on graph + new_args: tuple[Any, ...] = ( + x, + prepack_weight_node, + bias, + ) + linear_op = ( + torch.ops.onednn.linear_relu_dynamic_fp16.default + if relu_fused + else torch.ops.onednn.linear_dynamic_fp16.default + ) + new_linear_node = graph.call_function(linear_op, args=new_args) + out_node = match.output_node() + out_node.replace_all_uses_with(new_linear_node) + + # Erase the original nodes in the reverse order + new_linear_node.meta.update(out_node.meta) + if relu_node is not None: + graph.erase_node(relu_node) + if output_reshape_node is not None: + graph.erase_node(output_reshape_node) + if add_bias_node is not None: + graph.erase_node(add_bias_node) + graph.erase_node(linear_node) + if act_reshape_node is not None: + assert isinstance(act_reshape_node, torch.fx.node.Node) + graph.erase_node(act_reshape_node) + if expand_x_node is not None: + assert isinstance(expand_x_node, torch.fx.node.Node) + graph.erase_node(expand_x_node) + if expand_w_node is not None: + assert isinstance(expand_w_node, torch.fx.node.Node) + graph.erase_node(expand_w_node) + graph.erase_node(t_node) + graph.erase_node(w_to_fp32_node) + graph.erase_node(w_to_fp16_node) + + counters["inductor"]["qlinear_weight_prepack_matcher_count"] += 1 + counters["inductor"]["qlinear_weight_prepack_matcher_nodes"] += len( + match.nodes + ) + + +def _register_linear_dynamic_fp16_weight_prepack(): + to_dtype_op = torch.ops.quantized_decomposed.convert_element_type.no_fuse + weight_pattern = CallFunction( + to_dtype_op, + CallFunction( + to_dtype_op, + KeywordArg("w"), + KeywordArg("dtype_fp16"), + ), + KeywordArg("dtype_fp32"), + ) + cases = itertools.product( + [False, True], # input_dim_exceeds_two + [True, False], # input_contiguous + [False, True], # relu fused + ) + for input_dim_exceeds_two, input_contiguous, relu_fused in cases: + patterns = _generate_linear_dynamic_fp16_pattern( + weight_pattern, + input_dim_exceeds_two, + input_contiguous, + relu_fused, + ) + for pattern in patterns: + _register_linear_dynamic_fp16_weight_prepack_pass( + pattern, + pass_number=0 if relu_fused else 1, + input_dim_exceeds_two=input_dim_exceeds_two, + input_contiguous=input_contiguous, + relu_fused=relu_fused, + ) + + +def _register_smooth_quant_int_mm_pattern(): + """ + The pattern is: + (no bias) reshape -> _int_mm -> convert_element_type -> (expand ->) mul -> mul -> reshape + or + (with bias) pattern_no_bias -> add (-> reshape -> reshape) + """ + + # When torch.compile'ing with dynamic=True, the expand node and the two tailing reshape nodes exist + # When torch.compile'ing with dynamic=False, they don't exist + def get_pattern_no_bias(expand_a_scale: bool, reshape_a: bool = True): + return CallFunction( + aten.mul.Tensor, + CallFunction( + aten.mul.Tensor, + CallFunction( + prims.convert_element_type.default, + CallFunction( + aten._int_mm.default, + CallFunction( + aten.reshape.default, + KeywordArg("a"), + KeywordArg("in_shape"), + ) + if reshape_a + else KeywordArg("a"), + KeywordArg("b"), + ), + KeywordArg("dtype"), + ), + ( + CallFunction( + aten.expand.default, + KeywordArg("x_scale"), + Arg(), + ) + if expand_a_scale + else KeywordArg("x_scale") + ), + ), + KeywordArg("w_scale"), + ) + + def _with_outer_reshape(pattern): + return CallFunction( + aten.reshape.default, pattern, KeywordArg("out_shape_no_bias") + ) + + # for torch.compile(dynamic=False) + pattern_no_bias_1 = _with_outer_reshape(get_pattern_no_bias(expand_a_scale=False)) + pattern_with_bias_1 = CallFunction( + aten.add.Tensor, + pattern_no_bias_1, + KeywordArg("bias"), + ) + # for torch.compile(dynamic=True) + pattern_no_bias_2 = _with_outer_reshape(get_pattern_no_bias(expand_a_scale=True)) + pattern_with_bias_2 = CallFunction( + aten.reshape.default, + CallFunction( + aten.reshape.default, + CallFunction( + aten.add.Tensor, + pattern_no_bias_2, + KeywordArg("bias"), + ), + Arg(), + ), + KeywordArg("out_shape_with_bias"), + ) + + # The following patterns are for torchao int8_dynamic_activation_int8_weight linear, + # when both activation and weights are symmetrically quantized. + # In practice, though, they may also match smooth-quant pattern when a 2D input shape would be used. + # Since add is not currently being used as a oneDNN post-op, but is unfused, we don't need these patterns with bias. + # Ideally, we should add mul + add post-op support in ATen int8 oneDNN linear op. + pattern1_with_no_outer_or_act_reshape = get_pattern_no_bias( + expand_a_scale=False, reshape_a=False + ) + pattern2_with_no_outer_or_act_reshape = get_pattern_no_bias( + expand_a_scale=True, reshape_a=False + ) + + def _validate_pattern(match: Match): + if len(match.nodes) not in [4, 5, 6, 7, 10]: + return False + # Make sure weight is a constant + aten_int_mm_node = filter_nodes(match.nodes, aten._int_mm.default)[0] + if not isinstance(aten_int_mm_node.args[1], torch.fx.node.Node): + return False + if aten_int_mm_node.args[1].op != "get_attr": + return False + + if len(match.nodes) == 10: + # Check the two tailing reshape nodes can be fused + if match.nodes[9].args[1] != match.nodes[6].args[1]: + return False + if len(match.nodes) == 10 or ( + len(match.nodes) == 7 and match.nodes[6].target is aten.add.Tensor + ): + bias_idx = 7 if len(match.nodes) == 10 else 6 + # Check bias shape + bias_node = match.nodes[bias_idx].args[1] + if not isinstance(bias_node, torch.fx.node.Node): + return False + if len(bias_node.meta.get("tensor_meta").shape) != 1: # type: ignore[union-attr] + return False + return True + + pattern_to_pass_number = { + pattern_no_bias_2: 0, + pattern_with_bias_2: 0, + pattern_no_bias_1: 1, + pattern_with_bias_1: 1, + pattern1_with_no_outer_or_act_reshape: 2, + pattern2_with_no_outer_or_act_reshape: 2, + } + for pattern, pass_number in pattern_to_pass_number.items(): + + @register_freezing_graph_pattern( + pattern, + extra_check=_validate_pattern, + pass_number=pass_number, + ) + def _int_mm_weight_prepack(match: Match, *args, **kwargs): + bias = kwargs.get("bias", None) + x = kwargs["a"] + weight = kwargs["b"] + dtype = kwargs["dtype"] + x_scale = kwargs["x_scale"] + w_scale = kwargs["w_scale"] + x_shape = x.meta.get("tensor_meta").shape + if has_free_symbols(x_shape): + # For dynamic shape case, we can't get activation shape ahead of runtime. + x_shape = None + + out_node = match.output_node() + with match.graph.inserting_before(out_node): + transpose_node = match.graph.call_function( + aten.permute.default, args=(weight, [1, 0]) + ) + contig_node = match.graph.call_function( + aten.contiguous.default, args=(transpose_node,) + ) + packed_weight_inputs = ( + contig_node, + x_shape, + ) + packed_weight_op = torch.ops.onednn.qlinear_prepack + prepack_weight_node = match.graph.call_function( + packed_weight_op, args=packed_weight_inputs + ) + + dummy_zp = None + w_scale = match.graph.call_function( + prims.convert_element_type.default, args=(w_scale, torch.float32) + ) + + x_scale_shape = x_scale.meta.get("tensor_meta").shape + x_scale_is_scalar = False + if not has_free_symbols(x_scale_shape): + prod = 1 + for d in x_scale_shape: + prod *= d + x_scale_is_scalar = prod == 1 + + new_args: tuple[Any, ...] + if x_scale_is_scalar: + # in this case, we can call onednn.qlinear directly + new_args = ( + x, + x_scale, + dummy_zp, # x_zp + prepack_weight_node, + w_scale, + dummy_zp, # w_zp + bias, + 1.0, # output_scale + 0, # output_zero_point + dtype, # output_dtype + "none", # post op name + [], # post op args + "", # post op algorithm + ) + new_linear_node = match.graph.call_function( + torch.ops.onednn.qlinear_pointwise.tensor, args=new_args + ) + out_node.replace_all_uses_with(new_linear_node) + new_linear_node.meta.update(out_node.meta) + else: + # onednn.qlinear does not support per-channel quantization of x + # so in this case, we have to apply x scale and add bias ourselves after qlinear + in_shape = kwargs.get("in_shape", None) + if in_shape is None: + x_reshaped = x + else: + x_reshaped = match.graph.call_function( + aten.reshape.default, args=(x, in_shape) + ) + new_args = ( + x_reshaped, + 1.0, # x_scale + 0, # x_zp + prepack_weight_node, + w_scale, + dummy_zp, # w_zp + None, # bias + 1.0, # output_scale + 0, # output_zero_point + dtype, # output_dtype + "none", # post op name + [], # post op args + "", # post op algorithm + ) + new_linear_node = match.graph.call_function( + torch.ops.onednn.qlinear_pointwise, args=new_args + ) + # apply x scale + new_out_node = match.graph.call_function( + aten.mul.Tensor, args=(new_linear_node, x_scale) + ) + + # Add bias and reshape + has_outer_reshape = ( + kwargs.get("out_shape_with_bias", None) is not None + or kwargs.get("out_shape_no_bias", None) is not None + ) + + if has_outer_reshape: + out_shape = kwargs.get( + "out_shape_with_bias", kwargs["out_shape_no_bias"] + ) + if bias is not None: + new_out_node = match.graph.call_function( + aten.add.Tensor, args=(new_out_node, bias) + ) + if has_outer_reshape: + new_out_node = match.graph.call_function( + aten.reshape.default, + args=(new_out_node, out_shape), # type: ignore[possibly-undefined] + ) + else: + if has_outer_reshape: + new_out_node = match.graph.call_function( + aten.reshape.default, + args=(new_out_node, out_shape), # type: ignore[possibly-undefined] + ) + out_node.replace_all_uses_with(new_out_node) + new_out_node.meta.update(out_node.meta) + for node in reversed(match.nodes): + match.graph.erase_node(node) + counters["inductor"]["qlinear_weight_prepack_matcher_count"] += 1 + counters["inductor"]["qlinear_weight_prepack_matcher_nodes"] += len( + match.nodes + ) + + +class PostOpAttr: + def __init__( + self, + binary_op_name: str = "none", + alpha=None, + unary_op_name: str = "none", + scalars_attr=None, + algorithm_attr=None, + ) -> None: + self.binary_op_name = binary_op_name + self.alpha = alpha if alpha else 1.0 + self.unary_op_name = unary_op_name + self.scalars_attr = scalars_attr if scalars_attr else [] + self.algorithm_attr = algorithm_attr if algorithm_attr else "" + + +def _register_qconv_post_op_fusion_pass( + pattern, + pass_number, + computation_op, + post_op_attr, +): + has_binary_post_op = post_op_attr.binary_op_name != "none" + + @register_freezing_graph_pattern( + pattern, + extra_check=_is_valid_qconv_post_op_fusion_pattern(has_binary_post_op), + pass_number=pass_number, + ) + def qconv(match: Match, *args, **kwargs): + # Activation QParams + x, x_scale, x_zp = ( + kwargs["x"], + kwargs["x_scale"], + kwargs["x_zp"], + ) + # Weight QParams + packed_weight, w_scale, w_zp = ( + kwargs["packed_weight"], + kwargs["w_scale"], + kwargs["w_zp"], + ) + # Conv Params + b, stride, padding, dilation, groups = ( + kwargs["b"], + kwargs["stride"], + kwargs["padding"], + kwargs["dilation"], + kwargs["groups"], + ) + output_dtype = _get_pattern_output_dtype(match) + assert output_dtype in [torch.int8, torch.uint8, torch.float32, torch.bfloat16] + # Output QParams + o_inv_scale = ( + kwargs["o_inv_scale"] + if (output_dtype == torch.uint8 or output_dtype == torch.int8) + else 1.0 + ) + o_zero_point = ( + kwargs["o_zp"] + if (output_dtype == torch.uint8 or output_dtype == torch.int8) + else 0 + ) + assert ( + kwargs["postop_name"] == "none" + ) # Expected no post op fused in weight prepack phase + if post_op_attr.unary_op_name == "hardtanh": + min_value = kwargs.get("min_value") + max_value = kwargs.get("max_value") + post_op_attr.scalars_attr = [min_value, max_value] + + out_node = match.output_node() + with match.graph.inserting_before(out_node): + if not has_binary_post_op: + computation_args: tuple[Any, ...] = ( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + b, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + output_dtype, + post_op_attr.unary_op_name, + post_op_attr.scalars_attr, + post_op_attr.algorithm_attr, + ) + else: + accum = ( + kwargs["accum"] + if output_dtype in [torch.uint8, torch.int8] + else kwargs["accum_after_dequant"] + ) + accum_scale = ( + kwargs["accum_scale"] + if output_dtype in [torch.uint8, torch.int8] + else 1.0 + ) + accum_zp = ( + kwargs["accum_zp"] + if output_dtype in [torch.uint8, torch.int8] + else 0 + ) + computation_args = ( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + accum, + b, + stride, + padding, + dilation, + groups, + o_inv_scale, + o_zero_point, + output_dtype, + accum_scale, + accum_zp, + post_op_attr.binary_op_name, + post_op_attr.alpha, + post_op_attr.unary_op_name, + post_op_attr.scalars_attr, + post_op_attr.algorithm_attr, + ) + new_conv_node = match.graph.call_function( + computation_op, args=computation_args + ) + out_node.replace_all_uses_with(new_conv_node) + new_conv_node.meta.update(out_node.meta) + for node in reversed(match.nodes): + match.graph.erase_node(node) + count_key = ( + "qconv2d_binary_matcher_count" + if has_binary_post_op + else "qconv_unary_matcher_count" + ) + nodes_key = ( + "qconv2d_binary_matcher_nodes" + if has_binary_post_op + else "qconv_unary_matcher_nodes" + ) + counters["inductor"][count_key] += 1 + counters["inductor"][nodes_key] += len(match.nodes) + + return qconv + + +def _register_qconv_unary_fusion(): + from torch._inductor.fx_passes.mkldnn_fusion import ( + _hardswish_fusion, + _hardtanh_fusion, + _silu_fusion, + ) + + for original_pattern_output_dtype in [torch.float32, torch.bfloat16]: + # Priority 1 to match: QConv2d Unary pattern with int8 output + # If a pattern1 is a sub-set of pattern2, we should try to match pattern2 firstly. + # For example: pattern1 is qconv_fp32 -> relu, pattern2 is qconv_fp32 -> relu -> quant + is_bf16 = original_pattern_output_dtype == torch.bfloat16 + conv_unary_replace_patterns = { + PostOpAttr( + "none", None, "none", [], "" + ): generate_pattern_with_output_quant( + get_qconv_pt2e_pattern(1), + ), + PostOpAttr( + "none", None, "relu", [], "" + ): generate_pattern_with_output_quant( + generate_pattern_with_unary( + get_qconv_pt2e_pattern(1), aten.relu.default + ), + ), + PostOpAttr( + "none", None, "hardtanh", [], "" + ): generate_pattern_with_output_quant( + _unary_fusion_pattern( + _hardtanh_fusion, + get_qconv_pt2e_pattern(1), + 1, + is_bf16, + ), + with_dtype_convert=is_bf16, + ), + PostOpAttr( + "none", None, "hardswish", [], "" + ): generate_pattern_with_output_quant( + _unary_fusion_pattern( + _hardswish_fusion, + get_qconv_pt2e_pattern(1 if is_bf16 else 2), + 2, + is_bf16, + ), + with_dtype_convert=is_bf16, + ), + PostOpAttr( + "none", None, "swish", [], "" + ): generate_pattern_with_output_quant( + _unary_fusion_pattern( + _silu_fusion, + get_qconv_pt2e_pattern(1 if is_bf16 else 2), + 2, + is_bf16, + ), + with_dtype_convert=is_bf16, + ), + } + + for unary_attr, patterns in conv_unary_replace_patterns.items(): + # Register qconv2d pattern for ExternKernel Lowering + _register_qconv_post_op_fusion_pass( + patterns, + 3, # pass_number + torch.ops.onednn.qconv_pointwise.default, # computation_op + unary_attr, # unary_attr + ) + + # Priority 2 to match: QConv2d Unary pattern with fp32/bfloat16 output + conv_unary_replace_float_out_patterns = { + PostOpAttr("none", None, "relu", [], ""): generate_pattern_with_unary( + get_qconv_pt2e_pattern(1), aten.relu.default + ), + PostOpAttr( + "none", None, "hardtanh", [], "" + ): _may_generate_pattern_with_dtype_convert( + _unary_fusion_pattern( + _hardtanh_fusion, + get_qconv_pt2e_pattern(1), + 1, + is_bf16, + ), + Arg(), + is_bf16, + ), + PostOpAttr( + "none", None, "hardswish", [], "" + ): _may_generate_pattern_with_dtype_convert( + _unary_fusion_pattern( + _hardswish_fusion, + get_qconv_pt2e_pattern(1 if is_bf16 else 2), + 2, + is_bf16, + ), + Arg(), + is_bf16, + ), + PostOpAttr( + "none", None, "swish", [], "" + ): _may_generate_pattern_with_dtype_convert( + _unary_fusion_pattern( + _silu_fusion, + get_qconv_pt2e_pattern(1 if is_bf16 else 2), + 2, + is_bf16, + ), + Arg(), + is_bf16, + ), + } + + for unary_attr, patterns in conv_unary_replace_float_out_patterns.items(): + # Register qconv2d pattern for ExternKernel Lowering + _register_qconv_post_op_fusion_pass( + patterns, + 4, # pass_number + torch.ops.onednn.qconv_pointwise.default, # computation_op + unary_attr, # unary_attr + ) + + +def _register_qconv_binary_fusion(): + for int8_mixed_bf16_with_inplace_add in [False, True]: + # Priority 1 to match: QConv2d Binary or Binary-Unary pattern with int8 output + swap_binary_inputs_list = [False, True] + binary_replace_patterns = {} + for swap_inputs in swap_binary_inputs_list: + binary_replace_patterns.update( + { + PostOpAttr( + "sum", 1.0, "none", [], "" + ): generate_pattern_with_output_quant( + generate_pattern_with_binary( + aten.add.Tensor, + get_qconv_pt2e_pattern(1), + dequantize_accum_pattern, + int8_mixed_bf16_with_inplace_add, + swap_inputs=swap_inputs, + ), + ), + PostOpAttr( + "sum", 1.0, "relu", [], "" + ): generate_pattern_with_output_quant( + generate_pattern_with_unary( + generate_pattern_with_binary( + aten.add.Tensor, + get_qconv_pt2e_pattern(1), + dequantize_accum_pattern, + int8_mixed_bf16_with_inplace_add, + swap_inputs=swap_inputs, + ), + aten.relu.default, + ), + ), + } + ) + + for binary_unary_attr, patterns in binary_replace_patterns.items(): + _register_qconv_post_op_fusion_pass( + patterns, + 3, # pass_number + torch.ops.onednn.qconv2d_pointwise.binary, # computation_op + binary_unary_attr, # binary_unary_attr + ) + + # Priority 2 to match: QConv2d Binary-Unary pattern with fp32/bfloat16 output + binary_replace_float_out_patterns = {} + for swap_inputs in swap_binary_inputs_list: + binary_replace_float_out_patterns.update( + { + PostOpAttr("sum", 1.0, "relu", [], ""): generate_pattern_with_unary( + generate_pattern_with_binary( + aten.add.Tensor, + get_qconv_pt2e_pattern(1), + KeywordArg("accum_after_dequant"), + int8_mixed_bf16_with_inplace_add, + swap_inputs=swap_inputs, + ), + aten.relu.default, + ) + } + ) + + for ( + binary_unary_attr, + patterns, + ) in binary_replace_float_out_patterns.items(): + if int8_mixed_bf16_with_inplace_add: + _register_qconv_post_op_fusion_pass( + patterns, + 3, # pass_number + torch.ops.onednn.qconv2d_pointwise.binary, # computation_op + binary_unary_attr, # binary_unary_attr + ) + else: + _register_qconv_post_op_fusion_pass( + patterns, + 4, # pass_number + torch.ops.onednn.qconv2d_pointwise.binary, # computation_op + binary_unary_attr, # binary_unary_attr + ) + + # Priority 3: QConv2d Binary pattern with fp32/bfloat16 output + binary_replace_float_out_patterns = {} + for swap_inputs in swap_binary_inputs_list: + binary_replace_float_out_patterns.update( + { + PostOpAttr( + "sum", 1.0, "none", [], "" + ): generate_pattern_with_binary( + aten.add.Tensor, + get_qconv_pt2e_pattern(1), + KeywordArg("accum_after_dequant"), + int8_mixed_bf16_with_inplace_add, + swap_inputs=swap_inputs, + ), + } + ) + + for ( + binary_unary_attr, + patterns, + ) in binary_replace_float_out_patterns.items(): + _register_qconv_post_op_fusion_pass( + patterns, + 4 if int8_mixed_bf16_with_inplace_add else 5, # pass_number + torch.ops.onednn.qconv2d_pointwise.binary, # computation_op + binary_unary_attr, # binary_unary_attr + ) + + +def _register_qlinear_post_op_fusion_pass( + pattern, + pass_number, + computation_op, + post_op_attr, +): + has_binary_post_op = post_op_attr.binary_op_name != "none" + + @register_freezing_graph_pattern( + pattern, + extra_check=_is_valid_qlinear_post_op_fusion_pattern(has_binary_post_op), + pass_number=pass_number, + ) + def qlinear_post_op_fusion(match: Match, *args, **kwargs): + """ + Match the pattern: + qlinear - post op + """ + output_dtype = _get_pattern_output_dtype(match) + # Activation QParams + x, x_scale, x_zp = ( + kwargs["x"], + kwargs["x_scale"], + kwargs["x_zp"], + ) + # Weight QParams + packed_weight, w_scale, w_zp = ( + kwargs["packed_weight"], + kwargs["w_scale"], + kwargs["w_zp"], + ) + + # bias + b = kwargs["b"] if "b" in kwargs else None + + # Output QParams + o_inv_scale = ( + kwargs["o_inv_scale"] + if (output_dtype in [torch.uint8, torch.int8]) + else 1.0 + ) + o_zero_point = ( + kwargs["o_zp"] if (output_dtype in [torch.uint8, torch.int8]) else 0 + ) + assert ( + kwargs["postop_name"] == "none" + ) # Expected no post op fused in weight prepack phase + + out_node = match.output_node() + with match.graph.inserting_before(out_node): + if not has_binary_post_op: + computation_args: tuple[Any, ...] = ( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + b, + o_inv_scale, + o_zero_point, + output_dtype, + post_op_attr.unary_op_name, + post_op_attr.scalars_attr, + post_op_attr.algorithm_attr, + ) + else: + other = kwargs["other"] if "other" in kwargs else kwargs["accum"] + x2_scale = 1.0 + x2_zp = 0 + computation_args = ( + x, + x_scale, + x_zp, + packed_weight, + w_scale, + w_zp, + other, + b, + o_inv_scale, + o_zero_point, + output_dtype, + x2_scale, + x2_zp, + post_op_attr.binary_op_name, + post_op_attr.alpha, + post_op_attr.unary_op_name, + post_op_attr.scalars_attr, + post_op_attr.algorithm_attr, + ) + new_linear_node = match.graph.call_function( + computation_op, args=computation_args + ) + out_node.replace_all_uses_with(new_linear_node) + new_linear_node.meta.update(out_node.meta) + for node in reversed(match.nodes): + match.graph.erase_node(node) + count_key = ( + "qlinear_binary_matcher_count" + if has_binary_post_op + else "qlinear_unary_matcher_count" + ) + nodes_key = ( + "qlinear_binary_matcher_nodes" + if has_binary_post_op + else "qlinear_unary_matcher_nodes" + ) + counters["inductor"][count_key] += 1 + counters["inductor"][nodes_key] += len(match.nodes) + + +def _register_qlinear_unary_fusion(): + from torch._inductor.fx_passes.mkldnn_fusion import ( + _gelu_fusion_1 as _gelu_fusion_erf, + ) + from torch._inductor.fx_passes.mkldnn_fusion import ( + _gelu_fusion_2 as _gelu_fusion_tanh, + ) + + for original_pattern_output_dtype in [torch.float32, torch.bfloat16]: + is_bf16 = original_pattern_output_dtype == torch.bfloat16 + for x_scale_zp_are_tensors in (False, True): + qlinear_pattern = get_qlinear_pt2e_pattern(x_scale_zp_are_tensors) + computation_op = ( + torch.ops.onednn.qlinear_pointwise.tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qlinear_pointwise.default + ) + # Priority 1 to match: QLinear Unary pattern with int8 output + linear_unary_replace_patterns = { + PostOpAttr( + "none", None, "none", [], "" + ): generate_pattern_with_output_quant( + qlinear_pattern, + ), + PostOpAttr( + "none", None, "relu", [], "" + ): generate_pattern_with_output_quant( + generate_pattern_with_unary(qlinear_pattern, aten.relu.default), + ), + PostOpAttr( + "none", None, "gelu", [], "none" + ): generate_pattern_with_output_quant( + _unary_fusion_pattern( + _gelu_fusion_erf, + get_qlinear_pt2e_pattern( + x_scale_zp_are_tensors, 1 if is_bf16 else 2 + ), + 2, + is_bf16, + ), + with_dtype_convert=is_bf16, + ), + PostOpAttr( + "none", None, "gelu", [], "tanh" + ): generate_pattern_with_output_quant( + _unary_fusion_pattern( + _gelu_fusion_tanh, + get_qlinear_pt2e_pattern( + x_scale_zp_are_tensors, 1 if is_bf16 else 4 + ), + 4, + is_bf16, + ), + with_dtype_convert=is_bf16, + ), + } + + for unary_attr, patterns in linear_unary_replace_patterns.items(): + _register_qlinear_post_op_fusion_pass( + patterns, + 3, # pass_number + computation_op, + unary_attr, # unary_attr + ) + + # Priority 2 to match: QLinear Unary pattern with FP32/BF16 output + linear_unary_replace_float_out_patterns = { + PostOpAttr("none", None, "relu", [], ""): generate_pattern_with_unary( + qlinear_pattern, aten.relu.default + ), + PostOpAttr( + "none", None, "gelu", [], "none" + ): _may_generate_pattern_with_dtype_convert( + _unary_fusion_pattern( + _gelu_fusion_erf, + get_qlinear_pt2e_pattern( + x_scale_zp_are_tensors, 1 if is_bf16 else 2 + ), + 2, + is_bf16, + ), + Arg(), + is_bf16, + ), + PostOpAttr( + "none", None, "gelu", [], "tanh" + ): _may_generate_pattern_with_dtype_convert( + _unary_fusion_pattern( + _gelu_fusion_tanh, + get_qlinear_pt2e_pattern( + x_scale_zp_are_tensors, 1 if is_bf16 else 4 + ), + 4, + is_bf16, + ), + Arg(), + is_bf16, + ), + } + + for unary_attr, patterns in linear_unary_replace_float_out_patterns.items(): + _register_qlinear_post_op_fusion_pass( + patterns, + 4, # pass_number + computation_op, + unary_attr, # unary_attr + ) + + +def _register_qlinear_binary_fusion(): + r""" + Supported linear-binary(-unary) patterns + + linear(X) extra input + \ / + Add + | + Optional(relu) + | + Y + + 1. int8-mixed-fp32 + +---+---------------+-----------+------------------------------+---------+ + | # | Add type | Quant out | Pattern | Post op | + +---+---------------+-----------+------------------------------+---------+ + | 1 | In-/out-place | Yes | linear + fp32 -> (relu) -> q | add | + +---+---------------+-----------+------------------------------+---------+ + | 2 | In-/out-place | No | linear + fp32 -> (relu) | sum | + +---+---------------+-----------+------------------------------+---------+ + + 2. int8-mixed-bf16 + +---+----------+---------------+-----------+-----------------------------------------+---------+ + | # | X2 dtype | Add type | Quant out | Pattern | Post op | + +---+----------+---------------+-----------+-----------------------------------------+---------+ + | 1 | BF16 | In-/out-place | Yes | linear + bf16 -> (relu) -> q | add | + +---+----------+---------------+-----------+-----------------------------------------+---------+ + | 2 | BF16 | In-/out-place | No | linear + bf16 -> (relu) | sum | + +---+----------+---------------+-----------+-----------------------------------------+---------+ + | 3 | FP32 | Out-place | Yes | linear + fp32 -> (relu) -> q | add | + | | | In-place right| | | | + +---+----------+---------------+-----------+-----------------------------------------+---------+ + | 4 | FP32 | Out-place | No | linear + fp32 -> (relu) | sum | + | | | In-place right| | | | + +---+----------+---------------+-----------+-----------------------------------------+---------+ + | 5 | FP32 | In-place left | Yes | linear + fp32 -> to_bf16 -> (relu) -> q | add | + +---+----------+---------------+-----------+-----------------------------------------+---------+ + | 6 | FP32 | In-place left | No | linear + fp32 -> to_bf16 -> (relu) | add | + +---+----------+---------------+-----------+-----------------------------------------+---------+ + + Note + (1) The positions of linear and the extra input can be swapped. + (2) we don't insert q-dq before the extra input of linear-add by recipe. But if q-dq is found at the + extra input, we don't match that pattern because we cannot match all these patterns in 3 passes. + """ + for x_scale_zp_are_tensors in (False, True): + qlinear_binary_op = ( + torch.ops.onednn.qlinear_pointwise.binary_tensor + if x_scale_zp_are_tensors + else torch.ops.onednn.qlinear_pointwise.binary + ) + unary_postop_list = ["none", "relu"] + unary_postop_dict = { + "none": None, + "relu": aten.relu.default, + } + convert_dtype_after_binary_list = [False, True] + + # Priority 1 to match: QLinear Binary or Binary-Unary pattern with int8 output + # Covers case (1) of int8-mixed-fp32 and case (1)(3)(5) of int8-mixed-bf16, + # totally 3 patterns (2 are identical) + swap_binary_inputs_list = [False, True] + int8_mixed_bf16_list = [False, True] + combinations = itertools.product( + unary_postop_list, + int8_mixed_bf16_list, + swap_binary_inputs_list, + convert_dtype_after_binary_list, + ) + qlinear_binary_replace_patterns = {} + for unary_op, int8_mixed_bf16, swap_inputs, cvt_dtype_binary in combinations: + if not int8_mixed_bf16 and cvt_dtype_binary: + # No convert node after binary node if dtypes are all fp32 + continue + qlinear_binary_replace_patterns.update( + { + PostOpAttr( + "add", 1.0, unary_op, [], "" + ): generate_pattern_with_output_quant( + generate_pattern_with_unary( + generate_pattern_with_binary( + aten.add.Tensor, + get_qlinear_pt2e_pattern(x_scale_zp_are_tensors), + KeywordArg("other"), + # If fp32 extra input is inplace added to bf16 linear output, + # a to_bf16 node is inserted after binary + dtype_convert=cvt_dtype_binary, + swap_inputs=swap_inputs, + ), + unary_postop_dict[unary_op], + ), + ) + } + ) + for binary_unary_attr, patterns in qlinear_binary_replace_patterns.items(): + _register_qlinear_post_op_fusion_pass( + patterns, + 3, # pass_number + qlinear_binary_op, # computation_op + binary_unary_attr, + ) + + # Priority 2.1 to match: QLinear Binary-Unary pattern with fp32/bfloat16 output + # Covers case (2) of int8-mixed-fp32 and case (2)(4) of int8-mixed-bf16, + # totally 2 patterns (2 are identical) + binary_replace_float_out_patterns = {} + for swap_binary_inputs in swap_binary_inputs_list: + binary_replace_float_out_patterns.update( + { + PostOpAttr("sum", 1.0, "relu", [], ""): generate_pattern_with_unary( + generate_pattern_with_binary( + aten.add.Tensor, + get_qlinear_pt2e_pattern(x_scale_zp_are_tensors), + KeywordArg("accum"), + dtype_convert=False, + swap_inputs=swap_binary_inputs, + ), + aten.relu.default, + ), + } + ) + for ( + binary_unary_attr, + patterns, + ) in binary_replace_float_out_patterns.items(): + _register_qlinear_post_op_fusion_pass( + patterns, + 4, # pass_number + qlinear_binary_op, # computation_op + binary_unary_attr, + ) + # Priority 2.2 to match: QLinear Binary-Unary pattern with fp32/bfloat16 output + # Covers case (6) of int8-mixed-bf16 + binary_replace_float_out_patterns = {} + for swap_binary_inputs in swap_binary_inputs_list: + binary_replace_float_out_patterns.update( + { + PostOpAttr("add", 1.0, "relu", [], ""): generate_pattern_with_unary( + generate_pattern_with_binary( + aten.add.Tensor, + get_qlinear_pt2e_pattern(x_scale_zp_are_tensors), + KeywordArg("other"), + dtype_convert=True, + swap_inputs=swap_binary_inputs, + ), + aten.relu.default, + ), + } + ) + for ( + binary_unary_attr, + patterns, + ) in binary_replace_float_out_patterns.items(): + _register_qlinear_post_op_fusion_pass( + patterns, + 4, # pass_number + qlinear_binary_op, # computation_op + binary_unary_attr, + ) + + # Priority 3.1: QLinear Binary pattern with fp32/bfloat16 output + # Covers case (2) of int8-mixed-fp32 and case (2)(4) of int8-mixed-bf16, + # totally 2 patterns (2 are identical) + binary_replace_float_out_patterns = {} + for swap_binary_inputs in swap_binary_inputs_list: + binary_replace_float_out_patterns.update( + { + PostOpAttr( + "sum", 1.0, "none", [], "" + ): generate_pattern_with_binary( + aten.add.Tensor, + get_qlinear_pt2e_pattern(x_scale_zp_are_tensors), + KeywordArg("accum"), + dtype_convert=False, + swap_inputs=swap_binary_inputs, + ), + } + ) + for ( + binary_unary_attr, + patterns, + ) in binary_replace_float_out_patterns.items(): + _register_qlinear_post_op_fusion_pass( + patterns, + 5, # pass_number + qlinear_binary_op, # computation_op + binary_unary_attr, + ) + # Priority 3.2: QLinear Binary pattern with fp32/bfloat16 output + # Covers (6) of int8-mixed-bf16 + binary_replace_float_out_patterns = {} + for swap_binary_inputs in swap_binary_inputs_list: + binary_replace_float_out_patterns.update( + { + PostOpAttr( + "add", 1.0, "none", [], "" + ): generate_pattern_with_binary( + aten.add.Tensor, + get_qlinear_pt2e_pattern(x_scale_zp_are_tensors), + KeywordArg("other"), + dtype_convert=True, + swap_inputs=swap_binary_inputs, + ), + } + ) + for ( + binary_unary_attr, + patterns, + ) in binary_replace_float_out_patterns.items(): + _register_qlinear_post_op_fusion_pass( + patterns, + 5, # pass_number + qlinear_binary_op, # computation_op + binary_unary_attr, + ) + + +@functools.lru_cache(None) +def _register_quantization_weight_pack_pass(): + # Step 1: Dequant promotion for int8-mixed-fp32/bf16 + _register_dequant_promotion() + + # Step 2: QConv weight prepack + _register_qconv_weight_prepack() + + # Step 3: QLinear weight prepack + _register_qlinear_weight_prepack() + _register_linear_dynamic_fp16_weight_prepack() + + # Step 4: weight prepack for SmoothQuant from Torchao + _register_smooth_quant_int_mm_pattern() + + # Step 5: QLinear post op Fusion + if not torch.ops.mkldnn._is_mkldnn_acl_supported(): + # skip fusion on ARM + _register_qconv_unary_fusion() + _register_qconv_binary_fusion() + _register_qlinear_unary_fusion() + _register_qlinear_binary_fusion() + + +def quant_lift_up(module_graph: torch.fx.graph.Graph): + """ + Lift up the quant node before view like nodes. It can benefit performance + of Attention like block. For example, we have the pattern as: + + DQ + DQ LINEAR + LINEAR VIEW + VIEW PERMUTE + PERMUTE TRANSPOSE + Q Q + DQ DQ + Matmul + DIV + ADD + SOFTMAX + + We want to lift up the the quant nodes from matmul before view like nodes + as the output of Linear node. + + DQ + DQ LINEAR + LINEAR Q + Q VIEW + VIEW PERMUTE + PERMUTE TRANSPOSE + DQ DQ + Matmul + DIV + ADD + SOFTMAX + + It produces a DQ->LINEAR->Q pattern which can be fused by backend. + """ + + def is_view_op(node): + return node.op == "call_function" and node.target in _VIEW_OPS + + for node in module_graph.nodes: + # Leslie: Here we verify that the quant node has exactly + # one input FX node, with constant scalar value for scale and zero point. + # For the case input of quant node has more than one input FX nodes, + # extend the implementation to lift up all the connected nodes + # before the view nodes to keep the topological order. + if ( + node.op == "call_function" + and node.target in _PER_TENSOR_QUANTIZE_OPS + and len(node.all_input_nodes) == 1 + and is_view_op(node.all_input_nodes[0]) + ): + quant_node = node + input_node_of_quant = quant_node.args[0] + + # Check the nodes along lift up path has only 1 user node + # Propagate view like node to find where to insert the new quant node + could_lift_up = True + current_node = quant_node + input_node = current_node.args[0] + while is_view_op(input_node): + if len(input_node.users) != 1: + could_lift_up = False + break + current_node = input_node + input_node = current_node.args[0] + + # Further check the input node of the first view node has only 1 user node + if could_lift_up and len(input_node.users) == 1: + # Replace dequant's input from quant to quant's input + quant_node.replace_all_uses_with(input_node_of_quant) + # Insert the new quant node + with module_graph.inserting_before(current_node): + new_quant_node = module_graph.node_copy(quant_node) + input_node.replace_all_uses_with(new_quant_node) + + # Update inputs of new_quant_node + def maybe_replace_node(n: torch.fx.Node) -> torch.fx.Node: + if n == input_node_of_quant: + return input_node + else: + return n + + new_args = map_arg(new_quant_node.args, maybe_replace_node) + new_kwargs = map_arg(new_quant_node.kwargs, maybe_replace_node) + new_quant_node.args = new_args # type: ignore[assignment] + new_quant_node.kwargs = new_kwargs # type: ignore[assignment] + module_graph.erase_node(quant_node) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/prepare.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/prepare.py new file mode 100644 index 0000000000000000000000000000000000000000..97801f993c42938b2327b98161a61ea3ba0c44fc --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/prepare.py @@ -0,0 +1,664 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs +import copy +from dataclasses import asdict +from typing import Any, Optional, Union + +import torch +from torch._subclasses import FakeTensor +from torch.ao.quantization import QConfigMapping +from torch.ao.quantization.fx.custom_config import PrepareCustomConfig +from torch.ao.quantization.fx.prepare import ( + _insert_obs_or_fq, + _save_state, +) +from torch.ao.quantization.qconfig import QConfigAny +from torch.fx import Graph, GraphModule, Node +from torch.fx.node import Argument + +from torchao.quantization.pt2e import ( + FROM_NODE_KEY, + DerivedObserverOrFakeQuantize, + ObserverOrFakeQuantize, +) +from torchao.quantization.pt2e.fake_quantize import ( + FixedQParamsFakeQuantize, +) +from torchao.quantization.pt2e.observer import ( + FixedQParamsObserver, + PartialWrapper, + _is_activation_post_process, +) +from torchao.quantization.pt2e.quantizer import ( + DerivedQuantizationSpec, + EdgeOrNode, + FixedQParamsQuantizationSpec, + QuantizationSpec, + QuantizationSpecBase, + SharedQuantizationSpec, +) +from torchao.utils import TORCH_VERSION_AT_LEAST_2_6 + +# TODO: make pt2e folder private? +__all__ = [ + "prepare", +] + + +def _is_activation_post_process_node( + node: Node, named_modules: dict[str, torch.nn.Module] +) -> bool: + return ( + isinstance(node, torch.fx.Node) + and node.op == "call_module" + and _is_activation_post_process(named_modules[str(node.target)]) + ) + + +def _get_observer_kwargs( + quant_spec: Union[QuantizationSpec, FixedQParamsQuantizationSpec], +): + kwargs_dict = asdict(quant_spec) + return copy.deepcopy(kwargs_dict) + + +def _create_obs_or_fq_from_qspec( + quantization_spec: Optional[QuantizationSpecBase], + obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize], + is_qat: bool, +): + """Create observer or fake quantize objects based on quantization spec + + Args: + quantization_spec: used to store parameters to create the observer or fake quantizer + obs_or_fq_map: this is a map from edge/output to the corresponding observer/fake_quant + instance, it may be reused for different edge/output depending on configuration + """ + if quantization_spec is None: + return None + if isinstance(quantization_spec, SharedQuantizationSpec): + edge_or_node = quantization_spec.edge_or_node + assert edge_or_node in obs_or_fq_map, ( + "please make sure only refer to edge or node that has " + f"observer/fake_quant inserted: '{edge_or_node}' not in\n{obs_or_fq_map.keys()}" + ) + return obs_or_fq_map[edge_or_node] + elif isinstance(quantization_spec, DerivedQuantizationSpec): + # can't use asdict, so not calling get_observer_kwargs here + kwargs = { + "dtype": quantization_spec.dtype, + "derive_qparams_fn": quantization_spec.derive_qparams_fn, + "quant_min": quantization_spec.quant_min, + "quant_max": quantization_spec.quant_max, + "qscheme": quantization_spec.qscheme, + "ch_axis": quantization_spec.ch_axis, + } + edge_or_nodes = quantization_spec.derived_from + obs_or_fqs = [obs_or_fq_map[k] for k in edge_or_nodes] + kwargs["obs_or_fqs"] = obs_or_fqs + return DerivedObserverOrFakeQuantize.with_args(**kwargs)() + elif isinstance(quantization_spec, FixedQParamsQuantizationSpec): + kwargs = _get_observer_kwargs(quantization_spec) + observer_ctr = FixedQParamsObserver.with_args(**kwargs) + if is_qat: + return FixedQParamsFakeQuantize.with_args(observer=observer_ctr)() + else: + return observer_ctr() + + assert isinstance(quantization_spec, QuantizationSpec), ( + f"Expected QuantizationSpec got: {quantization_spec}" + ) + observer_or_fake_quant_ctr = quantization_spec.observer_or_fake_quant_ctr + kwargs = _get_observer_kwargs(quantization_spec) + kwargs.pop("observer_or_fake_quant_ctr") + # we will remove is_dynamic from QuantizationSpec because + # it seems that dynamic range quantization + obs_or_fq_class = observer_or_fake_quant_ctr + if isinstance(observer_or_fake_quant_ctr, PartialWrapper): + obs_or_fq_class = observer_or_fake_quant_ctr.p.func # type: ignore[union-attr, assignment] + if "PerChannel" not in obs_or_fq_class.__name__: # type: ignore[operator, union-attr] + kwargs.pop("ch_axis") + return observer_or_fake_quant_ctr.with_args(**kwargs)() + + +def _find_root_edge_or_node( + edge_or_node: EdgeOrNode, shared_with_map: dict[EdgeOrNode, EdgeOrNode] +) -> EdgeOrNode: + """Find the root node for the sharing tree + Args: + edge_or_node: edge/node that we want to find the root + shared_with_map: each edge/node points to the parent, the root node will points to itself + + Returns: + root edge/node + """ + parent = shared_with_map[edge_or_node] + if parent == edge_or_node: + return edge_or_node + root = _find_root_edge_or_node(parent, shared_with_map) + # path compression + shared_with_map[edge_or_node] = root + return root + + +def _union( + parent: EdgeOrNode, + child: EdgeOrNode, + shared_with_map: dict[EdgeOrNode, EdgeOrNode], +) -> None: + """Merge the subtree for `child` with `parent`, the order is important here""" + root_parent = _find_root_edge_or_node(parent, shared_with_map) + root_child = _find_root_edge_or_node(child, shared_with_map) + # union the two trees by pointing the root of child to root of parent + shared_with_map[root_child] = root_parent + + +def _update_shared_with( + child: EdgeOrNode, + qspec: QuantizationSpecBase, + shared_with_map: dict[EdgeOrNode, EdgeOrNode], +): + """Update the `shared_with_map` based on the qspec, this applies the `SharedQuantizationSpec` + configuration and established the relationship between `edge_or_node` with the edge/node that it + is pointing to, we'll use this information in the end to get the group id + """ + if isinstance(qspec, SharedQuantizationSpec): + parent = qspec.edge_or_node + # we point from edge_or_node to the node that it is sharing_with, e.g. + # qspec for a = SharedQuantizationSpec(b) means `a` points to `b` + _union(parent, child, shared_with_map) + + +def _unwrap_shared_qspec( + qspec: QuantizationSpecBase, + edge_or_node_to_qspec: dict[EdgeOrNode, QuantizationSpecBase], + shared_with_map: dict[EdgeOrNode, EdgeOrNode], +) -> QuantizationSpecBase: + """Unwraps qspec to get the final root qspec (non SharedQuantizationSpec) + if qspec is SharedQuantizationSpec + (1). tries to find the root edge or node for the node that the qspec points to + (2). recursively find the root qspec based on the qspec for the root node + """ + if isinstance(qspec, SharedQuantizationSpec): + sharing_with = qspec.edge_or_node + root = _find_root_edge_or_node(sharing_with, shared_with_map) + qspec = edge_or_node_to_qspec[root] + return _unwrap_shared_qspec(qspec, edge_or_node_to_qspec, shared_with_map) + return qspec + + +def _has_same_attr( + qspec_a: QuantizationSpecBase, qspec_b: QuantizationSpecBase, attr_name: str +): + return ( + hasattr(qspec_a, attr_name) + and hasattr(qspec_b, attr_name) + and getattr(qspec_a, attr_name) == getattr(qspec_b, attr_name) + ) or (not hasattr(qspec_a, attr_name) and not hasattr(qspec_b, attr_name)) + + +def _get_edge_or_node_to_qspec( + model: torch.fx.GraphModule, +) -> dict[EdgeOrNode, QuantizationSpecBase]: + """Get a map from EdgeOrNode to quantization spec based on annotations on the nodes""" + edge_or_node_to_qspec: dict[EdgeOrNode, QuantizationSpecBase] = {} + for n in model.graph.nodes: + if hasattr(n, "meta") and "quantization_annotation" in n.meta: + qa = n.meta["quantization_annotation"] + for input_to_n, qspec in qa.input_qspec_map.items(): + input_edge = (input_to_n, n) + edge_or_node_to_qspec[input_edge] = qspec + if qa.output_qspec is not None: + output_node = n + qspec = qa.output_qspec + edge_or_node_to_qspec[output_node] = qspec + return edge_or_node_to_qspec + + +def _union_input_edge_with( + input_edge, + input_edge_root_qspec, + edge_or_node, + edge_or_node_to_qspec, + shared_with_map, +): + """Union input edge with another edge or node, used in implicit sharing to point the current input + edge to other user edges of the producer node, or the output of producer node since these are + referring to the same Tensor + """ + root_qspec = None + if edge_or_node in edge_or_node_to_qspec: + qspec = edge_or_node_to_qspec[edge_or_node] + root_qspec = _unwrap_shared_qspec(qspec, edge_or_node_to_qspec, shared_with_map) + # TODO: add assertions for types of root qspecs + if root_qspec is not None and all( + _has_same_attr(root_qspec, input_edge_root_qspec, attr) + for attr in [ + "dtype", + "is_dynamic", + "quant_min", + "quant_max", + "qscheme", + "ch_axis", + "scale", + "zero_point", + ] + ): + # the input arg to the node should reuse the existing output observer for arg + # since dtype is the same (we may want to extend this to be a more strict check + # in the future) + # so we point from `input_edge` to `arg` (output of the argument) + _union(edge_or_node, input_edge, shared_with_map) + + +def _get_edge_or_node_to_group_id( + edge_or_node_to_qspec: dict[EdgeOrNode, QuantizationSpecBase], +) -> dict[EdgeOrNode, int]: + """Map from edge/node to the group ID, generated from quantization annotations, + edge/node with the same group ID should use the same observer/fake_quant instance + + This is applying SharedQuantizationSpec configuration and map each edge/node to a group + There is another implicit sharing that's built in the quantization, when we have the following: + * op1 -> op2 + * output of op1: int8_qspec + * (op1 -> op2) input edge: int8_qspec + we'll assume sharing between the output of op1 and input of (op1 -> op2) since these are the same Tensor. + + Figuring out the correct group ID for all edge/node is a standard union find problem: + https://www.geeksforgeeks.org/introduction-to-disjoint-set-data-structure-or-union-find-algorithm/ + + Args: + edge_or_node_to_qspec: Dictionary from edge_or_node to the qspec, derived from annotations + Returns: + edge_or_node_to_group_id: Dictionary from edge_or_node to group_id (int), all edge or node that + belongs to the same group should have the same id + + Example: + op2 -> cat1 -> cat2 + op1 / / + op3 + edge_or_node_to_qspec: { + op1: int8_qspec, + op2: int8_qspec, + (op1, cat1): int8_qspc, + (op2, cat1): SharedQuantizationSpec((op1, cat1)), + cat1: SharedQuantizationSpec((op1, cat1)), + (op3, cat2): int8_qspec, + (cat1, cat2): SharedQuantizationSpec((op3, cat2)), + cat2: SharedQuantizationSpec((op3, cat2)), + } + + edge_or_node_to_group_id = _get_edge_or_node_to_group_id(edge_or_node_to_qspec) + edge_or_node_to_group_id: { + op1: 1, + op2: 1, + (op1, cat1): 1, + (op2, cat1): 1, + cat1: 1, + (op3, cat2): 1, + (cat1, cat2): 1, + cat2: 1, + } + # everything are in the same group because (cat1) and (cat1, cat2) are implicitly shared, which + # connects the two sharing group around cat1 and cat2 op due to transitive sharing + """ + # means the observer of key should be shared with observer with value, by default it will + # be shared with itself + shared_with_map: dict[EdgeOrNode, EdgeOrNode] = { + k: k for k in edge_or_node_to_qspec.keys() + } + for edge_or_node, qspec in edge_or_node_to_qspec.items(): + if isinstance(edge_or_node, torch.fx.Node): + output_node = edge_or_node + _update_shared_with(output_node, qspec, shared_with_map) + else: + input_edge = edge_or_node + input_edge_root_qspec = _unwrap_shared_qspec( + qspec, edge_or_node_to_qspec, shared_with_map + ) + + assert isinstance(input_edge, tuple) + arg, n = input_edge + if n.meta["quantization_annotation"].allow_implicit_sharing: + # NOTE: the order is important here, we first share with other users and then share with previous + # output because the reverse order could cause circular dependency + # e.g node1 -> node2 + # \ -> node3 + # when processing (node1, node2), if we first point (node1, node2) to node1 + # Step 1. shared_map = {(node1, node2): node1} + # Step 2. after that, we point the (node1, node2) to its other user (node1, node3) , + # which means shared_map = {(node1, node2): node1, node1: (node1, node3)} + # because we will point the root of (node1, node2) (in this case node1) to the root of (node1, node3) + # Step 3. and when we process (node1, node3), it can try to point to node1 as well, then we'll + # have a circular dependency + # the following order works around this issue, but this does not allow arbitrary configuration + # of sharing so it might break in a different case in the future, when it breaks + # quantizer writer can check the notes here to debug the issue + + # sharing with other users of the producer node + # (arg, user) + if not isinstance(arg, Node) or not isinstance(n, Node): + raise Exception( # noqa: TRY002 + f"Expected input_edge to have type Tuple[Node, Node], but got: {arg, n}" + ) + for user in arg.users: + if user is n: + continue + arg_to_user_edge = (arg, user) + _union_input_edge_with( + input_edge, + input_edge_root_qspec, + arg_to_user_edge, + edge_or_node_to_qspec, + shared_with_map, + ) + + # sharing with output of producer node + _union_input_edge_with( + input_edge, + input_edge_root_qspec, + arg, + edge_or_node_to_qspec, + shared_with_map, + ) + + _update_shared_with(input_edge, qspec, shared_with_map) + + # now that we get the sharing relations between all edges and nodes, we can assingn group ids + cur_group_id = 0 + edge_or_node_to_group_id: dict[EdgeOrNode, int] = {} + for edge_or_node in shared_with_map.keys(): + root = _find_root_edge_or_node(edge_or_node, shared_with_map) + if root not in edge_or_node_to_group_id: + edge_or_node_to_group_id[root] = cur_group_id + cur_group_id += 1 + edge_or_node_to_group_id[edge_or_node] = edge_or_node_to_group_id[root] + + return edge_or_node_to_group_id + + +def _get_obs_or_fq_map( + edge_or_node_to_group_id: dict[EdgeOrNode, int], + edge_or_node_to_qspec: dict[EdgeOrNode, QuantizationSpecBase], + is_qat: bool, +) -> dict[EdgeOrNode, ObserverOrFakeQuantize]: + """Generates the EdgeOrNode to observer/fake_quant instances + Makes sure that for EdgeOrNode that has the same group_id should have the same observer or fake quant + instances + """ + obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize] = {} + group_id_to_obs_or_fq: dict[int, ObserverOrFakeQuantize] = {} + for edge_or_node, qspec in edge_or_node_to_qspec.items(): + group_id = edge_or_node_to_group_id[edge_or_node] + if group_id not in group_id_to_obs_or_fq: + # TODO: maybe edge_or_node_to_qspec should be edge_or_node_to_root_qspec, this will simplify + # the implementation for _create_obs_or_fq_from_qspec + group_id_to_obs_or_fq[group_id] = _create_obs_or_fq_from_qspec( + qspec, obs_or_fq_map, is_qat + ) + obs_or_fq_map[edge_or_node] = group_id_to_obs_or_fq[group_id] + return obs_or_fq_map + + +def _maybe_insert_input_observer_for_arg_or_kwarg( + node: Union[Node, Any], + arg: Argument, + qconfig: QConfigAny, + model: torch.nn.Module, + named_modules: dict[str, torch.nn.Module], + obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize], + is_qat: bool, +) -> Argument: + """ + Given a `node` and an `arg`, inserts an input observer between + `node` and `arg` if necessary. + """ + # for ops such as torch.cat([x0, x1]), + # traverse through the list + if isinstance(arg, (list, tuple)): + new_arg_to_return = [] + for inner_arg in arg: + new_inner_arg = _maybe_insert_input_observer_for_arg_or_kwarg( + node, + inner_arg, + qconfig, + model, + named_modules, + obs_or_fq_map, + is_qat, + ) + new_arg_to_return.append(new_inner_arg) + return type(arg)(new_arg_to_return) + + if not isinstance(arg, Node): + return arg + assert isinstance(arg, Node) + # default (no observer) + new_arg = arg + + # find the original `arg` node to the current node, skipping inserted observer/fake_quant nodes + original_arg = arg + while _is_activation_post_process_node(original_arg, named_modules): + original_arg = original_arg.args[0] # type: ignore[assignment] + assert isinstance(original_arg, Node), ( + f"expect original argument to be a Node, but got: {type(original_arg)}" + ) + + input_edge = (original_arg, node) + if input_edge not in obs_or_fq_map: + return new_arg + # input_edge needs to be observed + input_edge_obs_or_fq = obs_or_fq_map[input_edge] + if input_edge_obs_or_fq is None: + return new_arg + + arg_as_output_obs_or_fq = obs_or_fq_map.get(original_arg, None) + # the arg is observed as the output and is using the same instance as the input_edge + # we'll reuse the inserted observer/fake_quant + if arg_as_output_obs_or_fq is not None and id(arg_as_output_obs_or_fq) == id( + input_edge_obs_or_fq + ): + return new_arg + + # otherwise, we'll insert a new observer/fake_quant node + + # skip inserting new observers if the same observer instance is inserted before for another user + # Example: + # conv1 -> obs1 -> existing_obs -> conv2 + # \ -> conv3 + # + # instead of inserting new observers we will have: + # conv1 -> obs1 -> existing_obs -> conv2 + # \ -> conv3 + for maybe_obs_node in arg.users.keys(): + if not _is_activation_post_process_node(maybe_obs_node, named_modules): + continue + maybe_obs_mod = named_modules[maybe_obs_node.target] # type: ignore[index] + if id(maybe_obs_mod) == id(input_edge_obs_or_fq): + return maybe_obs_node + + assert isinstance(model.graph, Graph) + new_arg = _insert_obs_or_fq( + arg, input_edge_obs_or_fq, model, named_modules, model.graph + ) + return new_arg + + +def _maybe_insert_input_observers_for_node( + node: Node, + qconfig: QConfigAny, + model: torch.nn.Module, + named_modules: dict[str, torch.nn.Module], + obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize], + is_qat: bool, +) -> None: + """ + If needed, inserts observers to the input args and kwargs of `node`. + Note: modifies `node` inplace. + + For example, if cur_node needs an observer after prev_node, we change from + + prev_node -> cur_node + + To + + prev_node -> obs -> cur_node + + """ + # Look through every input arg. If that arg's target dtype does not + # match the current node's target dtype, insert an observer. + new_args = [] + for arg in node.args: + new_arg = _maybe_insert_input_observer_for_arg_or_kwarg( + node, + arg, + qconfig, + model, + named_modules, + obs_or_fq_map, + is_qat, + ) + new_args.append(new_arg) + + # Clone has a memory_format kwarg, zeros_like has a pin_memory kwarg, and + # gelu has a has an approximate kwarg that persist in exported graph. + # This is just a work around for these. + assert ( + node.target == torch.ops.aten.clone.default + or node.target == torch.ops.aten.zeros_like.default + or node.target == torch.ops.aten.gelu.default + or len(node.kwargs) == 0 + ), " expecting kwargs for aten op IR to be empty" + + # assign the new args to the node, inplace + node.args = tuple(new_args) + + +def _maybe_insert_output_observer_for_node( + node: Node, + model: torch.nn.Module, + named_modules: dict[str, torch.nn.Module], + graph: Graph, + obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize], + is_qat: bool, +) -> Optional[Node]: + if node in obs_or_fq_map: + output_act_obs_or_fq = obs_or_fq_map[node] + new_output = _insert_obs_or_fq( + node, output_act_obs_or_fq, model, named_modules, graph + ) + # propagate numeric debug handle from original node to observer/fake_quant node + if ( + isinstance(node, Node) + and isinstance(new_output, Node) + and FROM_NODE_KEY in node.meta + and TORCH_VERSION_AT_LEAST_2_6 + ): + new_output.meta[FROM_NODE_KEY] = node.meta[FROM_NODE_KEY] + return new_output + return None + + +def _maybe_insert_input_and_output_observers_for_node( + node: Node, + model: torch.fx.GraphModule, + obs_or_fq_map: dict[EdgeOrNode, ObserverOrFakeQuantize], + is_qat: bool, +): + this_node_quantization_annotation = ( + node.meta["quantization_annotation"] + if "quantization_annotation" in node.meta + else None + ) + if this_node_quantization_annotation is None: + return + + named_modules = dict(model.named_modules(remove_duplicate=False)) + _maybe_insert_input_observers_for_node( + node, + None, # qconfig + model, + named_modules, + obs_or_fq_map, + is_qat, + ) + + output_is_a_tensor = "val" in node.meta and isinstance(node.meta["val"], FakeTensor) + if not output_is_a_tensor: + return + + # this returns the new observer node if it was needed + maybe_output_obs_node = _maybe_insert_output_observer_for_node( + node, model, named_modules, model.graph, obs_or_fq_map, is_qat + ) + + if maybe_output_obs_node is None: + return + # Update users of original node to use the output observer + # instead. For example, change + # + # next_node + # / + # cur_node -> obs + # + # to + # + # next_node + # / + # cur_node -> obs + # + # We need to save orig users before updating uses because + # the list of users will change as we update uses + orig_users = list(node.users.keys()) + for user_node in orig_users: + if user_node is maybe_output_obs_node: + continue + user_node.replace_input_with(node, maybe_output_obs_node) + + +def prepare( + model: GraphModule, + node_name_to_scope: dict[str, tuple[str, type]], + is_qat: bool, + obs_or_fq_callback=None, +) -> GraphModule: + # Since we are mutating the graph as we go, we iterate over the original + # nodes before observer insertion, instead of model.graph.nodes. + nodes_before_observation = list(model.graph.nodes) + + # At the high level we construct a map from EdgeOrNode to a observer_or_fake_quant instance + # all edge/nodes that belongs to the same group will use the same instance + # and when we insert observers we'll just query this map to get the correct observer_or_fake_quant + # instance + edge_or_node_to_qspec = _get_edge_or_node_to_qspec(model) + edge_or_node_to_group_id = _get_edge_or_node_to_group_id(edge_or_node_to_qspec) + obs_or_fq_map = _get_obs_or_fq_map( + edge_or_node_to_group_id, edge_or_node_to_qspec, is_qat + ) + if obs_or_fq_callback: + obs_or_fq_callback(model, obs_or_fq_map) + + for node in nodes_before_observation: + # TODO: simplify logic for inserting observers + _maybe_insert_input_and_output_observers_for_node( + node, model, obs_or_fq_map, is_qat + ) + + model = GraphModule(model, model.graph) + + _save_state( + model, + {}, # node_name_to_qconfig + node_name_to_scope, + PrepareCustomConfig(), + {}, # equalization_node_name_to_qconfig + QConfigMapping(), + is_qat, + set(), # observed_node_names + ) + return model diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantize_pt2e.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantize_pt2e.py new file mode 100644 index 0000000000000000000000000000000000000000..5eb385b7de74d83df379651d12cd98e920a7f189 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantize_pt2e.py @@ -0,0 +1,336 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +import torch + +from torchao.utils import TORCH_VERSION_AT_LEAST_2_5, TORCH_VERSION_AT_LEAST_2_7 + +if TORCH_VERSION_AT_LEAST_2_7: + from .constant_fold import constant_fold + +from typing import Union + +from torch.fx import GraphModule, Node +from torch.fx.passes.infra.pass_manager import PassManager + +from torchao.quantization.pt2e.qat_utils import _fold_conv_bn_qat, _fuse_conv_bn_qat +from torchao.quantization.pt2e.quantizer import ( # noqa: F401 + DuplicateDQPass, + PortNodeMetaForQDQ, + Quantizer, +) +from torchao.quantization.pt2e.utils import ( + _disallow_eval_train, + _fuse_conv_bn_, + _get_node_name_to_scope, +) + +from .convert import _convert_to_reference_decomposed_fx +from .prepare import prepare +from .reference_representation_rewrite import reference_representation_rewrite + +__all__ = [ + "prepare_pt2e", + "prepare_qat_pt2e", + "convert_pt2e", +] + + +def prepare_pt2e( + model: GraphModule, + quantizer: Union[Quantizer, torch.ao.quantization.quantizer.quantizer.Quantizer], +) -> GraphModule: + """Prepare a model for post training quantization + + Args: + * `model` (torch.fx.GraphModule): a model captured by `torch.export.export_for_training` API. + * `quantizer`: A backend specific quantizer that conveys how user want the + model to be quantized. Tutorial for how to write a quantizer can be found here: + https://pytorch.org/tutorials/prototype/pt2e_quantizer.html + + Return: + A GraphModule with observer (based on quantizer annotation), ready for calibration + + Example:: + + import torch + from torchao.quantization.pt2e.quantize_pt2e import prepare_pt2e + from torchao.quantization.pt2e.quantizer import ( + XNNPACKQuantizer, + get_symmetric_quantization_config, + ) + + class M(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + self.linear = torch.nn.Linear(5, 10) + + def forward(self, x): + return self.linear(x) + + # initialize a floating point model + float_model = M().eval() + + # define calibration function + def calibrate(model, data_loader): + model.eval() + with torch.no_grad(): + for image, target in data_loader: + model(image) + + # Step 1. program capture + # NOTE: this API will be updated to torch.export API in the future, but the captured + # result shoud mostly stay the same + m = torch.export.export_for_training(m, *example_inputs).module() + # we get a model with aten ops + + # Step 2. quantization + # backend developer will write their own Quantizer and expose methods to allow + # users to express how they + # want the model to be quantized + quantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config()) + m = prepare_pt2e(m, quantizer) + + # run calibration + # calibrate(m, sample_inference_data) + """ + # We will temporarily make prepare_pt2e backward compatible with quantizers that configs, observers, + # and fake quantizers from torch.ao instead of torchao + if isinstance(quantizer, torch.ao.quantization.quantizer.quantizer.Quantizer): + from torch.ao.quantization.quantize_pt2e import ( + prepare_pt2e as torch_prepare_pt2e, + ) + + return torch_prepare_pt2e(model, quantizer) + + torch._C._log_api_usage_once("quantization_api.quantize_pt2e.prepare_pt2e") + original_graph_meta = model.meta + node_name_to_scope = _get_node_name_to_scope(model) + # TODO: check qconfig_mapping to make sure conv and bn are both configured + # to be quantized before fusion + # TODO: (maybe) rewrite this with subgraph_rewriter + _fuse_conv_bn_(model) + model = quantizer.transform_for_annotation(model) + quantizer.annotate(model) + quantizer.validate(model) + model = prepare( + model, + node_name_to_scope, + is_qat=False, + obs_or_fq_callback=quantizer.prepare_obs_or_fq_callback, + ) + model.meta.update(original_graph_meta) + model = _disallow_eval_train(model) + return model + + +def prepare_qat_pt2e( + model: GraphModule, + quantizer: Union[Quantizer, torch.ao.quantization.quantizer.quantizer.Quantizer], +) -> GraphModule: + """Prepare a model for quantization aware training + + Args: + * `model` (torch.fx.GraphModule): see :func:`~torchao.quantization.pt2e.quantize_pt2e.prepare_pt2e` + * `quantizer`: see :func:`~torchao.quantization.pt2e.quantize_pt2e.prepare_pt2e` + + Return: + A GraphModule with fake quant modules (based on quantizer annotation), ready for + quantization aware training + + Example:: + import torch + from torchao.quantization.pt2e.quantize_pt2e import prepare_qat_pt2e + from torchao.quantization.pt2e.quantizer import ( + XNNPACKQuantizer, + get_symmetric_quantization_config, + ) + + class M(torch.nn.Module): + def __init__(self) -> None: + super().__init__() + self.linear = torch.nn.Linear(5, 10) + + def forward(self, x): + return self.linear(x) + + # initialize a floating point model + float_model = M().eval() + + # define the training loop for quantization aware training + def train_loop(model, train_data): + model.train() + for image, target in data_loader: + ... + + # Step 1. program capture + # NOTE: this API will be updated to torch.export API in the future, but the captured + # result shoud mostly stay the same + m = torch.export.export_for_training(m, *example_inputs).module() + # we get a model with aten ops + + # Step 2. quantization + # backend developer will write their own Quantizer and expose methods to allow + # users to express how they + # want the model to be quantized + quantizer = XNNPACKQuantizer().set_global(get_symmetric_quantization_config()) + m = prepare_qat_pt2e(m, quantizer) + + # run quantization aware training + train_loop(prepared_model, train_loop) + + """ + # We will temporarily make prepare_qat_pt2e backward compatible with quantizers that configs, observers, + # and fake quantizers from torch.ao instead of torchao + if isinstance(quantizer, torch.ao.quantization.quantizer.quantizer.Quantizer): + from torch.ao.quantization.quantize_pt2e import ( + prepare_qat_pt2e as torch_prepare_qat_pt2e, + ) + + return torch_prepare_qat_pt2e(model, quantizer) + + torch._C._log_api_usage_once("quantization_api.quantize_pt2e.prepare_qat_pt2e") + original_graph_meta = model.meta + node_name_to_scope = _get_node_name_to_scope(model) + model = quantizer.transform_for_annotation(model) + quantizer.annotate(model) + quantizer.validate(model) + # Perform fusion after annotate to avoid quantizing ops in the new + # subgraph that don't need to be quantized + # TODO: only fuse if conv and bn are both configured to be quantized + _fuse_conv_bn_qat(model) + model = prepare( + model, + node_name_to_scope, + is_qat=True, + obs_or_fq_callback=quantizer.prepare_obs_or_fq_callback, + ) + model.meta.update(original_graph_meta) + model = _disallow_eval_train(model) + return model + + +_QUANT_OPS = [ + torch.ops.quantized_decomposed.quantize_per_tensor.default, + torch.ops.quantized_decomposed.quantize_per_tensor.tensor, + torch.ops.quantized_decomposed.quantize_per_channel.default, +] + +# ops are only registered after 2.5 +if TORCH_VERSION_AT_LEAST_2_5: + _QUANT_OPS += [ + torch.ops.torchao.quantize_affine, + ] + + +def _quant_node_constraint(n: Node) -> bool: + """If there is any pure ops between get_attr and quantize op they will be const propagated + e.g. get_attr(weight) -> transpose -> quantize -> dequantize* + (Note: dequantize op is not going to be constant propagated) + + This filter is added because we don't want to constant fold the things that are not + related to quantization + """ + return n.op == "call_function" and n.target in _QUANT_OPS + + +def _is_torchao_prepared_do_not_use_outside_this_file(model): + from torchao.quantization.pt2e.fake_quantize import ( + FakeQuantize as torchao_FakeQuantize, + ) + from torchao.quantization.pt2e.observer import ( + AffineQuantizedObserverBase as torchao_AffineQuantizedObserverBase, + ) + from torchao.quantization.pt2e.observer import ObserverBase as torchao_ObserverBase + + is_torch_ao_prepared = False + is_torchao_prepared = False + for _, m in model.named_modules(): + if ( + isinstance(m, torch.ao.quantization.fake_quantize.FakeQuantize) + or isinstance(m, torch.ao.quantization.observer.ObserverBase) + or isinstance(m, torch.ao.quantization.observer.AffineQuantizedObserverBase) + ): + is_torch_ao_prepared = True + if ( + isinstance(m, torchao_FakeQuantize) + or isinstance(m, torchao_ObserverBase) + or isinstance(m, torchao_AffineQuantizedObserverBase) + ): + is_torchao_prepared = True + + if is_torch_ao_prepared: + assert not is_torchao_prepared, ( + "Cannot be prepared using both torch.ao and torchao" + ) + if is_torchao_prepared: + assert not is_torch_ao_prepared, ( + "Cannot be prepared using both torch.ao and torchao" + ) + + return is_torchao_prepared + + +def convert_pt2e( + model: GraphModule, + use_reference_representation: bool = False, + fold_quantize: bool = True, +) -> GraphModule: + """Convert a calibrated/trained model to a quantized model + + Args: + * `model` (torch.fx.GraphModule): calibrated/trained model + * `use_reference_representation` (bool): boolean flag to indicate whether to produce referece representation or not + * `fold_quantize` (bool): boolean flag for whether fold the quantize op or not + + Returns: + quantized model, either in q/dq representation or reference representation + + Example:: + + # prepared_model: the model produced by `prepare_pt2e`/`prepare_qat_pt2e` and calibration/training + # `convert_pt2e` produces a quantized model that represents quantized computation with + # quantize dequantize ops and fp32 ops by default. + # Please refer to + # https://pytorch.org/tutorials/prototype/pt2e_quant_ptq_static.html#convert-the-calibrated-model-to-a-quantized-model + # for detailed explanation of output quantized model + quantized_model = convert_pt2e(prepared_model) + + """ + # We will temporarily make convert_pt2e backward compatible with quantizers that configs, observers, + # and fake quantizers from torch.ao instead of torchao + if not _is_torchao_prepared_do_not_use_outside_this_file(model): + from torch.ao.quantization.quantize_pt2e import ( + convert_pt2e as torch_convert_pt2e, + ) + + return torch_convert_pt2e(model, use_reference_representation, fold_quantize) + + torch._C._log_api_usage_once("quantization_api.quantize_pt2e.convert_pt2e") + if not isinstance(use_reference_representation, bool): + raise ValueError( + "Unexpected argument type for `use_reference_representation`, " + f"please make sure you intend to pass argument {use_reference_representation} to convert_pt2e" + ) + original_graph_meta = model.meta + model = _convert_to_reference_decomposed_fx(model) + model = _fold_conv_bn_qat(model) + + pm = PassManager([DuplicateDQPass()]) + model = pm(model).graph_module + + pm = PassManager([PortNodeMetaForQDQ()]) + model = pm(model).graph_module + + if fold_quantize and TORCH_VERSION_AT_LEAST_2_7: + constant_fold(model, _quant_node_constraint) + + if use_reference_representation: + model = reference_representation_rewrite(model) + + model.meta.update(original_graph_meta) + model = _disallow_eval_train(model) + return model diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c5d134b71d1f4ad9513567ad25208923b5e6255 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/__init__.py @@ -0,0 +1,53 @@ +from .composable_quantizer import ComposableQuantizer +from .duplicate_dq_pass import DuplicateDQPass +from .port_metadata_pass import PortNodeMetaForQDQ +from .quantizer import ( + DerivedQuantizationSpec, + EdgeOrNode, + FixedQParamsQuantizationSpec, + QuantizationAnnotation, + QuantizationSpec, + QuantizationSpecBase, + Quantizer, + SharedQuantizationSpec, +) +from .utils import ( + OperatorConfig, + OperatorPatternType, + QuantizationConfig, + annotate_input_qspec_map, + annotate_output_qspec, + get_bias_qspec, + get_input_act_qspec, + get_module_name_filter, + get_output_act_qspec, + get_weight_qspec, + is_valid_annotation, +) + +__all__ = [ + # basic classes for quantizer and annotations + "Quantizer", + "ComposableQuantizer", + "EdgeOrNode", + "QuantizationSpec", + "QuantizationSpecBase", + "DerivedQuantizationSpec", + "FixedQParamsQuantizationSpec", + "SharedQuantizationSpec", + "QuantizationAnnotation", + # utils + "annotate_input_qspec_map", + "annotate_output_qspec", + "get_module_name_filter", + "is_valid_annotation", + "QuantizationConfig", + "OperatorPatternType", + "OperatorConfig", + "get_input_act_qspec", + "get_output_act_qspec", + "get_weight_qspec", + "get_bias_qspec", + "DuplicateDQPass", + "PortNodeMetaForQDQ", +] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/arm_inductor_quantizer.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/arm_inductor_quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..af0c04a79de22ba81f5f3f0a1b9f3c0946b26985 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/arm_inductor_quantizer.py @@ -0,0 +1,396 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs +import functools +import operator +import warnings +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional + +import torch +import torch.nn.functional as F +from torch.fx import Node +from typing_extensions import TypeAlias + +from torchao.quantization.pt2e.fake_quantize import ( + FakeQuantize, + FusedMovingAvgObsFakeQuantize, +) +from torchao.quantization.pt2e.observer import ( + HistogramObserver, + MinMaxObserver, + MovingAverageMinMaxObserver, + PlaceholderObserver, +) +from torchao.quantization.pt2e.quantizer import ( + QuantizationConfig, + get_module_name_filter, +) +from torchao.quantization.pt2e.quantizer.quantizer import ( + QuantizationAnnotation, + QuantizationSpec, +) + +from .x86_inductor_quantizer import ( + X86InductorQuantizer, +) + +FilterFn: TypeAlias = Callable[[List[Node]], bool] + + +if TYPE_CHECKING: + from torchao.quantization.pt2e import _ObserverOrFakeQuantizeConstructor + +__all__ = [ + "ArmInductorQuantizer", + "get_default_arm_inductor_quantization_config", +] + + +@dataclass +class _ArmInductorQuantizationAnnotation(QuantizationAnnotation): + # _is_output_of_quantized_pattern: + # * Node as output node of a fusion pattern. + # * The fusion pattern supports int8 data type. + # * The fusion pattern has inputs annotated to insert observer. + # * The quantization_config is not `None`. + _is_output_of_quantized_pattern: bool = False + + +# Operators support the int8 data type +# and recipe is configured by default in ArmInductorQuantizer. +default_quantizable_ops = { + torch.ops.aten.conv2d.default, + torch.ops.aten.linear.default, +} + +# A superset of default_quantizable_ops includes operators support the int8 data type +# but not enabled by default recipe of ArmInductorQuantizer. +quantizable_ops = default_quantizable_ops | { + torch.ops.aten.matmul.default, +} + + +def _create_module_name_filter(module_name: str) -> FilterFn: + """Create a filter function for a given module name. + + The filter function takes a list of nodes (as determined by the annotate function) + and return True if *all* nodes come from the specified module name, False otherwise. + + For example: + linear_1: "f32[3, 10]" = torch.ops.aten.linear.default(...) # comes from a module with name `sub.linear1` + relu: "f32[3, 10]" = torch.ops.aten.relu.default(linear_1); # comes from a module with name `sub.relu1` + + >> module_name_filter = _create_module_name_filter_inner("sub") + >> print(module_name_filter([relu, linear_1])) + # True # These two nodes are determined by `_annotate_linear_unary` function and from "sub". + """ + + filter_fn = get_module_name_filter(module_name) + + def check_all_nodes_from_module(nodes: list[Node]) -> bool: + all_nodes_from_module_name: bool = all(filter_fn(n) for n in nodes) + return all_nodes_from_module_name + + return check_all_nodes_from_module + + +def _create_operator_type_filter( + operator_type: Callable, +) -> FilterFn: + """Create a filter function for a given operator type. + + The filter function takes a list of nodes and returns True if it contains + exactly one node with the specified operator type, False otherwise. + + For example: + linear_1: "f32[3, 10]" = torch.ops.aten.linear.default(...) # comes from a module with name `sub.linear1` + relu: "f32[3, 10]" = torch.ops.aten.relu.default(linear_1); # comes from a module with name `sub.relu1` + + >> operator_type_filter = _create_operator_type_filter(torch.ops.aten.linear.default) + >> print(operator_type_filter([relu, linear_1])) + # True # These two nodes are determined by `_annotate_linear_unary` function and the second node is `linear`. + """ + + def operator_type_filter(nodes: list[Node]): + num_nodes_with_operator_type = sum( + node.target == operator_type for node in nodes + ) + if num_nodes_with_operator_type > 1: + raise NotImplementedError( + f"Several nodes within a single pattern are {operator_type}." + ) + return num_nodes_with_operator_type == 1 + + return operator_type_filter + + +def _global_config_filter(nodes: List[Node]) -> bool: + """Filter function for global configuration. + + This filter function takes a list of nodes and returns True if there is exactly one node + in the list that is a default quantizable operation, False otherwise. + """ + num_nodes_in_default_quantizable_ops = sum( + node.target in default_quantizable_ops for node in nodes + ) + if num_nodes_in_default_quantizable_ops > 1: + raise NotImplementedError( + "Several nodes within a single pattern are default quantizable operations." + ) + return num_nodes_in_default_quantizable_ops == 1 + + +def _map_module_function_to_aten_operator_type(): + module_function_to_aten_operator: Dict[Callable, torch._ops.OpOverloadPacket] = {} + map_list = ( + ([torch.nn.Conv2d, F.conv2d], torch.ops.aten.conv2d.default), + ([torch.nn.Linear, F.linear], torch.ops.aten.linear.default), + ( + [ + torch.matmul, + ], + torch.ops.aten.matmul.default, + ), + ) + for map_item in map_list: + module_function_to_aten_operator.update(dict.fromkeys(map_item[0], map_item[1])) # type: ignore[arg-type, call-overload] + return module_function_to_aten_operator + + +@functools.lru_cache +def get_default_arm_inductor_quantization_config( + is_qat: bool = False, + is_dynamic: bool = False, +): + extra_args: Dict[str, Any] = {"eps": 2**-12} + if is_qat: + if is_dynamic: + act_observer_or_fake_quant_ctr = FakeQuantize + dynamic_quant_observer = MovingAverageMinMaxObserver.with_args( + averaging_constant=1 + ) + extra_args["observer"] = dynamic_quant_observer + else: + act_observer_or_fake_quant_ctr = FusedMovingAvgObsFakeQuantize # type: ignore[assignment] + else: + if is_dynamic: + act_observer_or_fake_quant_ctr = PlaceholderObserver # type: ignore[assignment] + else: + act_observer_or_fake_quant_ctr = HistogramObserver # type: ignore[assignment] + # check for the qconfig ------------------------- + act_quantization_spec = QuantizationSpec( + dtype=torch.int8, + quant_min=-128, + quant_max=127, + qscheme=torch.per_tensor_affine, + is_dynamic=is_dynamic, + observer_or_fake_quant_ctr=act_observer_or_fake_quant_ctr.with_args( + **extra_args + ), + ) + + weight_observer_or_fake_quant_ctr: _ObserverOrFakeQuantizeConstructor = ( + FusedMovingAvgObsFakeQuantize if is_qat else MinMaxObserver + ) + + if is_qat: + # Only support per tensor quant for now + extra_args["observer"] = MovingAverageMinMaxObserver # type: ignore[dict-item] + weight_quantization_spec = QuantizationSpec( + dtype=torch.int8, + quant_min=-128, + quant_max=127, + qscheme=torch.per_tensor_symmetric, + is_dynamic=False, + observer_or_fake_quant_ctr=weight_observer_or_fake_quant_ctr.with_args( + **extra_args + ), + ) + bias_quantization_spec = None # will use placeholder observer by default + quantization_config = QuantizationConfig( + act_quantization_spec, + act_quantization_spec, + weight_quantization_spec, + bias_quantization_spec, + is_qat, + ) + return quantization_config + + +def _config_checker(method: Callable) -> Callable: + @functools.wraps(method) + def wrapper( + quantizer: "ArmInductorQuantizer", + name: Any, + quantization_config: Optional["QuantizationConfig"], + ) -> "ArmInductorQuantizer": + if quantizer._need_skip_config(quantization_config): + warnings.warn( + f"Skip the quantization config for {name}.", + ) + return quantizer + return method(quantizer, name, quantization_config) + + return wrapper + + +class ArmInductorQuantizer(X86InductorQuantizer): + module_function_to_aten_operator_type = _map_module_function_to_aten_operator_type() + + def get_global_quantization_config(self): + if not isinstance(self.global_config, QuantizationConfig): + warnings.warn( + "The global_config for ArmInductorQuantizer is currently invalid. \ + Please ensure that you use set_global to establish the global quantization configuration." + ) + return self.global_config + + @_config_checker + def set_function_type_qconfig( + self, + function_type: Callable, + quantization_config: Optional[QuantizationConfig], + ) -> "ArmInductorQuantizer": + if function_type in ArmInductorQuantizer.module_function_to_aten_operator_type: + self._set_aten_operator_qconfig( + ArmInductorQuantizer.module_function_to_aten_operator_type[ + function_type + ], + quantization_config, + ) + else: + warnings.warn( + f"function: Unable to customize quantization config for {function_type} by ArmInductorQuantizer." + ) + return self + + @_config_checker + def set_module_type_qconfig( + self, + module_type: torch.nn.Module, + quantization_config: Optional[QuantizationConfig], + ) -> "ArmInductorQuantizer": + if module_type in ArmInductorQuantizer.module_function_to_aten_operator_type: + self._set_aten_operator_qconfig( + ArmInductorQuantizer.module_function_to_aten_operator_type[module_type], + quantization_config, + ) + else: + warnings.warn( + f"Module: Unable to customize quantization config for {module_type} by ArmInductorQuantizer." + ) + return self + + @_config_checker + def set_module_name_qconfig( + self, module_name: str, quantization_config: Optional[QuantizationConfig] + ): + """Set quantization_config for a submodule with name: `module_name`, for example: + quantizer.set_module_name_qconfig("blocks.sub"), it will quantize all supported operator/operator + patterns in the submodule with this module name with the given `quantization_config` + + The supported operators include `quantizable_ops` only. + """ + self.module_name_qconfig[module_name] = quantization_config + return self + + def _set_aten_operator_qconfig( + self, + operator_type: torch._ops.OpOverloadPacket, + quantization_config: Optional[QuantizationConfig], + ) -> "ArmInductorQuantizer": + if operator_type in quantizable_ops: + self.operator_type_qconfig[operator_type] = quantization_config + else: + warnings.warn( + f"operator: Unable to quantize {operator} by ArmInductorQuantizer." + ) + return self + + def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule: + """Annotate the given model with quantization configurations. + + Annotation contracts: + 1. Annotate each node according to the user's qconfig in the following order: + `module_name_qconfig`, `operator_type_qconfig`, and `global_config`. + 2. Avoid re-annotating nodes already annotated in prior stages. For example, + if `linear1` has been annotated by `module_name_qconfig`, it won't be annotated again + during the processing of the 'operator_type_qconfig' or 'global_config'. + 3. For config is `None`, the node will be annotated with `_ArmInductorQuantizationAnnotation(_annotated=True)`. + + For each pair of (module_name_or_operator_type_or_global, qconfig), a filter function is created. + This filter function checks if the node is marked by current stage and not annotated by the previous stage. + """ + for module_name, quantization_config in self.module_name_qconfig.items(): + self._annotate_with_config( + model, quantization_config, _create_module_name_filter(module_name) + ) + + for operator_type, quantization_config in self.operator_type_qconfig.items(): + self._annotate_with_config( + model, quantization_config, _create_operator_type_filter(operator_type) + ) + + if self.global_config: + self._annotate_with_config( + model, + self.global_config, + _global_config_filter, + ) + + return model + + def _annotate_with_config( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: FilterFn, + ) -> None: + """Annotate the model with the given quantization configuration. + + High-level description of quantization recipe for Arm Inductor Backend: + Apply quantization recipe for fusion patterns of conv/linear to enable int8 data type actively. + """ + + # Step1: Recipe of fusion patterns like conv/linear. + self._annotate_conv2d_fusion_pattern(model, quantization_config, filter_fn) + self._annotate_linear_fusion_pattern(model, quantization_config, filter_fn) + self._annotate_matmul(model, quantization_config, filter_fn) + + def _annotate_qat_conv2d_fusion_pattern( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ): + # Annotate QAT Specific patterns + self._annotate_qat_conv2d_bn_binary(model, quantization_config, filter_fn) + self._annotate_qat_conv2d_bn(model, quantization_config, filter_fn) + + def _annotate_conv2d_fusion_pattern( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ): + if (quantization_config is None) or (quantization_config.is_qat): + # Annotate QAT specific pattern: mainly due to BN not folded in prepare_qat + self._annotate_qat_conv2d_fusion_pattern( + model, quantization_config, filter_fn + ) + self._annotate_conv2d_binary(model, quantization_config, filter_fn) + self._annotate_conv2d(model, quantization_config, filter_fn) + + def _annotate_linear_fusion_pattern( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ): + self._annotate_linear_unary(model, quantization_config, filter_fn) + self._annotate_linear(model, quantization_config, filter_fn) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/composable_quantizer.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/composable_quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..6602151e3f507ea2115e1f2302bafca01cf825af --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/composable_quantizer.py @@ -0,0 +1,84 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from .quantizer import QuantizationAnnotation, Quantizer + +if TYPE_CHECKING: + import torch + from torch.fx import Node + +__all__ = [ + "ComposableQuantizer", +] + + +class ComposableQuantizer(Quantizer): + """ + ComposableQuantizer allows users to combine more than one quantizer into a single quantizer. + This allows users to quantize a model with multiple quantizers. E.g., embedding quantization + maybe supported by one quantizer while linear layers and other ops might be supported by another + quantizer. + + ComposableQuantizer is initialized with a list of `Quantizer` instances. + The order of the composition matters since that is the order in which the quantizers will be + applies. + Example: + ``` + embedding_quantizer = EmbeddingQuantizer() + linear_quantizer = MyLinearQuantizer() + xnnpack_quantizer = XNNPackQuantizer() # to handle ops not quantized by previous two quantizers + composed_quantizer = ComposableQuantizer([embedding_quantizer, linear_quantizer, xnnpack_quantizer]) + prepared_m = prepare_pt2e(model, composed_quantizer) + ``` + """ + + def __init__(self, quantizers: list[Quantizer]): + super().__init__() + self.quantizers = quantizers + self._graph_annotations: dict[Node, QuantizationAnnotation] = {} + + def _record_and_validate_annotations( + self, gm: torch.fx.GraphModule, quantizer: Quantizer + ) -> None: + for n in gm.graph.nodes: + if "quantization_annotation" in n.meta: + # check if the annotation has been changed by + # comparing QuantizationAnnotation object id + if n in self._graph_annotations and ( + id(self._graph_annotations[n]) + != id(n.meta["quantization_annotation"]) + ): + raise RuntimeError( + f"Quantizer {quantizer.__class__.__name__} has changed annotations on node {n}" + ) + else: + self._graph_annotations[n] = n.meta["quantization_annotation"] + else: + if n in self._graph_annotations: + raise RuntimeError( + f"Quantizer {quantizer.__class__.__name__} has removed annotations on node {n}" + ) + + def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule: + """just handling global spec for now""" + for quantizer in self.quantizers: + quantizer.annotate(model) + self._record_and_validate_annotations(model, quantizer) + return model + + def transform_for_annotation( + self, model: torch.fx.GraphModule + ) -> torch.fx.GraphModule: + for quantizer in self.quantizers: + model = quantizer.transform_for_annotation(model) + return model + + def validate(self, model: torch.fx.GraphModule) -> None: + pass diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/duplicate_dq_pass.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/duplicate_dq_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..2bf4e732c1c53d2bb5614bc37687849505d52f5e --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/duplicate_dq_pass.py @@ -0,0 +1,91 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs +import logging +import operator + +import torch +from torch.fx.node import map_arg +from torch.fx.passes.infra.pass_base import PassBase, PassResult + +from torchao.quantization.pt2e.utils import ( + _filter_sym_size_users, +) + +from .utils import ( + is_valid_annotation, +) + +logger = logging.getLogger(__name__) +logger.setLevel(logging.WARNING) + +__all__ = ["DuplicateDQPass"] + +_QUANTIZE_OPS = [ + torch.ops.quantized_decomposed.quantize_per_tensor.default, + torch.ops.quantized_decomposed.quantize_per_tensor.tensor, + torch.ops.quantized_decomposed.quantize_per_channel.default, +] + +_DEQUANTIZE_OPS = [ + torch.ops.quantized_decomposed.dequantize_per_tensor.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.tensor, + torch.ops.quantized_decomposed.dequantize_per_channel.default, +] + + +def _maybe_duplicate_dq( + gm: torch.fx.GraphModule, dq_node: torch.fx.Node, user: torch.fx.Node +): + annotation = user.meta.get("quantization_annotation", None) + if not is_valid_annotation(annotation): + return + with gm.graph.inserting_after(dq_node): + new_node = gm.graph.node_copy(dq_node) + + def maybe_replace_node(n: torch.fx.Node) -> torch.fx.Node: + if n == dq_node: + return new_node + else: + return n + + new_args = map_arg(user.args, maybe_replace_node) + new_kwargs = map_arg(user.kwargs, maybe_replace_node) + user.args = new_args # type: ignore[assignment] + user.kwargs = new_kwargs # type: ignore[assignment] + + +class DuplicateDQPass(PassBase): + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: + for node in graph_module.graph.nodes: + if node.op == "call_function" and node.target in _DEQUANTIZE_OPS: + dq_users = _filter_sym_size_users(node) + if len(dq_users) <= 1: + continue + # Do not duplicate dq for dynamic quantization + # Pattern: choose_qparam - getitem - q - dq + q_node = node.args[0] + if q_node.op == "call_function" and q_node.target in _QUANTIZE_OPS: + getitem_node = q_node.args[1] + if ( + isinstance(getitem_node, torch.fx.node.Node) + and getitem_node.op == "call_function" + and getitem_node.target == operator.getitem + ): + choose_qparam_node = getitem_node.args[0] + if ( + isinstance(choose_qparam_node, torch.fx.node.Node) + and choose_qparam_node.op == "call_function" + and choose_qparam_node.target + == torch.ops.quantized_decomposed.choose_qparams.tensor + ): + continue + for user in dq_users: + _maybe_duplicate_dq(graph_module, node, user) + graph_module.graph.eliminate_dead_code() + graph_module.recompile() + return PassResult(graph_module, True) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/embedding_quantizer.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/embedding_quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..40979f6fe820fad27a02a26c24b7a93d5a5c1d78 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/embedding_quantizer.py @@ -0,0 +1,101 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs +from __future__ import annotations + +import copy + +import torch +import torch.nn.functional as F + +from torchao.quantization.pt2e.observer import PerChannelMinMaxObserver +from torchao.quantization.pt2e.quantizer import ( + OperatorConfig, + OperatorPatternType, + QuantizationAnnotation, + QuantizationConfig, + QuantizationSpec, + Quantizer, +) + +__all__ = [ + "get_embedding_operators_config", + "EmbeddingQuantizer", +] + + +def get_embedding_operators_config() -> OperatorConfig: + weight_quantization_spec = QuantizationSpec( + dtype=torch.uint8, + qscheme=torch.per_channel_affine_float_qparams, + ch_axis=0, + observer_or_fake_quant_ctr=PerChannelMinMaxObserver.with_args(eps=2**-12), + ) + quantization_config = QuantizationConfig(None, None, weight_quantization_spec, None) + ops: list[OperatorPatternType] = [[torch.nn.Embedding]] + ops.append([F.embedding]) + supported_config_and_operators = OperatorConfig( + config=quantization_config, operators=ops + ) + return copy.deepcopy(supported_config_and_operators) + + +class EmbeddingQuantizer(Quantizer): + def __init__(self) -> None: + super().__init__() + + @classmethod + def get_supported_quantization_configs(cls) -> list[QuantizationConfig]: + op_configs: set[QuantizationConfig] = { + spec for spec, _ in cls.get_supported_operators() + } + return list(op_configs) + + @classmethod + def get_supported_operator_for_quantization_config( + cls, quantization_config: QuantizationConfig + ) -> list[OperatorPatternType]: + for config, ops in cls.get_supported_operators(): + # note: this assumes each entry in cls.supported_spec_and_operators + # corresponds to one spec, e.g. we don't have + # [(spec1, op_list1), (spec1, op_list2), (spec2, op_list3)] + # where the first and second entry have the same spec but did not + # merge the op list + if config == quantization_config: + return ops + return [] + + def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule: + """just handling global spec for now""" + self._annotate_embedding_ops(model.graph) + return model + + def _annotate_embedding_ops(self, graph: torch.fx.Graph) -> None: + embedding_config: OperatorConfig = get_embedding_operators_config() + for node in graph.nodes: + # Keep node parsing based annotations instead of module partitioners + # just as an example of alternate ways of annotating + if ( + node.op == "call_function" + and node.target == torch.ops.aten.embedding.default + ): + if embedding_config.config.weight is None: + raise ValueError( + "Embedding config must have a valid weight quantization spec." + ) + node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map={ + node.args[0]: embedding_config.config.weight, + } + ) + + def validate(self, model: torch.fx.GraphModule) -> None: + pass + + @classmethod + def get_supported_operators(cls) -> list[OperatorConfig]: + return [get_embedding_operators_config()] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/port_metadata_pass.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/port_metadata_pass.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d910e603e2a8aff06d86fb5bec5d123a6ac7ec --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/port_metadata_pass.py @@ -0,0 +1,291 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs +import logging +from typing import Any, Optional + +import torch +from torch._export.error import InternalError +from torch.fx.passes.infra.pass_base import PassBase, PassResult + +from torchao.quantization.pt2e.utils import ( + _filter_sym_size_users, +) +from torchao.quantization.quant_primitives import quant_lib # noqa: F401 +from torchao.utils import TORCH_VERSION_AT_LEAST_2_5 + +from .quantizer import ( + QuantizationSpecBase, +) +from .utils import ( + is_valid_annotation, +) + +logger = logging.getLogger(__name__) +logger.setLevel(logging.ERROR) + +__all__ = ["PortNodeMetaForQDQ"] + +_METADATA_TO_PORT = [ + "stack_trace", + "quantization_tag", +] + +_QUANTIZE_OPS = [ + torch.ops.quantized_decomposed.quantize_per_tensor.default, + torch.ops.quantized_decomposed.quantize_per_tensor.tensor, + torch.ops.quantized_decomposed.quantize_per_channel.default, +] + +_DEQUANTIZE_OPS = [ + torch.ops.quantized_decomposed.dequantize_per_tensor.default, + torch.ops.quantized_decomposed.dequantize_per_tensor.tensor, + torch.ops.quantized_decomposed.dequantize_per_channel.default, +] + +_CHOOSE_QPARAMS_OPS = [ + torch.ops.quantized_decomposed.choose_qparams.tensor, + torch.ops.quantized_decomposed.choose_qparams_symmetric.tensor, +] + + +# ops are only registered after 2.5 +if TORCH_VERSION_AT_LEAST_2_5: + _QUANTIZE_OPS += [torch.ops.torchao.quantize_affine] + _DEQUANTIZE_OPS += [torch.ops.torchao.dequantize_affine] + _CHOOSE_QPARAMS_OPS += [torch.ops.torchao.choose_qparams_affine] + + +def _add_metadata(to_node: torch.fx.Node, from_node: torch.fx.Node) -> None: + from_meta = from_node.meta + for meta_name in _METADATA_TO_PORT: + if meta_name in from_meta: + to_node.meta[meta_name] = from_meta[meta_name] + + +def _has_quant_annotation(node: torch.fx.Node) -> bool: + return "quantization_annotation" in node.meta + + +def _find_choose_qparams_node(node: torch.fx.Node) -> Optional[torch.fx.Node]: + # BFS to look for choose qparams + from collections import deque + + queue = deque(list(node.users.keys())) + while len(queue): + n = queue.popleft() + if n.op == "output": + continue + if n.op == "call_function" and n.target in _CHOOSE_QPARAMS_OPS: + return n + for k in n.users.keys(): + queue.append(k) + return None + + +def _is_connected(source: torch.fx.Node, dest: torch.fx.Node) -> bool: + """ + Assuming dest is one of the ops inserted by quant workflow, this function + finds if source and dest are connected. Assumption is that only quant workflow + inserted ops exist between source and dest + """ + quant_workflow_ops = _QUANTIZE_OPS + _DEQUANTIZE_OPS + quant_workflow_ops.append(torch.ops.quantized_decomposed.choose_qparams.tensor) + while dest.target in quant_workflow_ops: + if not isinstance(dest.args[0], torch.fx.Node): + raise ValueError( + f"expected arg[0] of quant workflow ops to be a node but found {dest.args[0]}" + ) + dest = dest.args[0] + return dest == source + + +def _find_q_dq_node_for_user( + produer: torch.fx.Node, user: torch.fx.Node +) -> tuple[Any, Any]: + """ + Find q, dq pair corresponding to [producer -> q -> dq -> user] + Utils works by finding dq arg of user and ensuring it is connected to + producer + """ + dq_node = None + for n in user.args: + if ( + isinstance(n, torch.fx.Node) + and n.op == "call_function" + and n.target in _DEQUANTIZE_OPS + ): + if _is_connected(produer, n): + dq_node = n + break + if dq_node is None: + for n in user.kwargs: + if ( + isinstance(n, torch.fx.Node) + and n.op == "call_function" + and n.target in _DEQUANTIZE_OPS + ): + if _is_connected(produer, n): + dq_node = n + break + if dq_node is None: + return (None, None) + + q_node = None + if ( + dq_node.args[0].op == "call_function" # type: ignore[union-attr] + and dq_node.args[0].target in _QUANTIZE_OPS # type: ignore[union-attr] + ): + q_node = dq_node.args[0] + return (q_node, dq_node) + + +def _port_metadata_for_input_quant_nodes( + input_node: torch.fx.Node, + node: torch.fx.Node, + qspec: Optional[QuantizationSpecBase], +): + if qspec is None: + return + + is_dynamic_quant = getattr(qspec, "is_dynamic", None) + if is_dynamic_quant is not None and is_dynamic_quant is True: + choose_qparams_node = _find_choose_qparams_node(input_node) + if choose_qparams_node is None: + raise ValueError(f"No chose qparams node found for {node}") + choose_qparam_users = _filter_sym_size_users(choose_qparams_node) + if len(choose_qparam_users) != 2: + raise InternalError(f"Expecting exactly two user for {choose_qparams_node}") + scale_node = choose_qparam_users.pop() + dynamic_q_node = next(iter(scale_node.users.keys())) + dynamic_q_node_users = _filter_sym_size_users(dynamic_q_node) + if len(dynamic_q_node_users) > 1: + raise InternalError(f"Expecting single user for {dynamic_q_node}") + dynamic_dq_node = dynamic_q_node_users.pop() + _add_metadata(choose_qparams_node, node) + _add_metadata(dynamic_q_node, node) + _add_metadata(dynamic_dq_node, node) + else: + q_node, dq_node = _find_q_dq_node_for_user(input_node, node) + if q_node is None or dq_node is None: + return + # add metadata for all the node between q_node and get_attr node + # if the q_node can be traced back to get_attr node + q_to_get_attr_nodes = [q_node] + q_node_input = q_node.args[0] + while ( + isinstance(q_node_input, torch.fx.Node) + and q_node_input.op == "call_function" + and q_node_input.target + in [ + torch.ops.aten.flatten.using_ints, + torch.ops.aten.permute.default, + torch.ops.aten.permute_copy.default, + torch.ops.aten.slice_copy.Tensor, + torch.ops.aten.squeeze.dim, + torch.ops.aten.squeeze_copy.dim, + torch.ops.aten.transpose.Dimname, + torch.ops.aten.transpose.int, + torch.ops.aten.transpose_, + torch.ops.aten.view_copy.default, + torch.ops.aten.view.default, + torch.ops.aten._mkldnn_transpose, + ] + ): + q_to_get_attr_nodes.append(q_node_input) + q_node_input = q_node_input.args[0] + if isinstance(q_node_input, torch.fx.Node) and q_node_input.op == "get_attr": + for n in q_to_get_attr_nodes: + _add_metadata(n, q_node_input) + _add_metadata(dq_node, node) + + +def _port_metadata_for_output_quant_nodes( + node: torch.fx.Node, qspec: Optional[QuantizationSpecBase] +): + if qspec is None: + return + + node_users = _filter_sym_size_users(node) + if len(node.users) == 0: + return + if len(node_users) != 1: + logger.warning(f"Expecting {node} to have single user") # noqa: G004 + q_node = node_users.pop() + if q_node.op != "call_function" or q_node.target not in _QUANTIZE_OPS: + logger.warning( + f"Expecting {node} user to be a quantized op but got {q_node}" # noqa: G004 + ) # noqa: G004 + return + + _add_metadata(q_node, node) + + +class PortNodeMetaForQDQ(PassBase): + """ + Port metadata for nodes added by quantization flow. + For static quant these are: + - quantizer_per_tensor.default, dequantize_per_tensor.default + - quantizer_per_channel.default, dequantize_per_channel.default + For dynamic quant these are: + - choose_qparams.tensor + - quantizer_per_tensor.tensor, dequantize_per_tensor.tensor + - quantizer_per_channel.default, dequantize_per_channel.default + + Rules of porting metadata: + - Metadata to be ported: + - nn_module_stack + - stack_trace + - quantization_tag + - Metadata to NOT be ported: + - Everything else + - Rules: + - Statically quantized patterns: + - Dequantize nodes on the inputs to be quantized inherit metadata of the consumer node. + - Quantize nodes on the outputs inherit metadata of the producer node. + - Example 1: + - Original: [Conv -> AvgPool -> Linear] + - Quantized [Q-> DQ -> Conv -> Q -> DQ -> AvgPool -> Q -> DQ -> Linear -> Q -> DQ] + - Inner brackets specify which nodes Q/DQ inherit metdata from + - [Q-> [DQ -> Conv -> Q] -> [DQ -> AvgPool -> Q] -> [DQ -> Linear -> Q] -> DQ] + - Note first Q and last DQ do not inherit metadata from any nodes + - Example 2: + - Original: [Conv -> AvgPool -> Linear] + - AvgPool is not quantized + - Quantized [Q-> DQ -> Conv -> Q -> DQ -> AvgPool -> Q -> DQ -> Linear -> Q -> DQ] + - Inner brackets specify which nodes Q/DQ inherit metdata from + - [Q-> [DQ -> Conv -> Q] -> DQ -> [AvgPool] -> Q -> [DQ -> Linear -> Q] -> DQ] + - Note DQ and Q nodes around AvgPool do not inherit metadata from AvgPool because + AvgPool was not supposed to be quantized. Metadata porting relies on quantization_annotation + on the nodes (in this case AvgPool node) to conclude if the node or patter was + supposed to be quantized. And subsequntly decide if the preceding Q, if any, should + inherit metadata from AvgPool. + - Dynamically quantized patterns: + - Input that are dynamically quantized have choose_qparams, quantize and dequantize nodes + - For example, below linear is dynamically quantized while rest statically: + - Original: [Conv -> AvgPool -> Linear] + - Quantized [Q-> DQ -> Conv -> Q -> DQ -> AvgPool -> Q -> DQ -> choose_params -> Q -> DQ -> Linear] + - Quantized [Q-> [DQ -> Conv -> Q] -> [DQ -> AvgPool -> Q] -> DQ -> [choose_params -> Q -> DQ -> Linear]] + - Note first Q does not inherit metadata from any nodes + NB: + - The best place for porting metadata is during observer conversion to q/dq. This is because it precisely + knows which quantization spec is converted to q/dq and thus from where the metadata should be ported. + However, since FX and PT2E quant workflow are on a common code-base, this hurts readability quite a bit. + Doing it via a separate pass, helps readability of the code. Once we are able to refactor PT2E quant + code, this pass should like to be integrated in the refactored variant of "convert" step. + """ + + def call(self, graph_module: torch.fx.GraphModule) -> PassResult: + for node in graph_module.graph.nodes: + annotation = node.meta.get("quantization_annotation", None) + if is_valid_annotation(annotation): + input_qspec_map = node.meta["quantization_annotation"].input_qspec_map + output_qspec = node.meta["quantization_annotation"].output_qspec + for input_node, qspec in input_qspec_map.items(): + _port_metadata_for_input_quant_nodes(input_node, node, qspec) + _port_metadata_for_output_quant_nodes(node, output_qspec) + return PassResult(graph_module, True) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/quantizer.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..479a2a678f179a298a3ee155afa2947676e93a12 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/quantizer.py @@ -0,0 +1,189 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from typing import Callable, Optional, Union + +import torch +from torch import Tensor +from torch.fx import Node + +from torchao.quantization.pt2e import ( + ObserverOrFakeQuantize, + ObserverOrFakeQuantizeConstructor, +) + +__all__ = [ + "Quantizer", + "QuantizationSpecBase", + "QuantizationSpec", + "FixedQParamsQuantizationSpec", + "EdgeOrNode", + "SharedQuantizationSpec", + "DerivedQuantizationSpec", + "QuantizationAnnotation", +] + + +class QuantizationSpecBase(ABC): # noqa: B024 + """Base class for different types of quantization specs that allows users to + specify how to quantize a Tensor (input/output of a Node) in the model + """ + + +@dataclass(eq=True, frozen=True) +class QuantizationSpec(QuantizationSpecBase): + """Quantization spec for common operators that allows user to specify how to + quantize a Tensor, this includes dtype, quant_min, quant_max etc. + """ + + dtype: torch.dtype + # observer or fake_quantize constructor such as + # MinMaxObserver, PerChannelHistogramObserver etc. + # or we can attach some custom args to them + # e.g. MinMaxObserver.with_args(eps=eps) + observer_or_fake_quant_ctr: ObserverOrFakeQuantizeConstructor + quant_min: Optional[int] = None + quant_max: Optional[int] = None + qscheme: Optional[torch.qscheme] = None + ch_axis: Optional[int] = None + is_dynamic: bool = False + + def __post_init__(self): + # TODO: add init for quant_min/quant_max + # quant_min must be less than quant_max + if ( + self.quant_min is not None + and self.quant_max is not None + and self.quant_min > self.quant_max + ): + raise ValueError( + f"quant_min {self.quant_min} must be <= quant_max {self.quant_max}." + ) + + # ch_axis must be less than the number of channels + # but no way to check here. Just check that it is not < 0. + if self.ch_axis is not None and self.ch_axis < 0: + raise ValueError("Ch_axis is < 0.") + + +@dataclass(eq=True, frozen=True) +class FixedQParamsQuantizationSpec(QuantizationSpecBase): + dtype: torch.dtype + scale: float + zero_point: int + quant_min: Optional[int] = None + quant_max: Optional[int] = None + qscheme: Optional[torch.qscheme] = None + is_dynamic: bool = False + + +""" +The way we refer to other points of quantization in the graph will be either +an input edge or an output value +input edge is the connection between input node and the node consuming the input, so it's a Tuple[Node, Node] +output value is an fx Node +""" +EdgeOrNode = Union[tuple[Node, Node], Node] +EdgeOrNode.__module__ = "torchao.quantization.pt2e.quantizer.quantizer" + + +@dataclass(eq=True, frozen=True) +class SharedQuantizationSpec(QuantizationSpecBase): + """ + Quantization spec for the Tensors whose quantization parameters are shared with other Tensors + """ + + # the edge or node to share observer or fake quant instances with + edge_or_node: EdgeOrNode + + +@dataclass(eq=True, frozen=True) +class DerivedQuantizationSpec(QuantizationSpecBase): + """Quantization spec for the Tensors whose quantization parameters are derived from other Tensors""" + + derived_from: list[EdgeOrNode] + derive_qparams_fn: Callable[[list[ObserverOrFakeQuantize]], tuple[Tensor, Tensor]] + dtype: torch.dtype + quant_min: Optional[int] = None + quant_max: Optional[int] = None + qscheme: Optional[torch.qscheme] = None + ch_axis: Optional[int] = None + is_dynamic: bool = False + + +@dataclass +class QuantizationAnnotation: + """How are input arguemnt or output should be quantized, + expressed as QuantizationSpec, this corresponds to how a Tensor in the + operator Graph is observed (PTQ) or fake quantized (QAT) + """ + + # a map from torch.fx.Node to a type of QuantizationSpecBase + input_qspec_map: dict[Node, Optional[QuantizationSpecBase]] = field( + default_factory=dict + ) + + # How the output of this node is quantized, expressed as QuantizationSpec + # TODO: change the value to QuantizationSpec in a separate PR + output_qspec: Optional[QuantizationSpecBase] = None + + # For a Node: node1 and edge: (node1, node2), since they are observing the same + # Tensor, we may want to implicitly share observers, this flag allows people to + # turn off this behavior for the output of the node + allow_implicit_sharing: bool = True + + # whether the node is annotated or not + _annotated: bool = False + + +class Quantizer(ABC): + def transform_for_annotation( + self, model: torch.fx.GraphModule + ) -> torch.fx.GraphModule: + """Allows for user defined transforms to run before annotating the graph. + This allows quantizer to allow quantizing part of the model that are otherwise not quantizable. + For example quantizer can + a) decompose a compound operator like scaled dot product attention, + into bmm and softmax if quantizer knows how to quantize bmm/softmax but not sdpa + or b) transform scalars to tensor to allow quantizing scalares. + + Note: this is an optional method + """ + return model + + # annotate nodes in the graph with observer or fake quant constructors + # to convey the desired way of quantization + @abstractmethod + def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule: + pass + + # validate the annotated graph is supported by the backend + @abstractmethod + def validate(self, model: torch.fx.GraphModule) -> None: + pass + + def prepare_obs_or_fq_callback( + self, + model: torch.fx.GraphModule, + edge_or_node_to_obs_or_fq: dict[EdgeOrNode, ObserverOrFakeQuantize], + ) -> None: + """A callback that will be called after the observers or fake quants are created + for each sharing group, but before they are inserted into the graph. The + callback can be used to make final quantization adjustments, such as enforcing + specific scale and zero point on model input or output. + + Args: + * `model`: the graph module being prepared. + * `edge_or_node_to_obs_or_fq`: a dictionary mapping each annotated edge and + node to the corresponding observer or fake quant object. Note that multiple + edges and/or nodes can map to the same observer / fake quant instance if + they were annotated with SharedQuantizationSpec. This dictionary can be + modified by the callback. + """ + return diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f84ae44817a1af658909d3620e2c9a0668672699 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/utils.py @@ -0,0 +1,164 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs + +import typing +from dataclasses import dataclass +from typing import Callable, NamedTuple, Optional + +import torch +from torch.fx import Node + +from .quantizer import QuantizationAnnotation, QuantizationSpec + + +# In the absence of better name, just winging it with QuantizationConfig +@dataclass(eq=True, frozen=True) +class QuantizationConfig: + input_activation: Optional[QuantizationSpec] + output_activation: Optional[QuantizationSpec] + weight: Optional[QuantizationSpec] + bias: Optional[QuantizationSpec] + # TODO: remove, since we can use observer_or_fake_quant_ctr to express this + is_qat: bool = False + + +# Use Annotated because list[Callable].__module__ is read-only. +OperatorPatternType = typing.Annotated[list[Callable], None] +OperatorPatternType.__module__ = "torchao.quantization.pt2e.quantizer.utils" + + +class OperatorConfig(NamedTuple): + # fix List[str] with List[List[Union[nn.Module, FunctionType, BuiltinFunctionType]]] + # Basically we are mapping a quantization config to some list of patterns. + # a pattern is defined as a list of nn module, function or builtin function names + # e.g. [nn.Conv2d, torch.relu, torch.add] + # We have not resolved whether fusion can be considered internal details of the + # quantizer hence it does not need communication to user. + # Note this pattern is not really informative since it does not really + # tell us the graph structure resulting from the list of ops. + config: QuantizationConfig + operators: list[OperatorPatternType] + + +def get_input_act_qspec(quantization_config: Optional[QuantizationConfig]): + if quantization_config is None: + return None + if quantization_config.input_activation is None: + return None + quantization_spec: QuantizationSpec = quantization_config.input_activation + assert quantization_spec.qscheme in [ + torch.per_tensor_affine, + torch.per_tensor_symmetric, + ] + return quantization_spec + + +def get_output_act_qspec(quantization_config: Optional[QuantizationConfig]): + if quantization_config is None: + return None + if quantization_config.output_activation is None: + return None + quantization_spec: QuantizationSpec = quantization_config.output_activation + assert quantization_spec.qscheme in [ + torch.per_tensor_affine, + torch.per_tensor_symmetric, + ] + return quantization_spec + + +def get_weight_qspec(quantization_config: Optional[QuantizationConfig]): + if quantization_config is None: + return None + assert quantization_config is not None + if quantization_config.weight is None: + return None + quantization_spec: QuantizationSpec = quantization_config.weight + if quantization_spec.qscheme not in [ + torch.per_tensor_symmetric, + torch.per_channel_symmetric, + None, + ]: + raise ValueError( + f"Unsupported quantization_spec {quantization_spec} for weight" + ) + return quantization_spec + + +def get_bias_qspec(quantization_config: Optional[QuantizationConfig]): + if quantization_config is None: + return None + assert quantization_config is not None + if quantization_config.bias is None: + return None + quantization_spec: QuantizationSpec = quantization_config.bias + assert quantization_spec.dtype == torch.float, ( + "Only float dtype for bias is supported for bias right now" + ) + return quantization_spec + + +def annotate_input_qspec_map(node: Node, input_node: Node, qspec): + quantization_annotation = node.meta.get( + "quantization_annotation", QuantizationAnnotation() + ) + if quantization_annotation.input_qspec_map is None: + quantization_annotation.input_qspec_map = {} + quantization_annotation.input_qspec_map[input_node] = qspec + node.meta["quantization_annotation"] = quantization_annotation + + +def annotate_output_qspec(node: Node, qspec): + quantization_annotation = node.meta.get( + "quantization_annotation", QuantizationAnnotation() + ) + quantization_annotation.output_qspec = qspec + node.meta["quantization_annotation"] = quantization_annotation + + +def get_module_name_filter(module_name: str): + """Get the module_name_filter function for a given module name, the filter accepts + a node and checks if the node comes from a module that has certain module name + + For example: + node: linear_op = call_function[...](...) # comes from a module with name blocks.sub.linear1 + + + >> module_name_filter = _get_module_name_filter("blocks.sub") + >> print(module_name_filter(node)) + True # the node is from "blocks.sub" based on the fully qualified name "blocks.sub.linear1" + """ + + def module_name_filter(n: Node) -> bool: + # example: { + # 'L__self___sub': ("L['self'].sub", ), + # 'L__self___sub_linear': ("L['self'].sub.linear", ) + # } + # get_attr nodes doesn't have nn_module_stack? + nn_module_stack = n.meta.get("nn_module_stack", {}) + + def _normalize_path(n): + prefix = 0 + # TODO This is non standard behavior and should be removed when we migrate off capture_pre_autograd_graph. + if n.startswith("L['self']."): + prefix = len("L['self'].") + return n[prefix:] + + names = [_normalize_path(n) for n, _ in nn_module_stack.values()] + return module_name in names + + return module_name_filter + + +def is_valid_annotation(annotation: QuantizationAnnotation) -> bool: + if annotation is None: + return False + input_qspec_map = annotation.input_qspec_map + output_qspec = annotation.output_qspec + if len(input_qspec_map) == 0 and output_qspec is None: + return False + return True diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/x86_inductor_quantizer.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/x86_inductor_quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..84a66447c1fe6cf2190f0ba4b22d4df3a949784a --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/x86_inductor_quantizer.py @@ -0,0 +1,1641 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs +import functools +import itertools +import operator +import warnings +from collections.abc import Sequence +from dataclasses import dataclass +from typing import TYPE_CHECKING, Any, Callable, Optional, Union + +import torch +import torch.nn.functional as F +from torch.fx import Node +from torch.fx.passes.utils.source_matcher_utils import ( + SourcePartition, + get_source_partitions, +) +from typing_extensions import TypeAlias + +from torchao.quantization.pt2e import ( + FakeQuantize, + FusedMovingAvgObsFakeQuantize, + HistogramObserver, + MovingAverageMinMaxObserver, + MovingAveragePerChannelMinMaxObserver, + PerChannelMinMaxObserver, + PlaceholderObserver, + find_sequential_partitions, +) +from torchao.quantization.pt2e.quantizer import ( + QuantizationAnnotation, + QuantizationConfig, + QuantizationSpec, + Quantizer, + SharedQuantizationSpec, + get_bias_qspec, + get_input_act_qspec, + get_module_name_filter, + get_output_act_qspec, + get_weight_qspec, +) + +FilterFn: TypeAlias = Callable[[list[Node]], bool] + + +if TYPE_CHECKING: + from torchao.quantization.pt2e import ObserverOrFakeQuantizeConstructor + +__all__ = [ + "X86InductorQuantizer", + "get_default_x86_inductor_quantization_config", + "get_x86_inductor_linear_dynamic_fp16_config", +] + + +@dataclass +class _X86InductorQuantizationAnnotation(QuantizationAnnotation): + # _is_output_of_quantized_pattern: + # * Node as output node of a fusion pattern. + # * The fusion pattern supports int8 data type. + # * The fusion pattern has inputs annotated to insert observer. + # * The quantization_config is not `None`. + _is_output_of_quantized_pattern: bool = False + + +# Operators that: +# 1. Operators are optimized to run with int8 when int8 input provided. +# 2. Operators do not support int8 input and produce fp32 output. +int8_in_int8_out_ops: set = { + torch.ops.aten.max_pool2d.default, + torch.ops.aten.cat.default, + torch.ops.aten.avg_pool2d.default, + torch.ops.aten.adaptive_avg_pool2d.default, + torch.ops.aten.flatten.using_ints, +} + +# Operators that support the int8 data type for quantization config propagation. +# A superset of int8_in_int8_out_ops incorporating additional operators. +propagation_quantizable_ops = int8_in_int8_out_ops + +# Operators support the int8 data type +# and recipe is configured by default in X86InductorQuantizer. +default_quantizable_ops = propagation_quantizable_ops | { + torch.ops.aten.conv1d.default, + torch.ops.aten.conv2d.default, + torch.ops.aten.linear.default, + torch.ops.aten.mul.Tensor, +} + +# A superset of default_quantizable_ops includes operators support the int8 data type +# but not enabled by default recipe of X86InductorQuantizer. +quantizable_ops = default_quantizable_ops | { + torch.ops.aten.matmul.default, +} + +QUANT_ANNOTATION_KEY = "quantization_annotation" + + +def _skip_annotate(nodes: list[Node], filter_fn: Optional[FilterFn] = None) -> bool: + """Determine whether to skip annotation for a list of nodes.""" + + # 1) Skip annotate if any node is already annotated + if _is_any_annotated(nodes): + return True + + # 2) Proceed annotate if a) a filter function is provided + # and b) the given nodes list passes the filter function check. + if filter_fn and filter_fn(nodes): + return False + + return True + + +def _create_module_name_filter(module_name: str) -> FilterFn: + """Create a filter function for a given module name. + + The filter function takes a list of nodes (as determined by the annotate function) + and return True if *all* nodes come from the specified module name, False otherwise. + + For example: + linear_1: "f32[3, 10]" = torch.ops.aten.linear.default(...) # comes from a module with name `sub.linear1` + relu: "f32[3, 10]" = torch.ops.aten.relu.default(linear_1); # comes from a module with name `sub.relu1` + + >> module_name_filter = _create_module_name_filter_inner("sub") + >> print(module_name_filter([relu, linear_1])) + # True # These two nodes are determined by `_annotate_linear_unary` function and from "sub". + """ + + filter_fn = get_module_name_filter(module_name) + + def check_all_nodes_from_module(nodes: list[Node]) -> bool: + all_nodes_from_module_name: bool = all(filter_fn(n) for n in nodes) + return all_nodes_from_module_name + + return check_all_nodes_from_module + + +def _create_operator_type_filter( + operator_type: Callable, +) -> FilterFn: + """Create a filter function for a given operator type. + + The filter function takes a list of nodes and returns True if it contains + exactly one node with the specified operator type, False otherwise. + + For example: + linear_1: "f32[3, 10]" = torch.ops.aten.linear.default(...) # comes from a module with name `sub.linear1` + relu: "f32[3, 10]" = torch.ops.aten.relu.default(linear_1); # comes from a module with name `sub.relu1` + + >> operator_type_filter = _create_operator_type_filter(torch.ops.aten.linear.default) + >> print(operator_type_filter([relu, linear_1])) + # True # These two nodes are determined by `_annotate_linear_unary` function and the second node is `linear`. + """ + + def operator_type_filter(nodes: list[Node]): + num_nodes_with_operator_type = sum( + node.target == operator_type for node in nodes + ) + if num_nodes_with_operator_type > 1: + raise NotImplementedError( + f"Several nodes within a single pattern are {operator_type}." + ) + return num_nodes_with_operator_type == 1 + + return operator_type_filter + + +def _global_config_filter(nodes: list[Node]) -> bool: + """Filter function for global configuration. + + This filter function takes a list of nodes and returns True if there is exactly one node + in the list that is a default quantizable operation, False otherwise. + """ + num_nodes_in_default_quantizable_ops = sum( + node.target in default_quantizable_ops for node in nodes + ) + if num_nodes_in_default_quantizable_ops > 1: + raise NotImplementedError( + "Several nodes within a single pattern are default quantizable operations." + ) + return num_nodes_in_default_quantizable_ops == 1 + + +def _map_module_function_to_aten_operator_type(): + module_function_to_aten_operator: dict[Callable, torch._ops.OpOverloadPacket] = {} + map_list = ( + ([torch.nn.Conv2d, F.conv1d], torch.ops.aten.conv1d.default), + ([torch.nn.Conv2d, F.conv2d], torch.ops.aten.conv2d.default), + ([torch.nn.Linear, F.linear], torch.ops.aten.linear.default), + ([torch.nn.MaxPool2d, F.max_pool2d], torch.ops.aten.max_pool2d.default), + ( + [ + torch.cat, + ], + torch.ops.aten.cat.default, + ), + ([torch.nn.AvgPool2d, F.avg_pool2d], torch.ops.aten.avg_pool2d.default), + ( + [torch.nn.AdaptiveAvgPool2d, F.adaptive_avg_pool2d], + torch.ops.aten.adaptive_avg_pool2d.default, + ), + ( + [ + torch.flatten, + ], + torch.ops.aten.flatten.using_ints, + ), + ( + [ + torch.matmul, + ], + torch.ops.aten.matmul.default, + ), + ( + [ + torch.mul, + ], + torch.ops.aten.mul.Tensor, + ), + ) + for map_item in map_list: + module_function_to_aten_operator.update(dict.fromkeys(map_item[0], map_item[1])) # type: ignore[arg-type, call-overload] + return module_function_to_aten_operator + + +def _mark_nodes_as_annotated(nodes: list[Node]): + for node in nodes: + if node is not None: + if QUANT_ANNOTATION_KEY not in node.meta: + node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation() + node.meta[QUANT_ANNOTATION_KEY]._annotated = True + + +def _is_node_annotated(_node): + """ + return True if the node is annotated, otherwise return False + """ + return ( + QUANT_ANNOTATION_KEY in _node.meta + and _node.meta[QUANT_ANNOTATION_KEY]._annotated + ) + + +def _is_any_annotated(nodes: list[Node]): + """ + Given a list of nodes (that represents an operator pattern), + check if any of the node is annotated, return True if any of the node + is annotated, otherwise return False. + """ + return any(_is_node_annotated(node) for node in nodes) + + +def _is_all_annotated(nodes: list[Node]): + """ + Given a list of nodes (that represents an operator pattern), + return True if all of the node is annotated, otherwise return False. + """ + return all(_is_node_annotated(node) for node in nodes) + + +def _is_quantized_op_pt2e(node: torch.fx.Node): + """ + Used for pt2e flow to check if the node is a quantized node: + Case1: the node has been annotated as output node of a fusion pattern. + Case2: the node has been annotated as single quantized node. + """ + if not _is_any_annotated([node]): + # The node has not been annotated, directly return False + return False + quantization_annotation = node.meta.get(QUANT_ANNOTATION_KEY, None) + assert isinstance(quantization_annotation, _X86InductorQuantizationAnnotation) + return quantization_annotation._is_output_of_quantized_pattern + + +@functools.lru_cache +def get_default_x86_inductor_quantization_config( + is_qat: bool = False, + is_dynamic: bool = False, + reduce_range: bool = False, +): + """ + reduce_range is False by default. Set it to True on earlier CPUs without VNNI to avoid accuracy issue. + """ + extra_args: dict[str, Any] = {"eps": 2**-12} + if is_qat: + if is_dynamic: + act_observer_or_fake_quant_ctr = FakeQuantize + dynamic_quant_observer = MovingAverageMinMaxObserver.with_args( + averaging_constant=1 + ) + extra_args["observer"] = dynamic_quant_observer + else: + act_observer_or_fake_quant_ctr = FusedMovingAvgObsFakeQuantize # type: ignore[assignment] + else: + if is_dynamic: + act_observer_or_fake_quant_ctr = PlaceholderObserver # type: ignore[assignment] + else: + act_observer_or_fake_quant_ctr = HistogramObserver # type: ignore[assignment] + + # Copy from x86 default qconfig from torch/ao/quantization/qconfig.py + act_quantization_spec = QuantizationSpec( + dtype=torch.uint8, + quant_min=0, + quant_max=127 if reduce_range else 255, + qscheme=torch.per_tensor_affine, + is_dynamic=is_dynamic, + observer_or_fake_quant_ctr=act_observer_or_fake_quant_ctr.with_args( + **extra_args + ), + ) + + weight_observer_or_fake_quant_ctr: ObserverOrFakeQuantizeConstructor = ( + FusedMovingAvgObsFakeQuantize if is_qat else PerChannelMinMaxObserver + ) + + if is_qat: + # Only support per channel quant for now + extra_args["observer"] = MovingAveragePerChannelMinMaxObserver # type: ignore[dict-item] + weight_quantization_spec = QuantizationSpec( + dtype=torch.int8, + quant_min=-128, + quant_max=127, + qscheme=torch.per_channel_symmetric, + ch_axis=0, # 0 corresponding to weight shape = (oc, ic, kh, kw) of conv + is_dynamic=False, + observer_or_fake_quant_ctr=weight_observer_or_fake_quant_ctr.with_args( + **extra_args + ), + ) + bias_quantization_spec = None # will use placeholder observer by default + quantization_config = QuantizationConfig( + act_quantization_spec, + act_quantization_spec, + weight_quantization_spec, + bias_quantization_spec, + is_qat, + ) + return quantization_config + + +@functools.lru_cache +def get_x86_inductor_linear_dynamic_fp16_config(): + """ + For linear_dynamic_fp16. The name may be confusing. + The op's behavior is fp32_input * (fp16_weight -> to_fp32) -> fp32_output. + """ + weight_quantization_spec = QuantizationSpec( + dtype=torch.float16, + observer_or_fake_quant_ctr=PlaceholderObserver, + ) + quantization_config = QuantizationConfig( + None, # input_quantization_spec + None, # output_quantization_spec + weight_quantization_spec, + None, # bias_quantization_spec + ) + return quantization_config + + +def _annotate_nodes_not_quantize(nodes: Union[Node, list[Node]]) -> None: + """Annotate nodes to exclude them from quantization (their `quantization_config` is `None`).""" + if not isinstance(nodes, list): + nodes = [nodes] + for node in nodes: + node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + _annotated=True + ) + + +def _config_checker(method: Callable) -> Callable: + @functools.wraps(method) + def wrapper( + quantizer: "X86InductorQuantizer", + name: Any, + quantization_config: Optional["QuantizationConfig"], + ) -> "X86InductorQuantizer": + if quantizer._need_skip_config(quantization_config): + warnings.warn( + f"Skip the quantization config for {name}.", + ) + return quantizer + return method(quantizer, name, quantization_config) + + return wrapper + + +@dataclass +class _CurrentQuantizationMode: + r"""Configuration defining the current quantization mode for the quantizer. + + All possible current quantization modes are listed below: + ---------------------------------------------------------------------------------------------------------- + | dynamic_state + qat_state |--------------------------------------------------------------------------------------------- + | None | True | False + ---------------------------------------------------------------------------------------------------------- + None | quantizer does not receive a non-None `quantization_config` | \ | \ + False | quantizer will not do QAT | dynamic | static + True | quantizer will do QAT | QAT + dynamic | QAT + static + """ + + qat_state: Optional[bool] + dynamic_state: Optional[bool] + + +class X86InductorQuantizer(Quantizer): + module_function_to_aten_operator_type = _map_module_function_to_aten_operator_type() + + def __init__(self) -> None: + super().__init__() + self.global_config: Optional[QuantizationConfig] = None + self.operator_type_qconfig: dict[ + torch._ops.OpOverloadPacket, Optional[QuantizationConfig] + ] = {} + self.module_name_qconfig: dict[str, Optional[QuantizationConfig]] = {} + + def _get_current_quantization_mode(self) -> _CurrentQuantizationMode: + """Retrieves the current quantization mode based on all configurations.""" + qat_state = None + dynamic_state = None + + # As we use `_need_skip_config` to skip all invalid configurations, + # we can safely assume that the all existing non-None configurations + # have the same quantization mode. + for qconfig in ( + list(self.module_name_qconfig.values()) + + list(self.operator_type_qconfig.values()) + + [self.global_config] + ): + if qconfig is not None: + # Query the `is_qat` state + if qat_state is None: + qat_state = qconfig.is_qat + else: + assert qat_state == qconfig.is_qat, ( + f"All non-None quantization configs should have the same `is_qat`," + f"but got {qat_state} and {qconfig.is_qat}." + ) + # Query the `is_dynamic` state + input_activation_spec = qconfig.input_activation + if input_activation_spec is not None: + if dynamic_state is None: + dynamic_state = input_activation_spec.is_dynamic + else: + assert dynamic_state == input_activation_spec.is_dynamic, ( + f"All non-None `input_activation_spec` should have the same `is_dynamic`," + f"but got {dynamic_state} and {input_activation_spec.is_dynamic}." + ) + return _CurrentQuantizationMode( + qat_state=qat_state, dynamic_state=dynamic_state + ) + + def _need_skip_config( + self, quantization_config: Optional[QuantizationConfig] + ) -> bool: + """Check if the provided quantization config is valid for X86InductorQuantizer. + + Mixed static/dynamic configurations or mixed QAT/non-QAT configurations are not supported. + To avoid such a mix, we compare the incoming configuration with current configuration status. + Refer the `_CurrentQuantizationMode` definition for all possible modes. + """ + if quantization_config is None: + return False + + need_skip = False + current_mode = self._get_current_quantization_mode() + if ( + current_mode.qat_state is not None + and current_mode.qat_state != quantization_config.is_qat + ): + warnings.warn("Mixed QAT and Non-QAT quantization config is not supported.") + need_skip = True + if current_mode.dynamic_state is not None: + input_activation_spec = quantization_config.input_activation + if ( + input_activation_spec is not None + and current_mode.dynamic_state != input_activation_spec.is_dynamic + ): + warnings.warn( + "Mixed dynamic and static quantization config is not supported." + ) + need_skip = True + return need_skip + + def set_global(self, quantization_config: QuantizationConfig): + if self._need_skip_config(quantization_config): + warnings.warn("Skip the global quantization config.") + return self + self.global_config = quantization_config + return self + + def get_global_quantization_config(self): + if not isinstance(self.global_config, QuantizationConfig): + warnings.warn( + "The global_config for X86InductorQuantizer is currently invalid. \ + Please ensure that you use set_global to establish the global quantization configuration." + ) + return self.global_config + + @_config_checker + def set_function_type_qconfig( + self, + function_type: Callable, + quantization_config: Optional[QuantizationConfig], + ) -> "X86InductorQuantizer": + if function_type in X86InductorQuantizer.module_function_to_aten_operator_type: + self._set_aten_operator_qconfig( + X86InductorQuantizer.module_function_to_aten_operator_type[ + function_type + ], + quantization_config, + ) + else: + warnings.warn( + f"function: Unable to customize quantization config for {function_type} by X86InductorQuantizer." + ) + return self + + @_config_checker + def set_module_type_qconfig( + self, + module_type: torch.nn.Module, + quantization_config: Optional[QuantizationConfig], + ) -> "X86InductorQuantizer": + if module_type in X86InductorQuantizer.module_function_to_aten_operator_type: + self._set_aten_operator_qconfig( + X86InductorQuantizer.module_function_to_aten_operator_type[module_type], + quantization_config, + ) + else: + warnings.warn( + f"Module: Unable to customize quantization config for {module_type} by X86InductorQuantizer." + ) + return self + + @_config_checker + def set_module_name_qconfig( + self, module_name: str, quantization_config: Optional[QuantizationConfig] + ): + """Set quantization_config for a submodule with name: `module_name`, for example: + quantizer.set_module_name_qconfig("blocks.sub"), it will quantize all supported operator/operator + patterns in the submodule with this module name with the given `quantization_config` + + The supported operators include `quantizable_ops` and `propagation_quantizable_ops`. + """ + self.module_name_qconfig[module_name] = quantization_config + return self + + def _set_aten_operator_qconfig( + self, + operator_type: torch._ops.OpOverloadPacket, + quantization_config: Optional[QuantizationConfig], + ) -> "X86InductorQuantizer": + if operator_type in quantizable_ops: + self.operator_type_qconfig[operator_type] = quantization_config + else: + warnings.warn( + f"operator: Unable to quantize {operator} by X86InductorQuantizer." + ) + return self + + def _annotate_conv_node_helper( + self, + conv_node: torch.fx.Node, + annotate_output: bool, + quantization_config: Optional[QuantizationConfig], + ) -> None: + """Helper function to annotate the conv node""" + if quantization_config is None: + _annotate_nodes_not_quantize(conv_node) + return + input_qspec_map = {} + input_node = conv_node.args[0] + assert isinstance(input_node, Node) + input_qspec_map[input_node] = get_input_act_qspec(quantization_config) + weight_node = conv_node.args[1] + assert isinstance(weight_node, Node) + input_qspec_map[weight_node] = get_weight_qspec(quantization_config) + bias_node = None if len(conv_node.args) == 2 else conv_node.args[2] + if isinstance(bias_node, Node): + input_qspec_map[bias_node] = get_bias_qspec(quantization_config) + if annotate_output: + conv_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + else: + conv_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + ) + + def _annotate_linear_node_helper( + self, + linear_node: torch.fx.Node, + annotate_output: bool, + quantization_config: Optional[QuantizationConfig], + ) -> None: + """Helper function to annotate the linear node""" + if quantization_config is None: + _annotate_nodes_not_quantize(linear_node) + return + input_qspec_map = {} + assert linear_node.target in (torch.ops.aten.linear.default,) + has_bias = len(linear_node.args) == 3 + input_index = 0 + weight_index = 1 + bias_index = 2 + + input_node = linear_node.args[input_index] + assert isinstance(input_node, Node) + input_qspec_map[input_node] = get_input_act_qspec(quantization_config) + + weight_node = linear_node.args[weight_index] + assert isinstance(weight_node, Node) + input_qspec_map[weight_node] = get_weight_qspec(quantization_config) + + bias_node = linear_node.args[bias_index] if has_bias else None + if isinstance(bias_node, Node): + input_qspec_map[bias_node] = get_bias_qspec(quantization_config) + + if annotate_output: + linear_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + else: + linear_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=input_qspec_map, _annotated=True + ) + + def _get_output_nodes_of_partitions( + self, + partition_list: list[SourcePartition], + ) -> list[torch.fx.Node]: + """Helper function to get the output node list from partition list""" + output_node_list = [] + for partition in partition_list: + if len(partition.output_nodes) > 1: + raise ValueError("Input partition has more than one output node") + output_node = partition.output_nodes[0] + assert isinstance(output_node, Node) + output_node_list.append(output_node) + if len(output_node_list) != len(partition_list): + raise ValueError( + "length of output_node_list should equal to length of partition_list" + ) + return output_node_list + + def _get_input_idx_for_binary_node( + self, + conv_gemm_node: torch.fx.Node, + binary_node: torch.fx.Node, + ): + """Helper function to check conv_gemm and extra input node index + for binary node fused with conv_gemm. + """ + conv_gemm_node_idx = None + extra_input_node_idx = None + if (binary_node.args[0].op == "call_function") and ( # type: ignore[union-attr] + binary_node.args[0] == conv_gemm_node + ): + conv_gemm_node_idx = 0 + extra_input_node_idx = 1 + elif (binary_node.args[1].op == "call_function") and ( # type: ignore[union-attr] + binary_node.args[1] == conv_gemm_node + ): + conv_gemm_node_idx = 1 + extra_input_node_idx = 0 + extra_input_node = binary_node.args[extra_input_node_idx] # type: ignore[index] + assert isinstance(extra_input_node, Node) + return conv_gemm_node_idx, extra_input_node_idx + + def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule: + """Annotate the given model with quantization configurations. + + Annotation contracts: + 1. Annotate each node according to the user's qconfig in the following order: + `module_name_qconfig`, `operator_type_qconfig`, and `global_config`. + 2. Avoid re-annotating nodes already annotated in prior stages. For example, + if `linear1` has been annotated by `module_name_qconfig`, it won't be annotated again + during the processing of the 'operator_type_qconfig' or 'global_config'. + 3. For config is `None`, the node will be annotated with `_X86InductorQuantizationAnnotation(_annotated=True)`. + + For each pair of (module_name_or_operator_type_or_global, qconfig), a filter function is created. + This filter function checks if the node is marked by current stage and not annotated by the previous stage. + """ + for module_name, quantization_config in self.module_name_qconfig.items(): + self._annotate_with_config( + model, quantization_config, _create_module_name_filter(module_name) + ) + + for operator_type, quantization_config in self.operator_type_qconfig.items(): + self._annotate_with_config( + model, quantization_config, _create_operator_type_filter(operator_type) + ) + + if self.global_config: + self._annotate_with_config( + model, + self.global_config, + _global_config_filter, + ) + + # Once we've annotated the model with quantization configurations, we also need to annotate + # the output of quantizable operations. For example, if we annotated `maxpool2d` to quantize its inputs, + # we will quantize its output accordingly. This enables us to fuse the dq-operator-q into a quantized op. + # Refer to https://github.com/intel/intel-extension-for-pytorch/blob/ + # 90d19323d96afc53fcc22ba5a7bb3fb07fdd6c1c/intel_extension_for_pytorch/quantization/_recipe.py#L487 + + self._annotate_output_for_int8_in_int8_out_pattern_entry(model) + + return model + + def _annotate_with_config( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: FilterFn, + ) -> None: + """Annotate the model with the given quantization configuration. + + High-level description of quantization recipe for X86 Inductor Backend: + Step 1: Apply quantization recipe for fusion patterns of conv/linear to enable int8 data type actively. + Step 2: Propagate quantization annotation for patterns besides conv/linear. Go through the pattern in model + from start to the end. If a pattern supports computation with int8 data type and inputs connected to + quantized patterns, annotate its inputs as quantized pattern. + """ + + # Step1: Recipe of fusion patterns like conv/linear. + self._annotate_conv2d_fusion_pattern(model, quantization_config, filter_fn) + self._annotate_linear_fusion_pattern(model, quantization_config, filter_fn) + self._annotate_matmul(model, quantization_config, filter_fn) + self._annotate_mul_tensor(model, quantization_config, filter_fn) + + # Step2: Recipe to propagate annotation for patterns beside conv/linear. + # Go through all the nodes from start to end. + # Recipe refer to https://github.com/intel/intel-extension-for-pytorch/blob/ + # 90d19323d96afc53fcc22ba5a7bb3fb07fdd6c1c/intel_extension_for_pytorch/quantization/_recipe.py#L538 + + self._annotate_propagation_quantizable_pattern_entry( + model, quantization_config, filter_fn + ) + + def _annotate_qat_conv2d_fusion_pattern( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ): + # Annotate QAT Specific patterns + self._annotate_qat_conv2d_bn_binary_unary(model, quantization_config, filter_fn) + self._annotate_qat_conv2d_bn_binary(model, quantization_config, filter_fn) + self._annotate_qat_conv2d_bn_unary(model, quantization_config, filter_fn) + self._annotate_qat_conv2d_bn(model, quantization_config, filter_fn) + + def _annotate_qat_conv2d_bn_binary_unary( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + fused_partitions = find_sequential_partitions( + gm, [torch.nn.Conv2d, torch.nn.BatchNorm2d, operator.add, torch.nn.ReLU] + ) + for fused_partition in fused_partitions: + ( + conv_partition, + bn_partition, + binary_partition, + unary_partition, + ) = fused_partition + + ( + conv_node, + bn_output_node, + binary_node, + unary_node, + ) = self._get_output_nodes_of_partitions( + [conv_partition, bn_partition, binary_partition, unary_partition] + ) + if len(bn_output_node.users) != 1: + # Conv BN pattern should only has 1 user. + continue + ( + bn_output_node_idx, + extra_input_node_idx, + ) = self._get_input_idx_for_binary_node(bn_output_node, binary_node) + if (bn_output_node_idx is None) or (extra_input_node_idx is None): + continue + if bn_output_node != binary_node.args[bn_output_node_idx]: + raise ValueError(f"{bn_output_node} doesn't match input of binary node") + extra_input_node = binary_node.args[extra_input_node_idx] + + if ( + conv_node.op != "call_function" + or conv_node.target != torch.ops.aten.conv2d.default + ): + continue + + if _skip_annotate( + [unary_node, binary_node, bn_output_node, conv_node], filter_fn + ): + continue + + self._annotate_conv_node_helper(conv_node, False, quantization_config) + + if quantization_config is not None: + binary_node_input_qspec_map = {} + binary_node_input_qspec_map[extra_input_node] = get_input_act_qspec( + quantization_config + ) + binary_node.meta[QUANT_ANNOTATION_KEY] = ( + _X86InductorQuantizationAnnotation( + input_qspec_map=binary_node_input_qspec_map, + _annotated=True, + ) + ) + unary_node.meta[QUANT_ANNOTATION_KEY] = ( + _X86InductorQuantizationAnnotation( + # TODO Remove the annotate of output in QAT when qat util support pattern matcher. + output_qspec=get_output_act_qspec(quantization_config), # type: ignore[arg-type] + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + ) + else: + _annotate_nodes_not_quantize([binary_node, unary_node]) + nodes_to_mark_annotated = list(conv_partition.nodes) + nodes_to_mark_annotated.extend(list(bn_partition.nodes)) + nodes_to_mark_annotated.extend(list(binary_partition.nodes)) + nodes_to_mark_annotated.extend(list(unary_partition.nodes)) + _mark_nodes_as_annotated(nodes_to_mark_annotated) + + def _annotate_qat_conv2d_bn_binary( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + fused_partitions = find_sequential_partitions( + gm, [torch.nn.Conv2d, torch.nn.BatchNorm2d, operator.add] + ) + for fused_partition in fused_partitions: + conv_partition, bn_partition, binary_partition = fused_partition + ( + conv_node, + bn_output_node, + binary_node, + ) = self._get_output_nodes_of_partitions( + [conv_partition, bn_partition, binary_partition] + ) + if len(bn_output_node.users) != 1: + # Conv BN pattern should only has 1 user. + continue + ( + bn_output_node_idx, + extra_input_node_idx, + ) = self._get_input_idx_for_binary_node(bn_output_node, binary_node) + if (bn_output_node_idx is None) or (extra_input_node_idx is None): + continue + if bn_output_node != binary_node.args[bn_output_node_idx]: + raise ValueError(f"{bn_output_node} doesn't match input of binary node") + + extra_input_node = binary_node.args[extra_input_node_idx] + + if ( + conv_node.op != "call_function" + or conv_node.target != torch.ops.aten.conv2d.default + ): + continue + + if _skip_annotate([binary_node, bn_output_node, conv_node], filter_fn): + continue + + self._annotate_conv_node_helper(conv_node, False, quantization_config) + + if quantization_config is not None: + binary_node_input_qspec_map = {} + binary_node_input_qspec_map[extra_input_node] = get_input_act_qspec( + quantization_config + ) + binary_node.meta[QUANT_ANNOTATION_KEY] = ( + _X86InductorQuantizationAnnotation( + input_qspec_map=binary_node_input_qspec_map, + # TODO Remove the annotate of output in QAT when qat util support pattern matcher. + output_qspec=get_output_act_qspec(quantization_config), # type: ignore[arg-type] + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + ) + else: + _annotate_nodes_not_quantize(binary_node) + nodes_to_mark_annotated = list(conv_partition.nodes) + nodes_to_mark_annotated.extend(list(bn_partition.nodes)) + nodes_to_mark_annotated.extend(list(binary_partition.nodes)) + _mark_nodes_as_annotated(nodes_to_mark_annotated) + + def _annotate_qat_conv2d_bn_unary( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + fused_partitions = [] + unary_patterns = [ + [torch.nn.Conv2d, torch.nn.BatchNorm2d, torch.nn.ReLU], + [torch.nn.Conv2d, torch.nn.BatchNorm2d, torch.nn.Hardtanh], + [torch.nn.Conv2d, torch.nn.BatchNorm2d, torch.nn.Hardswish], + [torch.nn.Conv2d, torch.nn.BatchNorm2d, torch.nn.ReLU6], + [torch.nn.Conv2d, torch.nn.BatchNorm2d, torch.nn.SiLU], + ] + for unary_pattern in unary_patterns: + partitions = find_sequential_partitions(gm, unary_pattern) + if partitions: + # Extend the fused_partitions if partitions is not empty + fused_partitions.extend(partitions) + + for fused_partition in fused_partitions: + conv_partition, bn_partition, unary_partition = fused_partition + ( + conv_node, + bn_output_node, + unary_node, + ) = self._get_output_nodes_of_partitions( + [conv_partition, bn_partition, unary_partition] + ) + + if ( + conv_node.op != "call_function" + or conv_node.target != torch.ops.aten.conv2d.default + ): + continue + + if _skip_annotate([unary_node, bn_output_node, conv_node], filter_fn): + continue + + self._annotate_conv_node_helper(conv_node, False, quantization_config) + if quantization_config is not None: + unary_node.meta[QUANT_ANNOTATION_KEY] = ( + _X86InductorQuantizationAnnotation( + # TODO Remove the annotate of output in QAT when qat util support pattern matcher. + output_qspec=get_output_act_qspec(quantization_config), # type: ignore[arg-type] + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + ) + else: + _annotate_nodes_not_quantize(unary_node) + nodes_to_mark_annotated = list(conv_partition.nodes) + nodes_to_mark_annotated.extend(list(bn_partition.nodes)) + nodes_to_mark_annotated.extend(list(unary_partition.nodes)) + _mark_nodes_as_annotated(nodes_to_mark_annotated) + + def _annotate_qat_conv2d_bn( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + fused_partitions = find_sequential_partitions( + gm, [torch.nn.Conv2d, torch.nn.BatchNorm2d] + ) + for fused_partition in fused_partitions: + conv_partition, bn_partition = fused_partition + conv_node, bn_output_node = self._get_output_nodes_of_partitions( + [conv_partition, bn_partition] + ) + + if ( + conv_node.op != "call_function" + or conv_node.target != torch.ops.aten.conv2d.default + ): + continue + + if _skip_annotate([bn_output_node, conv_node], filter_fn): + continue + + self._annotate_conv_node_helper(conv_node, False, quantization_config) + if quantization_config is not None: + bn_output_node.meta[QUANT_ANNOTATION_KEY] = ( + _X86InductorQuantizationAnnotation( + # TODO Remove the annotate of output in QAT when qat util support pattern matcher. + output_qspec=get_output_act_qspec(quantization_config), # type: ignore[arg-type] + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + ) + else: + _annotate_nodes_not_quantize(bn_output_node) + nodes_to_mark_annotated = list(conv_partition.nodes) + nodes_to_mark_annotated.extend(list(bn_partition.nodes)) + _mark_nodes_as_annotated(nodes_to_mark_annotated) + + def _annotate_conv2d_fusion_pattern( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ): + if (quantization_config is None) or (quantization_config.is_qat): + # Annotate QAT specific pattern: mainly due to BN not folded in prepare_qat + self._annotate_qat_conv2d_fusion_pattern( + model, quantization_config, filter_fn + ) + self._annotate_conv2d_binary_unary(model, quantization_config, filter_fn) + self._annotate_conv2d_binary(model, quantization_config, filter_fn) + self._annotate_conv2d_unary(model, quantization_config, filter_fn) + self._annotate_conv2d(model, quantization_config, filter_fn) + + def _annotate_linear_fusion_pattern( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ): + self._annotate_linear_binary_unary(model, quantization_config, filter_fn) + self._annotate_linear_unary(model, quantization_config, filter_fn) + self._annotate_linear(model, quantization_config, filter_fn) + + def _annotate_matmul( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ): + for node in model.graph.nodes: + if node.target != torch.ops.aten.matmul.default: + continue + if _skip_annotate([node], filter_fn): + continue + + if quantization_config is None: + _annotate_nodes_not_quantize(node) + continue + + input_qspec_map = {} + matmul_node = node + for input_node in matmul_node.args: + input_qspec_map[input_node] = get_input_act_qspec(quantization_config) + matmul_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + + def _annotate_conv2d_binary_unary( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + # Conv2d + add + unary op + fused_partitions = find_sequential_partitions( + gm, [torch.nn.Conv2d, operator.add, torch.nn.ReLU] + ) + for fused_partition in fused_partitions: + conv_partition, binary_partition, unary_partition = fused_partition + conv_node, binary_node, unary_node = self._get_output_nodes_of_partitions( + [conv_partition, binary_partition, unary_partition] + ) + if len(conv_node.users) != 1: + # Conv Node should only has 1 user node + continue + conv_node_idx, extra_input_node_idx = self._get_input_idx_for_binary_node( + conv_node, binary_node + ) + if (conv_node_idx is None) or (extra_input_node_idx is None): + continue + if conv_node != binary_node.args[conv_node_idx]: + raise ValueError(f"{conv_node} doesn't match input of binary node") + extra_input_node = binary_node.args[extra_input_node_idx] + if ( + conv_node.op != "call_function" + or conv_node.target != torch.ops.aten.conv2d.default + ): + # No conv node found to be fused with add + continue + if _skip_annotate([unary_node, binary_node, conv_node], filter_fn): + continue + + if quantization_config is None: + _annotate_nodes_not_quantize([conv_node, binary_node, unary_node]) + continue + + self._annotate_conv_node_helper(conv_node, False, quantization_config) + binary_node_input_qspec_map = {} + binary_node_input_qspec_map[extra_input_node] = get_input_act_qspec( + quantization_config + ) + binary_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=binary_node_input_qspec_map, + _annotated=True, + ) + unary_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + + def _annotate_conv2d_binary( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + # Conv2d + add + fused_partitions = find_sequential_partitions( + gm, [torch.nn.Conv2d, operator.add] + ) + for fused_partition in fused_partitions: + conv_partition, binary_partition = fused_partition + conv_node, binary_node = self._get_output_nodes_of_partitions( + [conv_partition, binary_partition] + ) + if len(conv_node.users) != 1: + # Conv Node should only has 1 user node + continue + conv_node_idx, extra_input_node_idx = self._get_input_idx_for_binary_node( + conv_node, binary_node + ) + if (conv_node_idx is None) or (extra_input_node_idx is None): + continue + if conv_node != binary_node.args[conv_node_idx]: + raise ValueError(f"{conv_node} doesn't match input of binary node") + extra_input_node = binary_node.args[extra_input_node_idx] + assert isinstance(conv_node, Node) + if ( + conv_node.op != "call_function" + or conv_node.target != torch.ops.aten.conv2d.default + ): + # No conv node found to be fused with add + continue + if _skip_annotate([binary_node, conv_node], filter_fn): + continue + + if quantization_config is None: + _annotate_nodes_not_quantize([conv_node, binary_node]) + continue + + self._annotate_conv_node_helper(conv_node, False, quantization_config) + binary_node_input_qspec_map = {} + binary_node_input_qspec_map[extra_input_node] = get_input_act_qspec( + quantization_config + ) + binary_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=binary_node_input_qspec_map, + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + + def _annotate_conv2d_unary( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + fused_partitions = [] + unary_patterns = [ + [torch.nn.Conv2d, torch.nn.ReLU], + [torch.nn.Conv2d, torch.nn.Hardtanh], + [torch.nn.Conv2d, torch.nn.Hardswish], + [torch.nn.Conv2d, torch.nn.ReLU6], + [torch.nn.Conv2d, torch.nn.SiLU], + [torch.nn.Conv1d, torch.nn.ReLU], + ] + for unary_pattern in unary_patterns: + partitions = find_sequential_partitions(gm, unary_pattern) + if partitions: + # Extend the fused_partitions if partitions is not empty + fused_partitions.extend(partitions) + + for fused_partition in fused_partitions: + conv_partition, unary_partition = fused_partition + conv_node, unary_node = self._get_output_nodes_of_partitions( + [conv_partition, unary_partition] + ) + if conv_node.op != "call_function" or conv_node.target not in ( + torch.ops.aten.conv2d.default, + torch.ops.aten.conv1d.default, + ): + continue + if _skip_annotate([unary_node, conv_node], filter_fn): + continue + + if quantization_config is None: + _annotate_nodes_not_quantize([conv_node, unary_node]) + continue + + self._annotate_conv_node_helper(conv_node, False, quantization_config) + unary_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + + def _annotate_conv2d( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + conv_partitions = get_source_partitions( + gm.graph, [torch.nn.Conv2d, torch.nn.functional.conv2d] + ) + conv_partitions = list(itertools.chain.from_iterable(conv_partitions.values())) + for conv_partition in conv_partitions: + if len(conv_partition.output_nodes) > 1: + raise ValueError("conv partition has more than one output node") + conv_node = conv_partition.output_nodes[0] + if ( + conv_node.op != "call_function" + or conv_node.target != torch.ops.aten.conv2d.default + ): + raise ValueError(f"{conv_node} is not an aten conv2d operator") + # skip annotation if it is already annotated + if _skip_annotate([conv_node], filter_fn): + continue + self._annotate_conv_node_helper(conv_node, True, quantization_config) + + def _annotate_maxpool2d( + self, + node: Node, + quantization_config: Optional[QuantizationConfig], + ) -> None: + if node.target is not torch.ops.aten.max_pool2d.default: + return + if quantization_config is None: + _annotate_nodes_not_quantize(node) + return + + maxpool_node = node + if _is_any_annotated( + [ + maxpool_node, + ] + ): + return + + input_node = maxpool_node.args[0] + assert isinstance(input_node, Node) + input_qspec_map = {} + input_qspec_map[input_node] = get_input_act_qspec(quantization_config) + maxpool_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + + def _annotate_cat( + self, node: Node, quantization_config: QuantizationConfig + ) -> None: + if quantization_config is None: + _annotate_nodes_not_quantize(node) + return + cat_node = node + input_nodes = cat_node.args[0] + assert isinstance(input_nodes, Sequence) + first_input_node = input_nodes[0] + input_qspec_map = {} + assert isinstance(first_input_node, Node) + assert isinstance(cat_node, Node) + input_qspec_map[first_input_node] = get_input_act_qspec(quantization_config) + share_qparams_with_input_act0_qspec = SharedQuantizationSpec( + (first_input_node, cat_node) + ) + + for input_node in input_nodes[1:]: + if input_node not in input_qspec_map: + # There has the case of cat same nodes: torch.cat([input0, input0], 1) + assert isinstance(input_node, Node) + input_qspec_map[input_node] = share_qparams_with_input_act0_qspec + + cat_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + + def _annotate_propagation_quantizable_pattern_entry( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ): + for node in gm.graph.nodes: + self._annotate_propagation_quantizable_pattern( + node, quantization_config, filter_fn + ) + + def _annotate_propagation_quantizable_pattern( + self, node: Node, quantization_config, filter_fn + ) -> None: + # Propagate annotation to quantizable patterns. + if ( + (node.target in propagation_quantizable_ops) + and (not _is_any_annotated([node])) + and (node.op == "call_function") + ): + + def is_all_inputs_connected_to_quantized_op(input_nodes): + # Ensure all the inputs connect to fusion pattern or quantized node + for input_node in input_nodes: + if not _is_quantized_op_pt2e(input_node): + return False + return True + + if _skip_annotate([node], filter_fn): + return + + if quantization_config is None: + _annotate_nodes_not_quantize(node) + return + + if node.target is torch.ops.aten.max_pool2d.default: + # Recipe of maxpool2d: check input arg[0] of maxpool2d is quantized or not + input_nodes_to_check = [node.all_input_nodes[0]] + if not is_all_inputs_connected_to_quantized_op(input_nodes_to_check): + if quantization_config is not None: + warnings.warn( + f"The input of maxpool2d is not quantized, skip annotate maxpool2d with config {quantization_config}." + ) + return + + self._annotate_maxpool2d(node, quantization_config) + return + elif node.target is torch.ops.aten.cat.default: + input_nodes_to_check = node.all_input_nodes + if not is_all_inputs_connected_to_quantized_op(input_nodes_to_check): + return + self._annotate_cat(node, quantization_config) + elif ( + node.target is torch.ops.aten.flatten.using_ints + and len(node.users) > 0 + and not any( + user.target in quantizable_ops for user in node.users.keys() + ) + ): + # Recipe of flatten: check if any users of flatten node are quantizable ops or not + return + else: + input_node = node.all_input_nodes[0] + if not is_all_inputs_connected_to_quantized_op( + [ + input_node, + ] + ): + return + input_qspec_map = {} + input_qspec_map[input_node] = get_input_act_qspec(quantization_config) + node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + return + + def _annotate_output_share_observer_as_input( + self, input_node: Node, source_node: Node + ): + source_node_quantization_annotation = ( + source_node.meta[QUANT_ANNOTATION_KEY] + if QUANT_ANNOTATION_KEY in source_node.meta + else None + ) + if ( + source_node_quantization_annotation + and source_node_quantization_annotation._is_output_of_quantized_pattern + ): + edge_or_node = (input_node, source_node) + source_node_quantization_annotation.output_qspec = SharedQuantizationSpec( + edge_or_node + ) + return + + def _annotate_output_for_int8_in_int8_out_pattern_entry( + self, + model: torch.fx.GraphModule, + ): + for node in model.graph.nodes: + self._annotate_output_for_int8_in_int8_out_pattern(node) + + def _annotate_output_for_int8_in_int8_out_pattern( + self, + node: Node, + ) -> None: + r""" + Check and insert observer at output of node in int8_in_int8_out_ops if needed. + Recipe refers to https://github.com/intel/intel-extension-for-pytorch/blob/ + 90d19323d96afc53fcc22ba5a7bb3fb07fdd6c1c/intel_extension_for_pytorch/quantization/_utils.py#L495 + """ + edge_or_node: tuple[Node, Node] + if (node.target in int8_in_int8_out_ops) and (_is_any_annotated([node])): + if node.target == torch.ops.aten.max_pool2d.default: + maxpool_node = node + if not _is_all_annotated( + [ + maxpool_node, + ] + ): + return + + # Get the quantization_annotation from getitem_node + maxpool_node_quantization_annotation = ( + maxpool_node.meta[QUANT_ANNOTATION_KEY] + if QUANT_ANNOTATION_KEY in maxpool_node.meta + else None + ) + if ( + maxpool_node_quantization_annotation + and maxpool_node_quantization_annotation._is_output_of_quantized_pattern + ): + # Annotate the output_qspec of getitem_node + input_act = maxpool_node.args[0] + assert isinstance(input_act, Node) + assert isinstance(maxpool_node, Node) + edge_or_node = (input_act, maxpool_node) + maxpool_node_quantization_annotation.output_qspec = ( + SharedQuantizationSpec(edge_or_node) + ) + else: + input_node = node.all_input_nodes[0] + self._annotate_output_share_observer_as_input(input_node, node) + return + + def _annotate_linear( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + linear_partitions = get_source_partitions( + gm.graph, [torch.nn.Linear, torch.nn.functional.linear] + ) + linear_partitions = list( + itertools.chain.from_iterable(linear_partitions.values()) + ) + for partition in linear_partitions: + if len(partition.output_nodes) > 1: + raise ValueError( + "Linear partition cannot have more than one output node" + ) + linear_node = partition.output_nodes[0] + if linear_node.op != "call_function" or linear_node.target not in ( + torch.ops.aten.linear.default, + ): + raise ValueError(f"{linear_node} is not an aten linear operator") + # skip annotation if it is already annotated + if _skip_annotate([linear_node], filter_fn): + continue + self._annotate_linear_node_helper(linear_node, True, quantization_config) + + def _annotate_linear_unary( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + postop_list = [ + torch.nn.ReLU, + torch.nn.LeakyReLU, + torch.nn.Tanh, + torch.nn.GELU, + ] + fused_partitions: list[tuple] = [] + for postop in postop_list: + fused_partitions = fused_partitions + find_sequential_partitions( + gm, [torch.nn.Linear, postop] + ) + for fused_partition in fused_partitions: + linear_partition, unary_partition = fused_partition + linear_node, unary_node = self._get_output_nodes_of_partitions( + [linear_partition, unary_partition] + ) + if linear_node.op != "call_function" or linear_node.target not in ( + torch.ops.aten.linear.default, + ): + continue + if _skip_annotate([unary_node, linear_node], filter_fn): + continue + + if quantization_config is None: + _annotate_nodes_not_quantize([linear_node, unary_node]) + continue + + self._annotate_linear_node_helper(linear_node, False, quantization_config) + unary_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + + def _annotate_linear_binary_unary( + self, + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ) -> None: + # linear + binary_op + (optional) unary op + binary_op_list = [operator.add] + unary_op_list = [torch.nn.ReLU, None] + combinations = itertools.product(binary_op_list, unary_op_list) + for binary_op, unary_op in combinations: + has_unary = unary_op is not None + seq_partition = [torch.nn.Linear, binary_op] + if has_unary: + seq_partition.append(unary_op) + fused_partitions = find_sequential_partitions(gm, seq_partition) + for fused_partition in fused_partitions: + unary_partition, unary_node = None, None + if has_unary: + ( + linear_partition, + binary_partition, + unary_partition, + ) = fused_partition + ( + linear_node, + binary_node, + unary_node, + ) = self._get_output_nodes_of_partitions( + [linear_partition, binary_partition, unary_partition] + ) + else: + linear_partition, binary_partition = fused_partition + linear_node, binary_node = self._get_output_nodes_of_partitions( + [linear_partition, binary_partition] + ) + if len(linear_node.users) != 1: + # Linear Node should only has 1 user node + continue + ( + linear_node_idx, + extra_input_node_idx, + ) = self._get_input_idx_for_binary_node(linear_node, binary_node) + if (linear_node_idx is None) or (extra_input_node_idx is None): + continue + if linear_node != binary_node.args[linear_node_idx]: + raise ValueError( + f"{linear_node} doesn't match input of binary node" + ) + assert isinstance(linear_node, Node) + if ( + linear_node.op != "call_function" + or linear_node.target != torch.ops.aten.linear.default + ): + # No linear node found to be fused with add + continue + node_list = ( + [binary_node, linear_node] + if unary_node is None + else [unary_node, binary_node, linear_node] + ) + if _skip_annotate(node_list, filter_fn): + continue + + if quantization_config is None: + _annotate_nodes_not_quantize(node_list) + continue + + self._annotate_linear_node_helper( + linear_node, False, quantization_config + ) + # We don't insert q-dq before the binary input node due to accuracy issues + binary_node.meta[QUANT_ANNOTATION_KEY] = ( + _X86InductorQuantizationAnnotation( + input_qspec_map={}, + _annotated=True, + _is_output_of_quantized_pattern=(not has_unary), + ) + ) + if unary_node is not None: + unary_node.meta[QUANT_ANNOTATION_KEY] = ( + _X86InductorQuantizationAnnotation( + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + ) + + def _annotate_mul_tensor( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ): + def _is_tensor(n: Node): + return isinstance(n, Node) and isinstance( + n.meta["val"], torch._subclasses.fake_tensor.FakeTensor + ) + + def _same_shape(n1: Node, n2: Node): + return n1.meta["val"].shape == n2.meta["val"].shape + + for node in model.graph.nodes: + if node.target != torch.ops.aten.mul.Tensor: + continue + + if _skip_annotate([node], filter_fn): + continue + + if quantization_config is None: + _annotate_nodes_not_quantize(node) + continue + + assert len(node.args) == 2 + if not (_is_tensor(node.args[0]) and _is_tensor(node.args[1])): + continue + + if not _same_shape(node.args[0], node.args[1]): + continue + + input_qspec_map = {} + mul_node = node + for input_node in mul_node.args: + input_qspec_map[input_node] = get_input_act_qspec(quantization_config) + mul_node.meta[QUANT_ANNOTATION_KEY] = _X86InductorQuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + _is_output_of_quantized_pattern=True, + ) + + def validate(self, model: torch.fx.GraphModule) -> None: + pass + + +# Register Inductor fusion passes +import torch._inductor.config + +from torchao.quantization.pt2e.inductor_passes.x86 import ( + _register_quantization_weight_pack_pass, + quant_lift_up, +) +from torchao.utils import TORCH_VERSION_AT_LEAST_2_8 + +if TORCH_VERSION_AT_LEAST_2_8: + torch._inductor.config.pre_grad_custom_pass = quant_lift_up + _register_quantization_weight_pack_pass() diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/xpu_inductor_quantizer.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/xpu_inductor_quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..d43d2bd8566b80a9dee3d134a2eb39b32cea8751 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/pt2e/quantizer/xpu_inductor_quantizer.py @@ -0,0 +1,131 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs +import functools +from typing import TYPE_CHECKING, Any, Optional + +import torch +from torch.fx import Node + +from torchao.quantization.pt2e.observer import ( + HistogramObserver, + PerChannelMinMaxObserver, +) +from torchao.quantization.pt2e.quantizer import ( + QuantizationConfig, + QuantizationSpec, +) +from torchao.quantization.pt2e.quantizer.x86_inductor_quantizer import ( + FilterFn, + X86InductorQuantizer, + _is_any_annotated, + int8_in_int8_out_ops, +) + +if TYPE_CHECKING: + from torchao.quantization.pt2e import _ObserverOrFakeQuantizeConstructor + +__all__ = [ + "XPUInductorQuantizer", + "get_default_xpu_inductor_quantization_config", +] + + +@functools.lru_cache +def get_default_xpu_inductor_quantization_config(): + extra_args: dict[str, Any] = {"eps": 2**-12} + act_observer_or_fake_quant_ctr = HistogramObserver + act_quantization_spec = QuantizationSpec( + dtype=torch.int8, + quant_min=-128, + quant_max=127, + qscheme=torch.per_tensor_affine, + is_dynamic=False, + observer_or_fake_quant_ctr=act_observer_or_fake_quant_ctr.with_args( + **extra_args + ), + ) + + weight_observer_or_fake_quant_ctr: _ObserverOrFakeQuantizeConstructor = ( + PerChannelMinMaxObserver + ) + + weight_quantization_spec = QuantizationSpec( + dtype=torch.int8, + quant_min=-128, + quant_max=127, + qscheme=torch.per_channel_symmetric, + ch_axis=0, # 0 corresponding to weight shape = (oc, ic, kh, kw) of conv + is_dynamic=False, + observer_or_fake_quant_ctr=weight_observer_or_fake_quant_ctr.with_args( + **extra_args + ), + ) + + bias_quantization_spec = None # will use placeholder observer by default + quantization_config = QuantizationConfig( + act_quantization_spec, + act_quantization_spec, + weight_quantization_spec, + bias_quantization_spec, + False, + ) + return quantization_config + + +class XPUInductorQuantizer(X86InductorQuantizer): + """ + XPUInductorQuantizer is a class designed to facilitate + quantization capability at Intel GPU backend. The class + highly reuses the existing implementation of + X86InductorQuantizer as both are intended to take advantage + of the optimized kernels in oneDNN library. + """ + + def __init__(self) -> None: + super().__init__() + + """ + Following annotate_xx overrides the impls in base class, as + no XPU implementation for these operators currently. We would + gradually enable the XPU implementation and remove following + overrides. We keep the annotate methods but make the function + body empty, aiming to let `_generate_qdq_quantized_model` + generate qdq around op and graph execute on fp32 dtype for + unspported operators. + """ + + def _annotate_qat_conv2d_fusion_pattern( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[FilterFn] = None, + ): + pass + + def _annotate_maxpool2d( + self, + node: Node, + quantization_config: Optional[QuantizationConfig], + ) -> None: + """ + Here we skip the annotate logic for maxpool at XPU backend + as the quantized::max_pool2d is only implemented for CPU. + """ + return + + def _annotate_output_for_int8_in_int8_out_pattern( + self, + node: Node, + ) -> None: + if (node.target in int8_in_int8_out_ops) and (_is_any_annotated([node])): + if node.target == torch.ops.aten.max_pool2d.default: + return + else: + input_node = node.all_input_nodes[0] + self._annotate_output_share_observer_as_input(input_node, node) + return diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/quantize_/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/quantize_/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..049b71631bda4df78410835425f561ba7b7f0b9b --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/quantize_/__init__.py @@ -0,0 +1,9 @@ +from .int4_groupwise_preshuffle_tensor import ( + Int4GroupwisePreshuffleTensor, +) + +Int4GroupwisePreshuffleTensor.__module__ = "torchao.quantization" + +__all__ = [ + "Int4GroupwisePreshuffleTensor", +] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/quantize_/int4_groupwise_preshuffle_tensor.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/quantize_/int4_groupwise_preshuffle_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..1313be51283126337a8f9d4482ed8163e03b6033 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/quantization/quantize_/int4_groupwise_preshuffle_tensor.py @@ -0,0 +1,353 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + + +import importlib.util +from typing import List + +import torch +from torch.utils._python_dispatch import return_and_correct_aliasing + +from torchao.utils import ( + TORCH_VERSION_AT_LEAST_2_5, + TorchAOBaseTensor, + fill_defaults, +) + +__all__ = [ + "Int4GroupwisePreshuffleTensor", +] + +aten = torch.ops.aten + + +if importlib.util.find_spec("fbgemm_gpu") is None: + quantize_int4_preshuffle = None +else: + from fbgemm_gpu.experimental.gen_ai.quantize import quantize_int4_preshuffle + + +class Int4GroupwisePreshuffleTensor(TorchAOBaseTensor): + """ + Groupwise int4 weight only quantization + + Tensor Attributes: + packed_weight: packed int4 weight, either 2D (N, K/2) or 3D (B, N, K/2), last dimension is packed + group_scale: (K/group_size, N) for 2D Tensor, (B, N, K/group_size) for 3D Tensor + dtype is the same as the original Tensor dtype + group_zero: (K/group_size, N) for 2D Tensor, (B, N, K/group_size) for 3D Tensor + dtype is the same as the original Tensor dtype + + Non-Tensor Attributes: + group_size: the group size for groupwise quantization + shape_multiplier: is the multipler from packed_weight to the real weight, since + we pack the weight for int4, for example, when we pack the last dimension for + a 2D tensor, the shape_multiplier will be [1, 2] + shape: shape of the original Tensor + + Note: + Details for preshuffle for fbgemm kernel: + + We use WGMMA instruction for efficient matrix multiplication in H100 Tensor Core. + To address a major inefficiency in how WGMMA tiles are loaded into shared memory before + dispatching to tensor cores, Each thread of an FP8 WGMMA reads 4 groups for 4 elements + (or 4 groups of 2 elements for BF16) into local registers. Each of those groups thus + contains a total 32 bits, which can be efficiently loaded using a single 32-bit load instruction. + However, weights are loaded using the same format. As the INT4 weights are only 4-bits each, + one group has a total of 16 bits. Unfortunately, 16 bit loads are not any faster than 32 bit + loads so having to load all four groups is wasteful. We can optimize weight loading by shuffling + the order of elements such that all 4 groups are sequential in memory. This allows us to + perform a single 64 bit load to move all needed weights for the thread into register memory. + """ + + tensor_data_attrs = ["packed_weight", "group_scale", "group_zero"] + tensor_attributes = ["group_size", "shape_multiplier", "shape"] + + def __new__( + cls, packed_weight, group_scale, group_zero, group_size, shape_multiplier, shape + ): + kwargs = {} + kwargs["device"] = packed_weight.device + kwargs["dtype"] = group_scale.dtype + kwargs["requires_grad"] = False + return torch.Tensor._make_wrapper_subclass(cls, shape, **kwargs) # type: ignore[attr-defined] + + def __init__( + self, + packed_weight, + group_scale, + group_zero, + group_size, + shape_multiplier, + shape, + ): + self.packed_weight = packed_weight + self.group_scale = group_scale + self.group_zero = group_zero + self.shape_multiplier = shape_multiplier + self.group_size = group_size + + def __tensor_flatten__(self): + return self.tensor_data_attrs, [ + getattr(self, attr) for attr in self.tensor_attributes + ] + + @classmethod + def __tensor_unflatten__( + cls, tensor_data_dict, tensor_attributes, outer_size, outer_stride + ): + return cls( + *[tensor_data_dict[name] for name in cls.tensor_data_attrs], + *tensor_attributes, + ) + + def _apply_fn_to_data(self, fn): + return self.__class__( + *[fn(getattr(self, attr)) for attr in self.tensor_data_attrs], + *[getattr(self, attr) for attr in self.tensor_attributes], + ) + + def __repr__(self): + return ( + f"{self.__class__.__name__}(weight={self.packed_weight}, group_size={self.group_size}, " + f"shape_multiplier={self.shape_multiplier}, shape={self.shape}, device={self.device}, dtype={self.dtype}, " + f"requires_grad={self.requires_grad})" + ) + + def _quantization_type(self): + return f"shape={self.shape}, group_size={self.group_size}, device={self.device}" + + def to(self, *args, **kwargs): + kwargs = self._get_to_kwargs(*args, **kwargs) + device = kwargs.pop("device") + return self.__class__( + self.packed_weight.to(device), + self.group_scale.to(device), + self.group_zero.to(device), + self.group_size, + self.shape_multiplier, + self.shape, + ) + + @classmethod + def from_float( + cls, + w: torch.Tensor, + block_size: List[int], + ): + assert len(block_size) == w.ndim, ( + f"Expecting the length of block_size to be equal to the dimension of the weight, got {block_size=} and {w.ndim=}" + ) + if quantize_int4_preshuffle is None: + raise ImportError("Requires fbgemm-gpu-genai >= 1.2.0") + + group_size = block_size[-1] + original_shape = w.shape + + if w.ndim >= 3: + wq, scales = zip( + *[quantize_int4_preshuffle(i.cuda(), dtype="bf16") for i in w] + ) + wq = torch.stack(wq, dim=0) + group_scale, group_zero = zip(*scales) + group_zero = torch.stack(group_zero, dim=0).contiguous() + group_scale = torch.stack(group_scale, dim=0).contiguous() + else: + wq, (group_scale, group_zero) = quantize_int4_preshuffle( + w.cuda(), dtype="bf16" + ) + + shape_multiplier = [1] * wq.ndim + shape_multiplier[-1] = 2 + + del w + return Int4GroupwisePreshuffleTensor( + packed_weight=wq, + group_scale=group_scale, + group_zero=group_zero, + group_size=group_size, + shape_multiplier=shape_multiplier, + shape=original_shape, + ) + + +implements = Int4GroupwisePreshuffleTensor.implements + + +@implements([torch.nn.functional.linear, aten.linear.default]) +def _(func, types, args, kwargs): + input_tensor, weight_tensor, bias = ( + args[0], + args[1], + args[2] if len(args) > 2 else None, + ) + orig_input_size = input_tensor.size() + orig_out_features = weight_tensor.shape[-2] + + wq = weight_tensor.packed_weight.contiguous() + group_scale = weight_tensor.group_scale.contiguous() + group_zero = weight_tensor.group_zero.contiguous() + + if input_tensor.dim() == 3: + B, M, _ = input_tensor.shape + _, N, _ = wq.shape + res = torch.empty((B, M, N), device=input_tensor.device, dtype=torch.bfloat16) + for i in range(B): + res[i] = torch.ops.fbgemm.bf16i4bf16_shuffled( + input_tensor[i], wq[i], group_scale[i], group_zero[i] + ) + else: + # Otherwise run gemm normally. + res = torch.ops.fbgemm.bf16i4bf16_shuffled( + input_tensor, wq, group_scale, group_zero + ) + + res = res.reshape(*orig_input_size[:-1], orig_out_features) + if bias is not None: + res = res + bias + return res + + +@implements(torch.bmm) +def _(func, types, args, kwargs): + input_tensor, weight_tensor = ( + args[0], + args[1], + ) + orig_input_size = input_tensor.size() + orig_out_features = weight_tensor.shape[-2] + assert weight_tensor.shape_multiplier[-1] == 2 + + wq = weight_tensor.packed_weight + group_scale = weight_tensor.group_scale + group_zero = weight_tensor.group_zero + # from https://github.com/pytorch/FBGEMM/blob/ba8f2b7adb90e096cff8818716f7cc3587030f70/fbgemm_gpu/experimental/gen_ai/bench/quantize_ops.py#L1715-L1722 + B, M, _ = input_tensor.shape + _, N, _ = wq.shape + res = torch.empty((B, M, N), device=input_tensor.device, dtype=torch.bfloat16) + for i in range(B): + res[i] = torch.ops.fbgemm.bf16i4bf16_shuffled( + input_tensor[i], wq[i], group_scale[i], group_zero[i] + ) + res = res.reshape(*orig_input_size[:-1], orig_out_features) + return res + + +@implements([aten.detach.default, aten.alias.default]) +def _(func, types, args, kwargs): + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.detach) + ) + + +@implements(aten.clone.default) +def _(func, types, args, kwargs): + return return_and_correct_aliasing( + func, args, kwargs, args[0]._apply_fn_to_data(torch.clone) + ) + + +def _same_metadata( + self: "Int4GroupwisePreshuffleTensor", src: "Int4GroupwisePreshuffleTensor" +) -> bool: + return ( + isinstance(self, Int4GroupwisePreshuffleTensor) + and isinstance(src, Int4GroupwisePreshuffleTensor) + and self.shape == src.shape + and self.packed_weight.shape == src.packed_weight.shape + and self.group_scale.shape == src.group_scale.shape + and self.group_zero.shape == src.group_zero.shape + and self.group_size == src.group_size + and self.shape_multiplier == src.shape_multiplier + ) + + +@implements(aten.copy_.default) +def _(func, types, args, kwargs): + self = args[0] + src = args[1] + if _same_metadata(self, src): + self_tensors = self.__tensor_flatten__()[0] + for tensor_name in self_tensors: + getattr(self, tensor_name).copy_(getattr(src, tensor_name)) + return + raise ValueError( + f"Not supported args for copy_ due to metadata mismatch: {args[0], args[1]}" + ) + + +@implements(aten.cat.default) +def _(func, types, args, kwargs): + tensors, dim = fill_defaults(args, 2, [[], 0]) + tensor_0 = tensors[0] + if dim < 0: + dim = dim + tensor_0.ndim + + for i in range(1, len(tensors)): + assert tensor_0.packed_weight.ndim == tensors[i].packed_weight.ndim + assert tensor_0.group_scale.ndim == tensors[i].group_scale.ndim + assert tensor_0.group_zero.ndim == tensors[i].group_zero.ndim + assert tensor_0.group_size == tensors[i].group_size + assert tensor_0.shape_multiplier == tensors[i].shape_multiplier + + packed_weight = [t.packed_weight for t in tensors] + group_scale = [t.group_scale for t in tensors] + group_zero = [t.group_zero for t in tensors] + + # with group wise quantization, dimension of group_scale, packed_weight and + # origianl shape will be the same, so original dim argument applies + # to both packed_weight and group_scale + cat_packed_weight = aten.cat.default(packed_weight, dim) + if cat_packed_weight.ndim == 2: + sz_dim = 1 - dim + else: + sz_dim = dim + + cat_group_scale = aten.cat.default(group_scale, sz_dim) + cat_group_zero = aten.cat.default(group_zero, sz_dim) + new_shape = list(cat_packed_weight.shape) + for i in range(len(tensor_0.shape_multiplier)): + new_shape[i] *= tensor_0.shape_multiplier[i] + new_shape = tuple(new_shape) + new = tensor_0.__class__( + cat_packed_weight, + cat_group_scale, + cat_group_zero, + group_size=tensor_0.group_size, + shape_multiplier=tensor_0.shape_multiplier, + shape=new_shape, + ) + return return_and_correct_aliasing(func, args, kwargs, new) + + +@implements(aten.transpose.int) +def _(func, types, args, kwargs): + self, dim0, dim1 = args + packed_weight = self.packed_weight.transpose(dim0, dim1).contiguous() + shape_multiplier = self.shape_multiplier.copy() + shape_multiplier[dim0], shape_multiplier[dim1] = ( + shape_multiplier[dim1], + shape_multiplier[dim0], + ) + + tensor_shape = list(packed_weight.shape) + for i in range(len(shape_multiplier)): + tensor_shape[i] *= shape_multiplier[i] + tensor_shape = tuple(tensor_shape) + new = self.__class__( + packed_weight, + self.group_scale, + self.group_zero, + self.group_size, + shape_multiplier, + tensor_shape, + ) + return return_and_correct_aliasing(func, args, kwargs, new) + + +if TORCH_VERSION_AT_LEAST_2_5: + # Allow a model with Int4GroupwisePreshuffleTensor weights to be loaded with `weights_only=True` + torch.serialization.add_safe_globals([Int4GroupwisePreshuffleTensor]) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/swizzle/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/swizzle/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa001267c4ac98bdca77ff04b4815215ab3290c --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/swizzle/__init__.py @@ -0,0 +1,9 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. + +# This source code is licensed under the license found in the +# LICENSE file in the root directory of this source tree. + +from .swizzle_tensor import SwizzleTensor + +__all__ = ["SwizzleTensor"] diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/swizzle/swizzle_ops.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/swizzle/swizzle_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d8bbad46a14b0ff9dd88328336cb036f1358a6b2 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/swizzle/swizzle_ops.py @@ -0,0 +1,119 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +from typing import Any, Dict + +import torch + +import torchao.ops +from torchao.swizzle.swizzle_tensor import SwizzleTensor + +aten = torch.ops.aten +SWIZZLE_OPS_TABLE: Dict[Any, Any] = {} + + +def implements(aten_ops): + """Register aten ops to the swizzle op table""" + + def decorator(func): + for op in aten_ops: + SWIZZLE_OPS_TABLE[op] = func + return func + + return decorator + + +@implements([aten.mm.default, aten.matmul.default]) +def swizzle_mm(aten_op, args, kwargs=None): + a = args[0] + b = args[1] + + if ( + torch.is_floating_point(a) + and torch.is_floating_point(b) + and a.ndim == 2 + and b.ndim == 2 + ): + a_is_swizzled = False + b_is_swizzled = False + if isinstance(a, SwizzleTensor): + a = a.as_tensor() + a_is_swizzled = True + if isinstance(b, SwizzleTensor): + b = b.as_tensor() + b_is_swizzled = True + tensor_out = torchao.ops.swizzle_mm(a, b, a_is_swizzled, b_is_swizzled) + else: + a = a.unswizzle() if isinstance(a, SwizzleTensor) else a + b = b.unswizzle() if isinstance(b, SwizzleTensor) else b + tensor_out = aten_op(a, b, **kwargs) + return tensor_out + + +@implements([aten.bmm.default]) +def swizzle_bmm(aten_op, args, kwargs=None): + a = args[0] + b = args[1] + + a = a.unswizzle() if isinstance(a, SwizzleTensor) else a + b = b.unswizzle() if isinstance(b, SwizzleTensor) else b + return aten_op(a, b, **kwargs) + + +@implements([aten.addmm.default]) +def swizzle_addmm(aten_op, args, kwargs=None): + bias = args[0] + a = args[1] + b = args[2] + a = a.unswizzle() if isinstance(a, SwizzleTensor) else a + b = b.unswizzle() if isinstance(b, SwizzleTensor) else b + return aten_op(bias, a, b, args[3:], **kwargs) + + +@implements([aten._scaled_mm.default]) +def swizzle_scaled_mm(aten_op, args, kwargs=None): + a = args[0] + b = args[1] + scale_a = args[2] + scale_b = args[3] + bias = None if len(args) <= 4 else args[4] + scale_result = None if len(args) <= 5 else args[5] + out_dtype = None if len(args) <= 6 else args[6] + + a_is_swizzled = False + b_is_swizzled = False + if isinstance(a, SwizzleTensor): + a = a.as_tensor() + a_is_swizzled = True + if isinstance(b, SwizzleTensor): + b = b.as_tensor() + b_is_swizzled = True + return torchao.ops.swizzle_scaled_mm( + a, + b, + a_is_swizzled, + b_is_swizzled, + scale_a, + scale_b, + bias, + scale_result, + out_dtype, + **kwargs, + ) + + +@implements([aten.permute.default]) +def swizzle_permute(aten_op, args, kwargs=None): + tensor = args[0] + dims = args[1] + if len(dims) == 2 and dims[0] == 1 and dims[1] == 0: + return tensor.shallow_transpose() + return aten_op(tensor.unswizzle(), dims) + + +@implements([aten.numpy_T.default]) +def swizzle_numpy_T(aten_op, args, kwargs=None): + tensor = args[0] + return tensor.shallow_transpose() diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/swizzle/swizzle_tensor.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/swizzle/swizzle_tensor.py new file mode 100644 index 0000000000000000000000000000000000000000..8ddfd9308aa45c43c98cdb0e045b7795873ba78f --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/swizzle/swizzle_tensor.py @@ -0,0 +1,143 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +import torch +from torch.utils._pytree import tree_map + + +# copied from float8_utils.py +def _get_min_alignment(size: int, alignment_value: int) -> int: + return (1 + ((size - 1) // alignment_value)) * alignment_value + + +class SwizzleTensor(torch.Tensor): + """ + A Python-only swizzled tensor subclass. + + Intended usage of this abstraction: + Swizzle weight Tensor to avoid LDS use during GEMMs on ROCm hardware. + """ + + def __new__( + cls, + original: torch.Tensor, + shallow: bool = False, + ): + wrapper = torch.empty_like(original, device="meta") + return torch.Tensor._make_subclass(cls, wrapper) + + def __init__(self, original, shallow=False): + if shallow: + return + # assert original.ndim == 2 or original.ndim == 3 # (M, K) or (B, M, K) + assert original.ndim == 2, "SwizzleTensor only supports ndim 2" + assert original.itemsize == 1 or original.itemsize == 2 + kdiv = 32 if original.itemsize == 2 else 64 + lastdim = 8 if original.itemsize == 2 else 16 + if original.ndim == 2: + M, K = original.shape + B = 0 + if original.ndim == 3: + B, M, K = original.shape + alignedM = _get_min_alignment(M, 16) + alignedK = _get_min_alignment(K, kdiv) + paddedM = alignedM - M + paddedK = alignedK - K + x = torch.nn.functional.pad(original, (0, paddedK, 0, paddedM), "constant", 0) + if original.ndim == 2: + x = x.view(alignedM // 16, 16, alignedK // kdiv, 4, lastdim) + x = x.permute(0, 2, 3, 1, 4) + if original.ndim == 3: + x = x.view(B, alignedM // 16, 16, alignedK // kdiv, 4, lastdim) + x = x.permute(0, 1, 3, 4, 2, 5) + self.x = x.contiguous() + self.B = B + self.M = M + self.K = K + self.alignedM = alignedM + self.alignedK = alignedK + self.paddedM = paddedM + self.paddedK = paddedK + self.original_ndim = original.ndim + self.is_transposed = False + + def __repr__(self): + return f"{self.__class__.__name__}(original={self.unswizzle()})" + + def unswizzle(self): + undone = None + if self.original_ndim == 2: + undone = self.x.permute(0, 3, 1, 2, 4).contiguous() + undone = undone.reshape(self.alignedM, self.alignedK) + undone = undone[0 : self.M, 0 : self.K] + undone = undone.reshape(self.M, self.K) + if self.is_transposed: + undone = undone.T + if self.original_ndim == 3: + undone = self.x.permute(0, 1, 4, 2, 3, 5).contiguous() + undone = undone.reshape(self.B, self.alignedM, self.alignedK) + undone = undone[0 : self.B, 0 : self.M, 0 : self.K] + undone = undone.reshape(self.B, self.M, self.K) + return undone + + def as_tensor(self): + # note the transpose because this causes col major hipblaslt op to be TN + if self.original_ndim == 2: + tmp = self.x.reshape(self.alignedM, self.alignedK) + if self.is_transposed: + tmp = tmp.T + return tmp + if self.original_ndim == 3: + tmp = self.x.reshape(self.B, self.alignedM, self.alignedK) + if self.is_transposed: + tmp = tmp.T + return tmp + + def shallow_transpose(self): + shape = ( + (self.M, self.K) if self.original_ndim == 2 else (self.B, self.M, self.K), + ) + new_obj = SwizzleTensor( + torch.empty(*shape, dtype=self.dtype, layout=self.layout, device="meta"), + True, + ) + new_obj.x = self.x + new_obj.B = self.B + new_obj.M = self.M + new_obj.K = self.K + new_obj.alignedM = self.alignedM + new_obj.alignedK = self.alignedK + new_obj.paddedM = self.paddedM + new_obj.paddedK = self.paddedK + new_obj.original_ndim = self.original_ndim + new_obj.is_transposed = not self.is_transposed + return new_obj + + @property + def shape(self): + return torch.Size((self.K, self.M) if self.is_transposed else (self.M, self.K)) + + def stride(self): + return (1, self.K) if self.is_transposed else (self.K, 1) + + @classmethod + def __torch_dispatch__(cls, func, types, args, kwargs=None): + # Lazy import to avoid circular dependency + from torchao.swizzle.swizzle_ops import SWIZZLE_OPS_TABLE + + if func in SWIZZLE_OPS_TABLE: + return SWIZZLE_OPS_TABLE[func](func, args, kwargs) + + def unwrap(e): + return e.unswizzle() if isinstance(e, SwizzleTensor) else e + + def wrap(e): + return SwizzleTensor(e) if isinstance(e, torch.Tensor) else e + + return tree_map(wrap, func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs))) + + # Do not force the SwizzleTensor type on the returned tensor + __torch_function__ = torch._C._disabled_torch_function_impl diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/model_architectures.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/model_architectures.py new file mode 100644 index 0000000000000000000000000000000000000000..f59a1271b18c49b31818e43b8a2eba83af611244 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/model_architectures.py @@ -0,0 +1,179 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +import re + +import torch +import torch.nn as nn + + +# TODO: Refactor torchao and tests to use these models +class ToyLinearModel(torch.nn.Module): + def __init__(self, k=64, n=32, dtype=torch.bfloat16): + super().__init__() + self.linear1 = torch.nn.Linear(k, n, bias=False).to(dtype) + + def forward(self, x): + x = self.linear1(x) + return x + + +class LNLinearActivationModel(nn.Module): + def __init__(self, fc_dim1, fc_dim2, dtype=torch.bfloat16, activation="sigmoid"): + super().__init__() + + activation = activation.lower() + activation_map = { + "relu": nn.ReLU(), + "sigmoid": nn.Sigmoid(), + "leakyrelu": nn.LeakyReLU(), + "relu6": nn.ReLU6(), + "gelu": nn.GELU(), + "silu": nn.SiLU(), + "hardswish": nn.Hardswish(), + } + + if activation not in activation_map: + raise ValueError(f"Unsupported activation: {activation}") + + self.ln = nn.LayerNorm(fc_dim1, elementwise_affine=False) + self.fc = nn.Linear(fc_dim1, fc_dim2, bias=False).to(dtype=dtype) + self.activation = activation_map[activation] + + def forward(self, x): + x = self.ln(x) + x = self.fc(x) + return self.activation(x) + + +class RMSNorm(nn.Module): + def __init__(self, dim: int, eps: float = 1e-5): + super().__init__() + self.eps = eps + self.weight = nn.Parameter(torch.ones(dim)) + + def _norm(self, x): + return x * torch.rsqrt(torch.mean(x * x, dim=-1, keepdim=True) + self.eps) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + output = self._norm(x.float()).type_as(x) + return output * self.weight + + +class TransformerBlock(torch.nn.Module): + def __init__(self, hidden_dim, num_heads=8, mlp_ratio=4, dtype=torch.bfloat16): + super().__init__() + self.hidden_dim = hidden_dim + self.num_heads = num_heads + self.head_dim = hidden_dim // num_heads + + # Self-attention + self.qkv = torch.nn.Linear(hidden_dim, 3 * hidden_dim, bias=False).to(dtype) + self.proj = torch.nn.Linear(hidden_dim, hidden_dim, bias=False).to(dtype) + + # MLP + self.mlp_ratio = mlp_ratio + self.mlp_hidden_dim = int(hidden_dim * mlp_ratio) + self.mlp_fc1 = torch.nn.Linear(hidden_dim, self.mlp_hidden_dim, bias=False).to( + dtype + ) + self.mlp_fc2 = torch.nn.Linear(self.mlp_hidden_dim, hidden_dim, bias=False).to( + dtype + ) + + # Layer norms + self.norm1 = RMSNorm(hidden_dim).to(dtype) + self.norm2 = RMSNorm(hidden_dim).to(dtype) + + # Activation + self.activation = torch.nn.GELU() + + def forward(self, x): + batch_size, seq_len, _ = x.shape + + # Self-attention + residual = x + x = self.norm1(x) + + # Reshape qkv projection for better memory layout + qkv = self.qkv(x) # [batch_size, seq_len, 3 * hidden_dim] + qkv = qkv.reshape(batch_size, seq_len, 3, self.num_heads, self.head_dim) + qkv = qkv.permute( + 2, 0, 3, 1, 4 + ) # [3, batch_size, num_heads, seq_len, head_dim] + q, k, v = qkv # Each has shape [batch_size, num_heads, seq_len, head_dim] + + # Scaled dot-product attention with proper reshaping + # Reshape for better memory layout and avoid broadcasting issues + q = q.reshape(batch_size * self.num_heads, seq_len, self.head_dim) + k = k.reshape(batch_size * self.num_heads, seq_len, self.head_dim) + v = v.reshape(batch_size * self.num_heads, seq_len, self.head_dim) + + # Compute attention scores + attn = (q @ k.transpose(-2, -1)) * (1.0 / (self.head_dim**0.5)) + attn = torch.softmax(attn, dim=-1) + + # Apply attention to values + x = attn @ v # [batch_size * num_heads, seq_len, head_dim] + + # Reshape back to original dimensions + x = x.reshape(batch_size, self.num_heads, seq_len, self.head_dim) + x = x.transpose(1, 2).reshape(batch_size, seq_len, self.hidden_dim) + + # Project back to hidden dimension + x = self.proj(x) + x = residual + x + + # MLP + residual = x + x = self.norm2(x) + x = self.mlp_fc1(x) + x = self.activation(x) + x = self.mlp_fc2(x) + x = residual + x + + return x + + +def create_model_and_input_data( + model_type: str, + m: int, + k: int, + n: int, + high_precision_dtype: torch.dtype = torch.bfloat16, + device: str = "cuda", + activation: str = "relu", +): + """Create a model and input data for benchmarking. + + Args: + model_type (str): type of the model to be created + batch_size (int): batch size of the input data + device (str): device to run the model on + high_precision_dtype (torch.dtype): data type of the model + m, k, n (int): dimensions of the model and input data + """ + if model_type == "linear": + model = ToyLinearModel(k, n, high_precision_dtype).to(device) + input_data = torch.randn(m, k, device=device, dtype=high_precision_dtype) + elif "ln_linear" in model_type: + # Extract activation type from model_type string + match = re.search(r"ln_linear_?(\w+)?", model_type) + activation = match.group(1) if match and match.group(1) else "relu" + model = LNLinearActivationModel( + k, n, high_precision_dtype, activation=activation + ).to(device) + input_data = torch.randn(m, k, device=device, dtype=high_precision_dtype) + elif model_type == "transformer_block": + # For transformer block, k is the hidden dimension + model = TransformerBlock( + k, num_heads=8, mlp_ratio=4, dtype=high_precision_dtype + ).to(device) + # Input shape for transformer is [batch_size, seq_len, hidden_dim] + input_data = torch.randn(m, 16, k, device=device, dtype=high_precision_dtype) + else: + raise ValueError(f"Unknown model type: {model_type}") + return model, input_data diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/_xnnpack_quantizer.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/_xnnpack_quantizer.py new file mode 100644 index 0000000000000000000000000000000000000000..30d2e6178db23e3d266cb0ea6f8af269654a1fd2 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/_xnnpack_quantizer.py @@ -0,0 +1,455 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs +from __future__ import annotations + +import copy +import functools +import warnings +from typing import TYPE_CHECKING, Any, Callable, Optional + +import torch +import torch._dynamo as torchdynamo +import torch.nn.functional as F +from torch.fx._compatibility import compatibility + +from torchao.quantization.pt2e import ( + FakeQuantize, + FusedMovingAvgObsFakeQuantize, + HistogramObserver, + MinMaxObserver, + MovingAverageMinMaxObserver, + MovingAveragePerChannelMinMaxObserver, + PerChannelMinMaxObserver, + PlaceholderObserver, +) +from torchao.quantization.pt2e.quantizer import ( + QuantizationSpec, + Quantizer, + get_module_name_filter, +) +from torchao.testing.pt2e._xnnpack_quantizer_utils import ( + OP_TO_ANNOTATOR, + OperatorConfig, + OperatorPatternType, + QuantizationConfig, + _convert_scalars_to_attrs, + propagate_annotation, +) + +if TYPE_CHECKING: + from torch.fx import Node + + from torchao.quantization.pt2e import _ObserverOrFakeQuantizeConstructor + + +__all__ = [ + "XNNPACKQuantizer", + "get_symmetric_quantization_config", +] + + +def _get_dynamo_graph(function: Callable, inputs) -> torch.fx.Graph: + gm, _ = torchdynamo.export(function, aten_graph=True)(*inputs) + gm.graph.eliminate_dead_code() + return gm.graph + + +def _get_linear_patterns(input_size: list[int]): + in_channels = input_size[-1] + out_channels = 8 # hard coding but this should not matter + weight = torch.ones((out_channels, in_channels)) + bias = torch.ones((out_channels,)) + act = torch.ones(input_size) + + def linear_op(act, weight, bias=None): + return F.linear(act, weight, bias) + + pattern_w_bias = _get_dynamo_graph(linear_op, (act, weight, bias)) + pattern_wo_bias = _get_dynamo_graph(linear_op, (act, weight)) + return [pattern_w_bias, pattern_wo_bias] + + +def _supported_symmetric_quantized_operators() -> dict[str, list[OperatorPatternType]]: + supported_operators: dict[str, list[OperatorPatternType]] = { + # Both conv and linear should be able to handle relu + hardtanh fusion since + # those are clamp ops + "conv2d": [ + [torch.nn.Conv2d, torch.nn.ReLU], + [torch.nn.Conv2d, F.relu], + [F.conv2d, torch.nn.ReLU], + [F.conv2d, F.relu], + ], + "linear": [[torch.nn.Linear], [F.linear]], + "add": [[torch.add]], + "adaptive_avg_pool2d": [ + [torch.nn.AdaptiveAvgPool2d], + [F.adaptive_avg_pool2d], + ], + } + return copy.deepcopy(supported_operators) + + +def _get_supported_symmetric_config_and_operators() -> list[OperatorConfig]: + supported_config_and_operators: list[OperatorConfig] = [] + for quantization_config in [ + get_symmetric_quantization_config(), + get_symmetric_quantization_config(is_qat=True), + get_symmetric_quantization_config(is_per_channel=True), + get_symmetric_quantization_config(is_per_channel=True, is_qat=True), + ]: + ops = _supported_symmetric_quantized_operators() + supported_config_and_operators.extend( + OperatorConfig(quantization_config, pattern_list) + for pattern_list in ops.values() + ) + return copy.deepcopy(supported_config_and_operators) + + +@functools.lru_cache +def get_symmetric_quantization_config( + is_per_channel: bool = False, + is_qat: bool = False, + is_dynamic: bool = False, + act_qmin: int = -128, + act_qmax: int = 127, + weight_qmin: int = -127, + weight_qmax: int = 127, +): + extra_args: dict[str, Any] = {"eps": 2**-12} + if is_qat: + if is_dynamic: + act_observer_or_fake_quant_ctr = FakeQuantize + dynamic_quant_observer = MovingAverageMinMaxObserver.with_args( + averaging_constant=1 + ) + extra_args["observer"] = dynamic_quant_observer + else: + act_observer_or_fake_quant_ctr = FusedMovingAvgObsFakeQuantize # type: ignore[assignment] + else: + if is_dynamic: + act_observer_or_fake_quant_ctr = PlaceholderObserver # type: ignore[assignment] + else: + act_observer_or_fake_quant_ctr = HistogramObserver # type: ignore[assignment] + + act_quantization_spec = QuantizationSpec( + dtype=torch.int8, + quant_min=act_qmin, + quant_max=act_qmax, + qscheme=torch.per_tensor_affine, + is_dynamic=is_dynamic, + observer_or_fake_quant_ctr=act_observer_or_fake_quant_ctr.with_args( + **extra_args, + ), + ) + weight_qscheme = ( + torch.per_channel_symmetric if is_per_channel else torch.per_tensor_symmetric + ) + weight_observer_or_fake_quant_ctr: _ObserverOrFakeQuantizeConstructor = ( + MinMaxObserver + ) + if is_qat: + # TODO: qat + per channel? + weight_observer_or_fake_quant_ctr = FusedMovingAvgObsFakeQuantize + elif is_per_channel: + weight_observer_or_fake_quant_ctr = PerChannelMinMaxObserver + + extra_args: dict[str, Any] = {"eps": 2**-12} + if is_qat: + if weight_qscheme == torch.per_tensor_symmetric: + extra_args["observer"] = MovingAverageMinMaxObserver + else: + extra_args["observer"] = MovingAveragePerChannelMinMaxObserver # type: ignore[dict-item] + weight_quantization_spec = QuantizationSpec( + dtype=torch.int8, + quant_min=weight_qmin, + quant_max=weight_qmax, + qscheme=weight_qscheme, + ch_axis=0, + is_dynamic=False, + observer_or_fake_quant_ctr=weight_observer_or_fake_quant_ctr.with_args( + **extra_args + ), + ) + + bias_quantization_spec = None + if is_dynamic: + quantization_config = QuantizationConfig( + act_quantization_spec, + None, + weight_quantization_spec, + bias_quantization_spec, + is_qat, + ) + else: + quantization_config = QuantizationConfig( + act_quantization_spec, + act_quantization_spec, + weight_quantization_spec, + bias_quantization_spec, + is_qat, + ) + return quantization_config + + +def _get_supported_config_and_operators() -> list[OperatorConfig]: + return _get_supported_symmetric_config_and_operators() + + +def _get_module_type_filter(tp: Callable): + """Get the module_type_filter function for a given module type, the filter accepts + a node and checks if the node comes from a module that has certain module type + + For example: + node: linear_op = call_function[...](...) # comes from a module with type Block -> Sub -> Linear + + + >> module_type_filter = _get_module_type_filter(Sub) # submodule with type `Sub`, under the `Block` submodule + >> print(module_type_filter(node)) + True # the node is from the submodule `Sub` (same for `Block` and `Linear` as well) + """ + + tp_str = tp.__module__ + "." + tp.__qualname__ + + def module_type_filter(n: Node) -> bool: + # example: { + # 'L__self___sub': ("L['self'].sub", ), + # 'L__self___sub_linear': ("L['self'].sub.linear", ) + # } + nn_module_stack = n.meta.get("nn_module_stack", {}) + types = [] + for _, t in nn_module_stack.values(): + # export() returns str, but older APIs (e.g. capture_pre_autograd_graph) + # return type. Handle both cases. + if isinstance(t, type): + t = t.__module__ + "." + t.__qualname__ + types.append(t) + return tp_str in types + + return module_type_filter + + +def _get_not_module_type_or_name_filter( + tp_list: list[Callable], module_name_list: list[str] +) -> Callable[[Node], bool]: + module_type_filters = [_get_module_type_filter(tp) for tp in tp_list] + module_name_list_filters = [get_module_name_filter(m) for m in module_name_list] + + def not_module_type_or_name_filter(n: Node) -> bool: + return not any(f(n) for f in module_type_filters + module_name_list_filters) + + return not_module_type_or_name_filter + + +@compatibility(is_backward_compatible=False) +class XNNPACKQuantizer(Quantizer): + """ + !!! DEPRECATED !!! + XNNPACKQuantizer is a marked as deprected. It will be removed in the future. + It has been moved to executorch.backends.xnnpack.quantizer.xnnpack_quantizer.XNNPACKQuantizer. + Please use the new quantizer instead. + """ + + supported_config_and_operators = _get_supported_config_and_operators() + STATIC_QAT_ONLY_OPS = [ + "conv_bn_relu", + "conv_bn", + "conv_transpose_bn_relu", + "conv_transpose_bn", + ] + + # static quantization ops (both PTQ and QAT) + # Preserve the order that fusions come before singular ops + STATIC_OPS = [ + "linear_relu", + "linear", + "conv_relu", + "conv", + "conv_transpose_relu", + "adaptive_avg_pool2d", + # TODO: move this to BoltNNQuantizer? + "gru_io_only", + "add_relu", + "add", + "mul_relu", + "mul", + "cat", + ] + + DYNAMIC_OPS = [ + "linear", + ] + + def __init__(self) -> None: + super().__init__() + warnings.warn(f"{self.__class__.__name__} is deprecated!") + self.global_config: Optional[QuantizationConfig] = None + self.operator_type_config: dict[ + torch._ops.OpOverloadPacket, Optional[QuantizationConfig] + ] = {} + self.module_type_config: dict[Callable, Optional[QuantizationConfig]] = {} + self.module_name_config: dict[str, Optional[QuantizationConfig]] = {} + + @classmethod + def get_supported_quantization_configs(cls) -> list[QuantizationConfig]: + op_configs: set[QuantizationConfig] = { + spec for spec, _ in cls.supported_config_and_operators + } + return list(op_configs) + + @classmethod + def get_supported_operator_for_quantization_config( + cls, quantization_config: Optional[QuantizationConfig] + ) -> list[OperatorPatternType]: + if quantization_config is None: + all_ops = [] + for _, ops in cls.supported_config_and_operators: + all_ops.extend(ops) + return all_ops + + for config, ops in cls.supported_config_and_operators: + # note: this assumes each entry in cls.supported_spec_and_operators + # corresponds to one spec, e.g. we don't have + # [(spec1, op_list1), (spec1, op_list2), (spec2, op_list3)] + # where the first and second entry have the same spec but did not + # merge the op list + if config == quantization_config: + return ops + return [] + + def set_global(self, quantization_config: QuantizationConfig) -> XNNPACKQuantizer: + self.global_config = quantization_config + return self + + def set_operator_type( + self, + operator_type: torch._ops.OpOverloadPacket, + quantization_config: QuantizationConfig, + ) -> XNNPACKQuantizer: + self.operator_type_config[operator_type] = quantization_config + return self + + def set_module_type( + self, module_type: Callable, quantization_config: QuantizationConfig + ): + """Set quantization_config for a submodule with type: `module_type`, for example: + quantizer.set_module_name(Sub) or quantizer.set_module_name(nn.Linear), it will quantize all supported operator/operator + patterns in the submodule with this module type with the given `quantization_config` + """ + self.module_type_config[module_type] = quantization_config + return self + + def set_module_name( + self, module_name: str, quantization_config: Optional[QuantizationConfig] + ): + """Set quantization_config for a submodule with name: `module_name`, for example: + quantizer.set_module_name("blocks.sub"), it will quantize all supported operator/operator + patterns in the submodule with this module name with the given `quantization_config` + """ + assert quantization_config is not None, ( + " quantization_config == None is not supported yet" + ) + self.module_name_config[module_name] = quantization_config + return self + + def transform_for_annotation( + self, model: torch.fx.GraphModule + ) -> torch.fx.GraphModule: + """Transforms scalar values to tensor attributes""" + return _convert_scalars_to_attrs(model) + + def annotate(self, model: torch.fx.GraphModule) -> torch.fx.GraphModule: + """just handling global spec for now""" + # hacked for handling dynamic linear quant. will fix later. + if self.global_config and self.global_config.input_activation.is_dynamic: # type: ignore[union-attr] + model = self._annotate_for_dynamic_quantization_config(model) + else: + model = self._annotate_for_static_quantization_config(model) + propagate_annotation(model) + return model + + def _annotate_all_static_patterns( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> torch.fx.GraphModule: + # TODO: implement the support for None to be canceling out previous annotations + if quantization_config is None: + return model + + if quantization_config.is_qat: + for op in self.STATIC_QAT_ONLY_OPS: + OP_TO_ANNOTATOR[op](model, quantization_config, filter_fn) + for op in self.STATIC_OPS: + OP_TO_ANNOTATOR[op](model, quantization_config, filter_fn) + return model + + def _annotate_all_dynamic_patterns( + self, + model: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + ) -> torch.fx.GraphModule: + # TODO: implement the support for None to be canceling out previous annotations + if quantization_config is None: + return model + + for op in self.DYNAMIC_OPS: + OP_TO_ANNOTATOR[op](model, quantization_config, filter_fn) + return model + + def _annotate_for_static_quantization_config( + self, model: torch.fx.GraphModule + ) -> torch.fx.GraphModule: + module_name_list = list(self.module_name_config.keys()) + for module_name, config in self.module_name_config.items(): + self._annotate_all_static_patterns( + model, config, get_module_name_filter(module_name) + ) + + tp_list = list(self.module_type_config.keys()) + for module_type, config in self.module_type_config.items(): + self._annotate_all_static_patterns( + model, config, _get_module_type_filter(module_type) + ) + + self._annotate_all_static_patterns( + model, + self.global_config, + _get_not_module_type_or_name_filter(tp_list, module_name_list), + ) + return model + + def _annotate_for_dynamic_quantization_config( + self, model: torch.fx.GraphModule + ) -> torch.fx.GraphModule: + module_name_list = list(self.module_name_config.keys()) + for module_name, config in self.module_name_config.items(): + self._annotate_all_dynamic_patterns( + model, config, get_module_name_filter(module_name) + ) + + tp_list = list(self.module_type_config.keys()) + for module_type, config in self.module_type_config.items(): + self._annotate_all_dynamic_patterns( + model, config, _get_module_type_filter(module_type) + ) + + self._annotate_all_dynamic_patterns( + model, + self.global_config, + _get_not_module_type_or_name_filter(tp_list, module_name_list), + ) + return model + + def validate(self, model: torch.fx.GraphModule) -> None: + pass + + @classmethod + def get_supported_operators(cls) -> list[OperatorConfig]: + return cls.supported_config_and_operators diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/_xnnpack_quantizer_utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/_xnnpack_quantizer_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c49caca28580de7dc31ee66198ebf6514f6e4afe --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/_xnnpack_quantizer_utils.py @@ -0,0 +1,1133 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +# mypy: allow-untyped-defs +import itertools +import typing +from dataclasses import dataclass +from typing import Callable, NamedTuple, Optional + +import torch +import torch.nn.functional as F +from torch._subclasses import FakeTensor +from torch.fx import Node +from torch.fx.passes.utils.matcher_with_name_node_map_utils import ( + SubgraphMatcherWithNameNodeMap, +) +from torch.fx.passes.utils.source_matcher_utils import get_source_partitions + +from torchao.quantization.pt2e.export_utils import WrapperModule +from torchao.quantization.pt2e.quantizer import ( + QuantizationAnnotation, + QuantizationSpec, + SharedQuantizationSpec, +) +from torchao.quantization.pt2e.quantizer.utils import ( + annotate_input_qspec_map, + annotate_output_qspec, +) +from torchao.quantization.pt2e.utils import ( + _get_aten_graph_module_for_pattern, + _is_conv_node, + _is_conv_transpose_node, + get_new_attr_name_with_prefix, +) + +__all__ = [ + "OperatorConfig", + "OperatorPatternType", + "QuantizationConfig", + "get_input_act_qspec", + "get_output_act_qspec", + "get_weight_qspec", + "get_bias_qspec", + "OP_TO_ANNOTATOR", + "propagate_annotation", +] + + +# In the absence of better name, just winging it with QuantizationConfig +@dataclass(eq=True, frozen=True) +class QuantizationConfig: + input_activation: Optional[QuantizationSpec] + output_activation: Optional[QuantizationSpec] + weight: Optional[QuantizationSpec] + bias: Optional[QuantizationSpec] + # TODO: remove, since we can use observer_or_fake_quant_ctr to express this + is_qat: bool = False + + +# Use Annotated because list[Callable].__module__ is read-only. +OperatorPatternType = typing.Annotated[list[Callable], None] +OperatorPatternType.__module__ = ( + "torchao.quantization.pt2e.quantizer.xnnpack_quantizer_utils" +) + +AnnotatorType = Callable[ + [ + torch.fx.GraphModule, + Optional[QuantizationConfig], + Optional[Callable[[Node], bool]], + ], + Optional[list[list[Node]]], +] +OP_TO_ANNOTATOR: dict[str, AnnotatorType] = {} + + +def register_annotator(op: str) -> Callable[[AnnotatorType], None]: + def decorator(annotator: AnnotatorType) -> None: + OP_TO_ANNOTATOR[op] = annotator + + return decorator + + +class OperatorConfig(NamedTuple): + # fix List[str] with List[List[Union[nn.Module, FunctionType, BuiltinFunctionType]]] + # Basically we are mapping a quantization config to some list of patterns. + # a pattern is defined as a list of nn module, function or builtin function names + # e.g. [nn.Conv2d, torch.relu, torch.add] + # We have not resolved whether fusion can be considered internal details of the + # quantizer hence it does not need communication to user. + # Note this pattern is not really informative since it does not really + # tell us the graph structure resulting from the list of ops. + config: QuantizationConfig + operators: list[OperatorPatternType] + + +def _is_annotated(nodes: list[Node]): + """ + Given a list of nodes (that represents an operator pattern), + check if any of the node is annotated, return True if any of the node + is annotated, otherwise return False + """ + annotated = False + for node in nodes: + annotated = annotated or ( + "quantization_annotation" in node.meta + and node.meta["quantization_annotation"]._annotated + ) + return annotated + + +def _mark_nodes_as_annotated(nodes: list[Node]): + for node in nodes: + if node is not None: + if "quantization_annotation" not in node.meta: + node.meta["quantization_annotation"] = QuantizationAnnotation() + node.meta["quantization_annotation"]._annotated = True + + +def get_input_act_qspec(quantization_config: Optional[QuantizationConfig]): + if quantization_config is None: + return None + if quantization_config.input_activation is None: + return None + quantization_spec: QuantizationSpec = quantization_config.input_activation + assert quantization_spec.qscheme in [ + torch.per_tensor_affine, + torch.per_tensor_symmetric, + ] + return quantization_spec + + +def get_output_act_qspec(quantization_config: Optional[QuantizationConfig]): + if quantization_config is None: + return None + if quantization_config.output_activation is None: + return None + quantization_spec: QuantizationSpec = quantization_config.output_activation + assert quantization_spec.qscheme in [ + torch.per_tensor_affine, + torch.per_tensor_symmetric, + ] + return quantization_spec + + +def get_weight_qspec(quantization_config: Optional[QuantizationConfig]): + if quantization_config is None: + return None + assert quantization_config is not None + if quantization_config.weight is None: + return None + quantization_spec: QuantizationSpec = quantization_config.weight + if quantization_spec.qscheme not in [ + torch.per_tensor_symmetric, + torch.per_channel_symmetric, + None, + ]: + raise ValueError( + f"Unsupported quantization_spec {quantization_spec} for weight" + ) + return quantization_spec + + +def get_bias_qspec(quantization_config: Optional[QuantizationConfig]): + if quantization_config is None: + return None + assert quantization_config is not None + if quantization_config.bias is None: + return None + quantization_spec: QuantizationSpec = quantization_config.bias + assert quantization_spec.dtype == torch.float, ( + "Only float dtype for bias is supported for bias right now" + ) + return quantization_spec + + +@register_annotator("linear") +def _annotate_linear( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + annotated_partitions = [] + input_act_qspec = get_input_act_qspec(quantization_config) + output_act_qspec = get_output_act_qspec(quantization_config) + weight_qspec = get_weight_qspec(quantization_config) + bias_qspec = get_bias_qspec(quantization_config) + for node in gm.graph.nodes: + if node.op != "call_function" or node.target != torch.ops.aten.linear.default: + continue + if filter_fn and not filter_fn(node): + continue + act_node = node.args[0] + weight_node = node.args[1] + bias_node = None + if len(node.args) > 2: + bias_node = node.args[2] + + if _is_annotated([node]) is False: # type: ignore[list-item] + annotate_input_qspec_map( + node, + act_node, + input_act_qspec, + ) + annotate_input_qspec_map( + node, + weight_node, + weight_qspec, + ) + nodes_to_mark_annotated = [node, weight_node] + if bias_node: + annotate_input_qspec_map( + node, + bias_node, + bias_qspec, + ) + nodes_to_mark_annotated.append(bias_node) + annotate_output_qspec(node, output_act_qspec) + _mark_nodes_as_annotated(nodes_to_mark_annotated) + annotated_partitions.append(nodes_to_mark_annotated) + + return annotated_partitions + + +@register_annotator("linear_relu") +def _annotate_linear_relu( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + annotated_partitions = [] + input_act_qspec = get_input_act_qspec(quantization_config) + output_act_qspec = get_output_act_qspec(quantization_config) + weight_qspec = get_weight_qspec(quantization_config) + bias_qspec = get_bias_qspec(quantization_config) + for node in gm.graph.nodes: + if node.op != "call_function" or node.target not in [ + torch.ops.aten.relu.default, + torch.ops.aten.relu_.default, + ]: + continue + relu_node = node + maybe_linear_node = node.args[0] + if ( + not isinstance(maybe_linear_node, Node) + or maybe_linear_node.op != "call_function" + or maybe_linear_node.target != torch.ops.aten.linear.default + ): + continue + + linear_node = maybe_linear_node + if len(linear_node.users) > 1: + # if linear node has multiple users, then it can't be fused with relu + continue + + input_qspec_map = {} + input_act = linear_node.args[0] + assert isinstance(input_act, Node) + input_qspec_map[input_act] = input_act_qspec + + weight = linear_node.args[1] + assert isinstance(weight, Node) + input_qspec_map[weight] = weight_qspec + + # adding weight node to the partition as well + partition = [relu_node, linear_node, weight] + bias = linear_node.args[2] if len(linear_node.args) > 2 else None + if isinstance(bias, Node): + input_qspec_map[bias] = bias_qspec + partition.append(bias) + + if _is_annotated(partition): + continue + + if filter_fn and any(not filter_fn(n) for n in partition): + continue + + linear_node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + ) + relu_node.meta["quantization_annotation"] = QuantizationAnnotation( + output_qspec=output_act_qspec, + _annotated=True, + ) + _mark_nodes_as_annotated(partition) + annotated_partitions.append(partition) + return annotated_partitions + + +@register_annotator("conv") +def _annotate_conv( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + annotated_partitions = [] + for n in gm.graph.nodes: + if n.op != "call_function" or n.target not in [ + torch.ops.aten.conv1d.default, + torch.ops.aten.conv2d.default, + ]: + continue + conv_node = n + + input_qspec_map = {} + input_act = conv_node.args[0] + assert isinstance(input_act, Node) + input_qspec_map[input_act] = get_input_act_qspec(quantization_config) + + weight = conv_node.args[1] + assert isinstance(weight, Node) + input_qspec_map[weight] = get_weight_qspec(quantization_config) + + # adding weight node to the partition as well + partition = [conv_node, conv_node.args[1]] + + bias = conv_node.args[2] if len(conv_node.args) > 2 else None + if isinstance(bias, Node): + input_qspec_map[bias] = get_bias_qspec(quantization_config) + partition.append(bias) + + if _is_annotated(partition): + continue + + if filter_fn and any(not filter_fn(n) for n in partition): + continue + + conv_node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map=input_qspec_map, + output_qspec=get_output_act_qspec(quantization_config), + _annotated=True, + ) + _mark_nodes_as_annotated(partition) + annotated_partitions.append(partition) + return annotated_partitions + + +def _do_annotate_conv_relu( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, + is_conv_transpose: bool = False, +): + annotated_partitions = [] + for n in gm.graph.nodes: + if n.op != "call_function" or n.target not in [ + torch.ops.aten.relu.default, + torch.ops.aten.relu_.default, + ]: + continue + relu_node = n + maybe_conv_node = n.args[0] + + is_conv_node = _is_conv_transpose_node if is_conv_transpose else _is_conv_node + if not isinstance(maybe_conv_node, Node) or not is_conv_node(maybe_conv_node): + continue + conv_node = maybe_conv_node + + if len(conv_node.users) > 1: + # relu shouldn't be fuseable to conv if there are other users + # of convolution + continue + + input_qspec_map = {} + input_act = conv_node.args[0] + assert isinstance(input_act, Node) + input_qspec_map[input_act] = get_input_act_qspec(quantization_config) + + weight = conv_node.args[1] + assert isinstance(weight, Node) + input_qspec_map[weight] = get_weight_qspec(quantization_config) + + # adding weight node to the partition as well + partition = [relu_node, conv_node, conv_node.args[1]] + bias = conv_node.args[2] if len(conv_node.args) > 2 else None + if isinstance(bias, Node): + input_qspec_map[bias] = get_bias_qspec(quantization_config) + partition.append(bias) + + if _is_annotated(partition): + continue + + if filter_fn and any(not filter_fn(n) for n in partition): + continue + + conv_node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map=input_qspec_map, _annotated=True + ) + relu_node.meta["quantization_annotation"] = QuantizationAnnotation( + output_qspec=get_output_act_qspec(quantization_config), # type: ignore[arg-type] + _annotated=True, + ) + _mark_nodes_as_annotated(partition) + annotated_partitions.append(partition) + return annotated_partitions + + +@register_annotator("conv_relu") +def _annotate_conv_relu( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + return _do_annotate_conv_relu( + gm, quantization_config, filter_fn, is_conv_transpose=False + ) + + +@register_annotator("conv_transpose_relu") +def _annotate_conv_transpose_relu( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + return _do_annotate_conv_relu( + gm, quantization_config, filter_fn, is_conv_transpose=True + ) + + +@register_annotator("conv_bn") +def _annotate_conv_bn( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + """ + Find conv + batchnorm parititions + Note: This is only used for QAT. In PTQ, batchnorm should already be fused into the conv. + """ + return _do_annotate_conv_bn(gm, quantization_config, filter_fn, has_relu=False) + + +@register_annotator("conv_bn_relu") +def _annotate_conv_bn_relu( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + """ + Find conv + batchnorm + relu parititions + Note: This is only used for QAT. In PTQ, batchnorm should already be fused into the conv. + """ + return _do_annotate_conv_bn(gm, quantization_config, filter_fn, has_relu=True) + + +@register_annotator("conv_transpose_bn") +def _annotate_conv_transpose_bn( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + """ + Find conv_transpose + batchnorm parititions + Note: This is only used for QAT. In PTQ, batchnorm should already be fused into the conv. + """ + return _do_annotate_conv_bn( + gm, quantization_config, filter_fn, has_relu=False, is_conv_transpose=True + ) + + +@register_annotator("conv_transpose_bn_relu") +def _annotate_conv_transpose_bn_relu( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + """ + Find conv_transpose + batchnorm + relu parititions + Note: This is only used for QAT. In PTQ, batchnorm should already be fused into the conv. + """ + return _do_annotate_conv_bn( + gm, quantization_config, filter_fn, has_relu=True, is_conv_transpose=True + ) + + +def _do_annotate_conv_bn( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]], + has_relu: bool, + is_conv_transpose: bool = False, +) -> list[list[Node]]: + """ + Given a function that takes in a `conv_fn` and returns a conv-bn[-relu] pattern, + return a list of annotated partitions. + + The output of the pattern must include a dictionary from string name to node + for the following names: "input", "conv", "weight", "bias", and "output". + """ + + # Example inputs for conv-bn1d patterns + _conv1d_bn_example_inputs = ( + torch.randn(1, 1, 3), # x + torch.randn(1, 1, 1), # conv_weight + torch.randn(1), # conv_bias + torch.randn(1), # bn_weight + torch.randn(1), # bn_bias + torch.randn(1), # bn_running_mean + torch.randn(1), # bn_running_var + ) + + # Example inputs for conv-bn2d patterns + _conv2d_bn_example_inputs = ( + torch.randn(1, 1, 3, 3), # x + torch.randn(1, 1, 1, 1), # conv_weight + torch.randn(1), # conv_bias + torch.randn(1), # bn_weight + torch.randn(1), # bn_bias + torch.randn(1), # bn_running_mean + torch.randn(1), # bn_running_var + ) + + def get_pattern(conv_fn: Callable, relu_is_inplace: bool): + def _conv_bn(x, conv_weight, conv_bias, bn_weight, bn_bias, bn_rm, bn_rv): + conv = conv_fn(x, conv_weight, conv_bias) + bn = F.batch_norm(conv, bn_rm, bn_rv, bn_weight, bn_bias, training=True) + if has_relu: + output = F.relu_(bn) if relu_is_inplace else F.relu(bn) + else: + output = bn + return output, { + "input": x, + "conv": conv, + "weight": conv_weight, + "bias": conv_bias, + "output": output, + } + + return WrapperModule(_conv_bn) + + # Needed for matching, otherwise the matches gets filtered out due to unused + # nodes returned by batch norm + gm.graph.eliminate_dead_code() + gm.recompile() + + matches = [] + if is_conv_transpose: + combinations = [ + (F.conv_transpose1d, _conv1d_bn_example_inputs), + (F.conv_transpose2d, _conv2d_bn_example_inputs), + ] + else: + combinations = [ + (F.conv1d, _conv1d_bn_example_inputs), # type: ignore[list-item] + (F.conv2d, _conv2d_bn_example_inputs), # type: ignore[list-item] + ] + + # Add `is_cuda` and `relu_is_inplace` dimensions + combinations = itertools.product( # type: ignore[assignment] + combinations, + [True, False] if torch.cuda.is_available() else [False], # is_cuda + [True, False] if has_relu else [False], # relu_is_inplace + ) + + # Match against all conv dimensions and cuda variants + for (conv_fn, example_inputs), is_cuda, relu_is_inplace in combinations: # type: ignore[misc] + pattern = get_pattern(conv_fn, relu_is_inplace) # type: ignore[has-type] + pattern = _get_aten_graph_module_for_pattern(pattern, example_inputs, is_cuda) # type: ignore[has-type] + pattern.graph.eliminate_dead_code() + pattern.recompile() + matcher = SubgraphMatcherWithNameNodeMap(pattern, ignore_literals=True) + matches.extend(matcher.match(gm.graph)) + + # Annotate nodes returned in the matches + annotated_partitions = [] + for match in matches: + name_node_map = match.name_node_map + input_node = name_node_map["input"] + conv_node = name_node_map["conv"] + weight_node = name_node_map["weight"] + bias_node = name_node_map["bias"] + output_node = name_node_map["output"] + + # TODO: annotate the uses of input, weight, and bias separately instead + # of assuming they come from a single conv node. This is not possible today + # because input may have multiple users, and we can't rely on the conv node + # always being the first user. This was the case in models with skip + # connections like resnet18 + + # Validate conv args + if conv_node.args[0] is not input_node: + raise ValueError("Conv arg did not contain input node ", input_node) + if conv_node.args[1] is not weight_node: + raise ValueError("Conv arg did not contain weight node ", weight_node) + if len(conv_node.args) > 2 and conv_node.args[2] is not bias_node: + raise ValueError("Conv arg did not contain bias node ", bias_node) + + # Skip if the partition is already annotated or is filtered out by the user + partition = [conv_node, weight_node] + if bias_node is not None: + partition.append(bias_node) + if _is_annotated(partition): + continue + if filter_fn and any(not filter_fn(n) for n in partition): + continue + + # Annotate conv inputs and pattern output + input_qspec_map = {} + input_qspec_map[input_node] = get_input_act_qspec(quantization_config) + input_qspec_map[weight_node] = get_weight_qspec(quantization_config) + if bias_node is not None: + input_qspec_map[bias_node] = get_bias_qspec(quantization_config) + conv_node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + ) + output_node.meta["quantization_annotation"] = QuantizationAnnotation( + output_qspec=get_output_act_qspec(quantization_config), # type: ignore[arg-type] + _annotated=True, + ) + _mark_nodes_as_annotated(partition) + annotated_partitions.append(partition) + return annotated_partitions + + +@register_annotator("gru_io_only") +def _annotate_gru_io_only( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + gru_partitions = get_source_partitions(gm.graph, [torch.nn.GRU], filter_fn) + gru_partitions = list(itertools.chain.from_iterable(gru_partitions.values())) + annotated_partitions = [] + for gru_partition in gru_partitions: + annotated_partitions.append(gru_partition.nodes) + output_nodes = gru_partition.output_nodes + input_nodes = gru_partition.input_nodes + # skip annotation if it is already annotated + if _is_annotated(input_nodes + output_nodes): + continue + # inside each GRU partition, we should be able to annotate each linear + # subgraph + input_act = input_nodes[0] + input_act_user = next(iter(input_act.users.keys())) + assert isinstance(input_act, Node) + assert isinstance(input_act_user, Node) + input_act_user.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map={ + input_act: get_input_act_qspec(quantization_config), + }, + _annotated=True, + ) + + hidden_state = input_nodes[1] + hidden_state_user = next(iter(hidden_state.users.keys())) + assert isinstance(hidden_state, Node) + assert isinstance(hidden_state_user, Node) + hidden_state_user.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map={ + hidden_state: get_input_act_qspec(quantization_config), + }, + _annotated=True, + ) + + assert len(output_nodes) == 2, "expecting GRU to have two outputs" + for output in output_nodes: + output.meta["quantization_annotation"] = QuantizationAnnotation( + output_qspec=get_output_act_qspec(quantization_config), + _annotated=True, + ) + nodes_to_mark_annotated = list(gru_partition.nodes) + _mark_nodes_as_annotated(nodes_to_mark_annotated) + return annotated_partitions + + +@register_annotator("adaptive_avg_pool2d") +def _annotate_adaptive_avg_pool2d( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + """Always annotate adaptive_avg_pool2d op""" + module_partitions = get_source_partitions( + gm.graph, [torch.nn.AdaptiveAvgPool2d, F.adaptive_avg_pool2d], filter_fn + ) + partitions = list(itertools.chain.from_iterable(module_partitions.values())) + annotated_partitions = [] + for partition in partitions: + pool_node = partition.output_nodes[0] + if ( + pool_node.op != "call_function" + or pool_node.target != torch.ops.aten.adaptive_avg_pool2d.default + ): + raise ValueError(f"{pool_node} is not an aten adaptive_avg_pool2d operator") + + if _is_annotated([pool_node]): + continue + + annotated_partitions.append(partition.nodes) + input_act = pool_node.args[0] + assert isinstance(input_act, Node) + + # only annotate input output sharing operator + # when the output of the input node is annotated + if ( + "quantization_annotation" not in input_act.meta + or not input_act.meta["quantization_annotation"]._annotated + or input_act.meta["quantization_annotation"].output_qspec is None + ): + input_act_qspec = get_input_act_qspec(quantization_config) + else: + input_act_qspec = SharedQuantizationSpec(input_act) + + # output sharing with input + output_act_qspec = SharedQuantizationSpec((input_act, pool_node)) + pool_node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map={ + input_act: input_act_qspec, + }, + output_qspec=output_act_qspec, + _annotated=True, + ) + return annotated_partitions + + +def _is_input_large_scalar(node: Node, gm: torch.fx.GraphModule): + """Check if input is a large scalar value. So that we can skip quantization for the node + since histc op (in HistogramObserver) only works for values up to certain upper bound + """ + if node.op == "get_attr": + qualified_name = str(node.target) + module_path, _, name = qualified_name.rpartition(".") + submod = gm.get_submodule(module_path) + tensor = getattr(submod, name) + # torch.histc works until this upper bound + HISTC_UPPER_BOUND = 3.4028235e15 + return tensor.numel() == 1 and abs(tensor.item()) > HISTC_UPPER_BOUND + return False + + +def _is_input_non_float_tensor(node: Node): + """Check if the input is not a float tensor, so that we can skip quantization for the node + since observers only works with float Tensors + """ + if "val" not in node.meta or not isinstance(node.meta["val"], FakeTensor): + return True + return node.meta["val"].dtype != torch.float32 + + +@register_annotator("add_relu") +def _annotate_add_relu( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + annotated_partitions = [] + for node in gm.graph.nodes: + if node.op != "call_function" or node.target not in [ + torch.ops.aten.relu.default, + torch.ops.aten.relu_.default, + ]: + continue + relu_node = node + maybe_add = node.args[0] + if ( + not isinstance(maybe_add, Node) + or maybe_add.op != "call_function" + or maybe_add.target + not in [ + torch.ops.aten.add.Tensor, + torch.ops.aten.add_.Tensor, + ] + ): + continue + + add_node = maybe_add + + if len(add_node.users) > 1: + # add can't be fused with ReLU if the result of add is being used + # else where in the graph + continue + + partition = [relu_node, add_node] + + if _is_annotated(partition): + continue + + if filter_fn and any(not filter_fn(n) for n in partition): + continue + + input_act_qspec = get_input_act_qspec(quantization_config) + output_act_qspec = get_output_act_qspec(quantization_config) + + input_qspec_map = {} + input_act0 = add_node.args[0] + if isinstance(input_act0, Node): + if _is_input_large_scalar(input_act0, gm): + continue + if _is_input_non_float_tensor(input_act0): + continue + partition.append(input_act0) + input_qspec_map[input_act0] = input_act_qspec + + input_act1 = add_node.args[1] + if isinstance(input_act1, Node): + if _is_input_large_scalar(input_act1, gm): + continue + if _is_input_non_float_tensor(input_act1): + continue + partition.append(input_act1) + input_qspec_map[input_act1] = input_act_qspec + + add_node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + ) + relu_node.meta["quantization_annotation"] = QuantizationAnnotation( + output_qspec=output_act_qspec, + _annotated=True, + ) + annotated_partitions.append(partition) + return annotated_partitions + + +@register_annotator("add") +def _annotate_add( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + annotated_partitions = [] + for node in gm.graph.nodes: + if node.op != "call_function" or node.target not in [ + torch.ops.aten.add.Tensor, + torch.ops.aten.add_.Tensor, + ]: + continue + add_node = node + partition = [add_node] + + if _is_annotated(partition): + continue + + if filter_fn and any(not filter_fn(n) for n in partition): + continue + + input_act_qspec = get_input_act_qspec(quantization_config) + output_act_qspec = get_output_act_qspec(quantization_config) + + input_qspec_map = {} + input_act0 = add_node.args[0] + if isinstance(input_act0, Node): + if _is_input_large_scalar(input_act0, gm): + continue + if _is_input_non_float_tensor(input_act0): + continue + input_qspec_map[input_act0] = input_act_qspec + partition.append(input_act0) + + input_act1 = add_node.args[1] + if isinstance(input_act1, Node): + if _is_input_large_scalar(input_act1, gm): + continue + if _is_input_non_float_tensor(input_act1): + continue + input_qspec_map[input_act1] = input_act_qspec + partition.append(input_act1) + + add_node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map=input_qspec_map, + output_qspec=output_act_qspec, + _annotated=True, + ) + annotated_partitions.append(partition) + return annotated_partitions + + +@register_annotator("mul_relu") +def _annotate_mul_relu( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + annotated_partitions = [] + for node in gm.graph.nodes: + if node.op != "call_function" or node.target not in [ + torch.ops.aten.relu.default, + torch.ops.aten.relu_.default, + ]: + continue + relu_node = node + maybe_mul = node.args[0] + if ( + not isinstance(maybe_mul, Node) + or maybe_mul.op != "call_function" + or maybe_mul.target + not in [ + torch.ops.aten.mul.Tensor, + torch.ops.aten.mul_.Tensor, + ] + ): + continue + + mul_node = maybe_mul + if len(mul_node.users) > 1: + # mul can't be fused with ReLU if the result of mul is being used + # else where in the graph + continue + + partition = [relu_node, mul_node] + + if _is_annotated(partition): + continue + + if filter_fn and any(not filter_fn(n) for n in partition): + continue + + input_act_qspec = get_input_act_qspec(quantization_config) + output_act_qspec = get_output_act_qspec(quantization_config) + + input_qspec_map = {} + input_act0 = mul_node.args[0] + if isinstance(input_act0, Node): + if _is_input_large_scalar(input_act0, gm): + continue + if _is_input_non_float_tensor(input_act0): + continue + partition.append(input_act0) + input_qspec_map[input_act0] = input_act_qspec + + input_act1 = mul_node.args[1] + if isinstance(input_act1, Node): + if _is_input_large_scalar(input_act1, gm): + continue + if _is_input_non_float_tensor(input_act1): + continue + partition.append(input_act1) + input_qspec_map[input_act1] = input_act_qspec + + mul_node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map=input_qspec_map, + _annotated=True, + ) + relu_node.meta["quantization_annotation"] = QuantizationAnnotation( + output_qspec=output_act_qspec, + _annotated=True, + ) + annotated_partitions.append(partition) + return annotated_partitions + + +@register_annotator("mul") +def _annotate_mul( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + annotated_partitions = [] + for node in gm.graph.nodes: + if node.op != "call_function" or node.target not in [ + torch.ops.aten.mul.Tensor, + torch.ops.aten.mul_.Tensor, + ]: + continue + + mul_node = node + partition = [mul_node] + if _is_annotated(partition): + continue + + if filter_fn and any(not filter_fn(n) for n in partition): + continue + + input_act_qspec = get_input_act_qspec(quantization_config) + output_act_qspec = get_output_act_qspec(quantization_config) + + input_qspec_map = {} + input_act0 = mul_node.args[0] + if isinstance(input_act0, Node): + if _is_input_large_scalar(input_act0, gm): + continue + if _is_input_non_float_tensor(input_act0): + continue + input_qspec_map[input_act0] = input_act_qspec + partition.append(input_act0) + + input_act1 = mul_node.args[1] + if isinstance(input_act1, Node): + if _is_input_large_scalar(input_act1, gm): + continue + if _is_input_non_float_tensor(input_act1): + continue + input_qspec_map[input_act1] = input_act_qspec + partition.append(input_act0) + + mul_node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map=input_qspec_map, + output_qspec=output_act_qspec, + _annotated=True, + ) + annotated_partitions.append(partition) + return annotated_partitions + + +# TODO: remove Optional in return type, fix annotated_partitions logic +@register_annotator("cat") +def _annotate_cat( + gm: torch.fx.GraphModule, + quantization_config: Optional[QuantizationConfig], + filter_fn: Optional[Callable[[Node], bool]] = None, +) -> Optional[list[list[Node]]]: + cat_partitions = get_source_partitions(gm.graph, [torch.cat], filter_fn) + cat_partitions = list(itertools.chain.from_iterable(cat_partitions.values())) + annotated_partitions = [] + for cat_partition in cat_partitions: + cat_node = cat_partition.output_nodes[0] + if _is_annotated([cat_node]): + continue + + if cat_node.target != torch.ops.aten.cat.default: + # TODO: change this to AnnotationException + raise Exception( # noqa: TRY002 + f"Expected cat node: torch.ops.aten.cat.default, but found {cat_node.target}" + " please check if you are calling the correct capture API" + ) + + annotated_partitions.append(cat_partition.nodes) + + input_act_qspec = get_input_act_qspec(quantization_config) + inputs = cat_node.args[0] + + input_qspec_map = {} + input_act0 = inputs[0] # type: ignore[index] + if isinstance(input_act0, Node): + input_qspec_map[input_act0] = input_act_qspec + + shared_with_input0_qspec = SharedQuantizationSpec((input_act0, cat_node)) # type: ignore[arg-type] + for input_act in inputs[1:]: # type: ignore[index, union-attr] + if input_act not in input_qspec_map: + input_qspec_map[input_act] = shared_with_input0_qspec # type: ignore[index] + + output_act_qspec = shared_with_input0_qspec + + cat_node.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map=input_qspec_map, + output_qspec=output_act_qspec, + _annotated=True, + ) + return annotated_partitions + + +def _is_share_obs_or_fq_op(op: Callable) -> bool: + return op in [ + torch.ops.aten.relu.default, + torch.ops.aten.hardtanh.default, + torch.ops.aten.hardtanh_.default, + torch.ops.aten.max_pool2d.default, + torch.ops.aten.mean.default, + torch.ops.aten.mean.dim, + torch.ops.aten.permute.default, + torch.ops.aten.permute_copy.default, + torch.ops.aten.squeeze.dim, + torch.ops.aten.squeeze_copy.dim, + # TODO: remove? + torch.ops.aten.adaptive_avg_pool2d.default, + torch.ops.aten.view_copy.default, + torch.ops.aten.view.default, + torch.ops.aten.slice_copy.Tensor, + torch.ops.aten.flatten.using_ints, + ] + + +def propagate_annotation(model: torch.fx.GraphModule) -> None: + for n in model.graph.nodes: + if n.op != "call_function" or not _is_share_obs_or_fq_op(n.target): + continue + + prev_node = n.args[0] + if not isinstance(prev_node, Node): + continue + + quantization_annotation = prev_node.meta.get("quantization_annotation", None) + if not quantization_annotation: + continue + + output_qspec = quantization_annotation.output_qspec + if not output_qspec: + continue + + # make sure current node is not annotated + if ( + "quantization_annotation" in n.meta + and n.meta["quantization_annotation"]._annotated + ): + continue + + shared_qspec = SharedQuantizationSpec(prev_node) + # propagate the previous output_qspec to the current node + n.meta["quantization_annotation"] = QuantizationAnnotation( + input_qspec_map={ + prev_node: shared_qspec, + }, + output_qspec=shared_qspec, + _annotated=True, + ) + + +# TODO: make the list of ops customizable +def _convert_scalars_to_attrs(model: torch.fx.GraphModule) -> torch.fx.GraphModule: + for n in model.graph.nodes: + if n.op != "call_function" or n.target not in [ + torch.ops.aten.add.Tensor, + torch.ops.aten.mul.Tensor, + ]: + continue + args = list(n.args) + new_args = [] + for i in range(len(args)): + if isinstance(args[i], torch.fx.Node): + new_args.append(args[i]) + continue + prefix = "_tensor_constant_" + get_new_attr_name = get_new_attr_name_with_prefix(prefix) + tensor_constant_name = get_new_attr_name(model) + float_tensor = torch.tensor(float(args[i])) + model.register_buffer(tensor_constant_name, float_tensor) + fake_mode = n.meta["val"].fake_mode + with model.graph.inserting_before(n): + get_attr_node = model.graph.create_node( + "get_attr", tensor_constant_name, (), {} + ) + get_attr_node.meta["val"] = fake_mode.from_tensor( + float_tensor, static_shapes=True + ) + new_args.append(get_attr_node) + n.args = tuple(new_args) + model.recompile() + return model diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c4773231a55bfe38e2420b6f6e23a98ea2a1d41d --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/pt2e/utils.py @@ -0,0 +1,206 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +import copy +import unittest + +import torch +from torch.ao.quantization.backend_config import ( + get_executorch_backend_config, +) +from torch.ao.quantization.quantize_fx import ( + _convert_to_reference_decomposed_fx, + prepare_fx, +) +from torch.testing._internal.common_quantization import ( + NodeSpec, + QuantizationTestCase, +) +from torch.testing._internal.common_utils import TestCase + +from torchao.quantization.pt2e import FROM_NODE_KEY +from torchao.quantization.pt2e._numeric_debugger import _extract_node_source_debug_info +from torchao.quantization.pt2e.graph_utils import bfs_trace_with_node_process +from torchao.quantization.pt2e.quantize_pt2e import ( + convert_pt2e, + prepare_pt2e, + prepare_qat_pt2e, +) +from torchao.utils import TORCH_VERSION_AT_LEAST_2_5, TORCH_VERSION_AT_LEAST_2_7 + +if TORCH_VERSION_AT_LEAST_2_5: + from torch.export import export_for_training + + +@unittest.skipIf( + not TORCH_VERSION_AT_LEAST_2_5, + "only works for torch 2.5+ since export_for_training is only supported after 2.5", +) +class PT2EQuantizationTestCase(QuantizationTestCase): + """ + Base QuantizationTestCase for PT2 with some helper methods. + """ + + _MAP_TO_FX_TRACED_OPS = { + torch.ops.quantized_decomposed.quantize_per_tensor: torch.ops.quantized_decomposed.quantize_per_tensor.default, + torch.ops.quantized_decomposed.dequantize_per_tensor: torch.ops.quantized_decomposed.dequantize_per_tensor.default, + torch.ops.quantized_decomposed.quantize_per_channel: torch.ops.quantized_decomposed.quantize_per_channel.default, + torch.ops.quantized_decomposed.dequantize_per_channel: torch.ops.quantized_decomposed.dequantize_per_channel.default, + torch.ops.quantized_decomposed.quantize_per_tensor.tensor: torch.ops.quantized_decomposed.quantize_per_tensor.tensor, + torch.ops.quantized_decomposed.dequantize_per_tensor.tensor: torch.ops.quantized_decomposed.dequantize_per_tensor.tensor, + } + + def _test_quantizer( + self, + model, + example_inputs, + quantizer, + expected_node_occurrence, + expected_node_list=None, + check_against_fx_quant=False, + # TODO: remove the test if fx quant is removed from pytorch + fx_qconfig_mapping=None, + export_with_dynamic_shape=False, + is_qat=False, + is_debug_mode=False, + training_ir_node_occurrence=None, + ): + # resetting dynamo cache + torch._dynamo.reset() + m_eager = model.eval() + + # program capture + m = copy.deepcopy(m_eager) + dynamic_shapes = tuple( + {0: torch.export.Dim("dim")} if i == 0 else None + for i in range(len(example_inputs)) + ) + m = export_for_training( + m, + example_inputs, + dynamic_shapes=dynamic_shapes if export_with_dynamic_shape else None, + strict=True, + ).module() + + if is_qat: + m = prepare_qat_pt2e(m, quantizer) + else: + m = prepare_pt2e(m, quantizer) + if is_debug_mode: + print("prepared model:", m) + # Calibrate + m(*example_inputs) + m = convert_pt2e(m) + if is_debug_mode: + print("quantized model", m) + + pt2_quant_output = m(*example_inputs) + ns = NodeSpec + node_occurrence = { + ns.call_function(k): v for k, v in expected_node_occurrence.items() + } + if expected_node_list is None: + expected_node_list = [] + node_list = [ns.call_function(n) for n in expected_node_list] + self.checkGraphModuleNodes( + m, expected_node_occurrence=node_occurrence, expected_node_list=node_list + ) + if check_against_fx_quant: + qconfig_mapping = fx_qconfig_mapping + backend_config = get_executorch_backend_config() + m_copy = copy.deepcopy(m_eager) + m_fx = prepare_fx( + m_copy, qconfig_mapping, example_inputs, backend_config=backend_config + ) + m_fx(*example_inputs) + m_fx = _convert_to_reference_decomposed_fx( + m_fx, backend_config=backend_config + ) + m_fx = export_for_training( + m_fx, + example_inputs, + dynamic_shapes=dynamic_shapes if export_with_dynamic_shape else None, + ).module() + node_occurrence = {} + for k, v in PT2EQuantizationTestCase._MAP_TO_FX_TRACED_OPS.items(): + if k in expected_node_occurrence: + node_occurrence[ns.call_function(v)] = expected_node_occurrence[k] + if training_ir_node_occurrence is not None: + node_occurrence = { + ns.call_function(k): v + for k, v in training_ir_node_occurrence.items() + } + self.checkGraphModuleNodes(m_fx, expected_node_occurrence=node_occurrence) + fx_quant_output = m_fx(*example_inputs) + self.assertEqual(fx_quant_output, pt2_quant_output) + return m + + +@unittest.skipIf(not TORCH_VERSION_AT_LEAST_2_7, "Requires torch 2.7+") +class PT2ENumericDebuggerTestCase(TestCase): + """ + Base test case class for PT2E numeric debugger tests containing common utility functions + for numeric debugging functionality. + """ + + def _assert_each_node_has_from_node_source(self, model) -> None: + def _assert_node_has_from_node_source(node): + if node.op == "placeholder" or node.op == "output": + return + self.assertIn( + FROM_NODE_KEY, + node.meta, + f"Node {node} doesn't have from_node info", + ) + + bfs_trace_with_node_process(model, _assert_node_has_from_node_source) + + def _extract_from_node_source(self, model) -> dict[str, any]: + from_node_source_map: dict[str, any] = {} + + def _extract_from_node_source_from_node(node): + nonlocal from_node_source_map + if (root_node_source := _extract_node_source_debug_info(node)) is not None: + from_node_source_map[str(node)] = ( + root_node_source.name, + root_node_source.graph_id, + ) + + bfs_trace_with_node_process(model, _extract_from_node_source_from_node) + + return from_node_source_map + + def _extract_from_node_source_with_prev_decomp_op(self, model) -> dict[str, any]: + prev_decomp_op_to_from_node_source_map: dict[str, any] = {} + + def _extract_from_node_source_with_prev_decomp_op_from_node(node): + nonlocal prev_decomp_op_to_from_node_source_map + if FROM_NODE_KEY in node.meta and node.meta[FROM_NODE_KEY] is not None: + prev_decomp_op = str(node.meta.get("nn_module_stack")) + from_node_source = _extract_node_source_debug_info(node) + if prev_decomp_op not in prev_decomp_op_to_from_node_source_map: + prev_decomp_op_to_from_node_source_map[prev_decomp_op] = ( + from_node_source + ) + else: + assert ( + prev_decomp_op_to_from_node_source_map[prev_decomp_op] + == from_node_source + ), ( + f"Node {node} has different from_node info {from_node_source}" + f"than previous node sharing the same decomp op {prev_decomp_op}" + ) + + bfs_trace_with_node_process( + model, _extract_from_node_source_with_prev_decomp_op_from_node + ) + return prev_decomp_op_to_from_node_source_map + + def assertNodeSourcesEqual(self, node_source_1, node_source_2): + self.assertTrue( + node_source_1.name == node_source_2.name + and node_source_1.graph_id == node_source_2.graph_id + ) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/__init__.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/dtensor_utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/dtensor_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..acbfbb6a3e4b3988e2bd62873fece2e1bdefc3cc --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/dtensor_utils.py @@ -0,0 +1,182 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import copy +from typing import Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.distributed._tensor import Replicate, Shard, distribute_tensor +from torch.distributed.device_mesh import DeviceMesh +from torch.distributed.tensor.parallel import ( + ColwiseParallel, + PrepareModuleInput, + RowwiseParallel, + parallelize_module, +) + +from torchao.float8 import Float8LinearConfig +from torchao.float8.float8_linear_utils import convert_to_float8_training +from torchao.float8.float8_tensor_parallel import ( + Float8ColwiseParallel, + Float8RowwiseParallel, + PrepareFloat8ModuleInput, +) +from torchao.prototype.mx_formats.config import MXLinearConfig +from torchao.quantization import quantize_ + + +class FeedForward(nn.Module): + """MLP based model""" + + def __init__(self, size): + super(FeedForward, self).__init__() + self.w1 = nn.Linear(size, size * 2, bias=False) + self.w2 = nn.Linear(size, size * 2, bias=False) + self.out_proj = nn.Linear(size * 2, size, bias=False) + + def forward(self, x): + x = F.silu(self.w1(x)) * self.w2(x) + x = self.out_proj(x) + return x + + +class ToyModel(nn.Module): + def __init__(self, size): + super(ToyModel, self).__init__() + self.ffn = FeedForward(size) + + def forward(self, x): + return self.ffn(x) + + +def _test_lowp_mlp_tensor_parallelism_base( + mesh: DeviceMesh, + config: Union[Float8LinearConfig, MXLinearConfig], + size=32, + compile: bool = False, + allgather_in_lowp: bool = False, +): + device = mesh.device_type + + # TODO(future): remove this once float8 training works with `quantize_` API + convert_model_func = convert_to_float8_training + if isinstance(config, MXLinearConfig): + convert_model_func = quantize_ + + toy_model = ToyModel(size).to(device) + toy_model_fp8 = copy.deepcopy(toy_model) + convert_model_func(toy_model_fp8, config=config) + + tp_model = copy.deepcopy(toy_model) + convert_model_func(tp_model, config=config) + sp_model = copy.deepcopy(toy_model) + convert_model_func(sp_model, config=config) + + # For tensorwise scaling, enable float8 all_gather. + # For rowwise scaling, keep high precision all_gather. Motivation for + # not doing float8 all-gather for rowwise: tensors need to be scaled both ways, + # so for float8 all-gather we'd need to send two float8 copies per tensor, + # which is similar # bytes over the wire than just doing bfloat16 all-gather. + if not allgather_in_lowp: + colwise_parallel_cls = ColwiseParallel + rowwise_parallel_cls = RowwiseParallel + prepare_input_cls = PrepareModuleInput + else: + colwise_parallel_cls = Float8ColwiseParallel + rowwise_parallel_cls = Float8RowwiseParallel + prepare_input_cls = PrepareFloat8ModuleInput + + # vanilla TP + tp_model = parallelize_module( + tp_model, + mesh, + { + "ffn.w1": colwise_parallel_cls(), + "ffn.w2": colwise_parallel_cls(), + "ffn.out_proj": rowwise_parallel_cls(), + }, + ) + + # "sequence parallel" mlp computation + sp_model = parallelize_module( + sp_model, + mesh, + { + "ffn": prepare_input_cls( + input_layouts=Shard(1), desired_input_layouts=Replicate() + ), + "ffn.w1": colwise_parallel_cls(), + "ffn.w2": colwise_parallel_cls(), + "ffn.out_proj": rowwise_parallel_cls( + output_layouts=Shard(1), use_local_output=False + ), + }, + ) + + # prepare_input_cls with specific submodule fqn + sp_model2 = copy.deepcopy(toy_model) + convert_model_func(sp_model2, config=config) + + if not allgather_in_lowp: + prepare_input = prepare_input_cls( + input_layouts=Shard(1), + desired_input_layouts=Replicate(), + ) + else: + prepare_input = prepare_input_cls( + input_layouts=Shard(1), + desired_input_layouts=Replicate(), + fwd_config_submodule_fqn="w2", + ) + + sp_model2 = parallelize_module( + sp_model2, + mesh, + { + "ffn": prepare_input, + "ffn.w1": colwise_parallel_cls(), + "ffn.w2": colwise_parallel_cls(), + "ffn.out_proj": rowwise_parallel_cls( + output_layouts=Shard(1), use_local_output=False + ), + }, + ) + + if compile: + tp_model = torch.compile(tp_model) + sp_model = torch.compile(sp_model) + sp_model2 = torch.compile(sp_model2) + + x_fp32 = torch.rand(2, size * 2, size, device=device, requires_grad=False) + go_fp32 = torch.rand(2, size * 2, size, device=device, requires_grad=False) + x_fp32_tp_input = x_fp32.clone() + go_fp32_tp = go_fp32.clone() + x_fp32_sp_input = distribute_tensor(x_fp32.clone(), mesh, [Shard(0)]) + go_fp32_sp = distribute_tensor(go_fp32.clone(), mesh, [Shard(0)]) + + tp_out = tp_model(x_fp32_tp_input) + tp_out.backward(go_fp32_tp) + sp_out = sp_model(x_fp32_sp_input) + sp_out.backward(go_fp32_sp) + global_out = toy_model_fp8(x_fp32) + global_out.backward(go_fp32) + torch.testing.assert_close(tp_out, global_out) + torch.testing.assert_close(sp_out.full_tensor(), global_out) + torch.testing.assert_close(tp_model.ffn.w1.weight.grad, sp_model.ffn.w1.weight.grad) + torch.testing.assert_close( + tp_model.ffn.out_proj.weight.grad, sp_model.ffn.out_proj.weight.grad + ) + + sp_out2 = sp_model2(x_fp32_sp_input) + sp_out2.backward(go_fp32_sp) + torch.testing.assert_close(sp_out2.full_tensor(), global_out) + torch.testing.assert_close( + tp_model.ffn.w1.weight.grad, sp_model2.ffn.w1.weight.grad + ) + torch.testing.assert_close( + tp_model.ffn.out_proj.weight.grad, sp_model2.ffn.out_proj.weight.grad + ) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/fsdp2_utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/fsdp2_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9eef29604077922a19da57100dab5046f8e7975b --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/fsdp2_utils.py @@ -0,0 +1,101 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +from typing import List + +import torch +import torch.distributed as dist +import torch.nn as nn + +from torchao.float8.config import ( + Float8LinearConfig, + ScalingType, +) +from torchao.float8.fsdp_utils import precompute_float8_dynamic_scale_for_fsdp + + +def check_parity_no_mp( + test_cls, + ref_model: nn.Module, + ref_optim: torch.optim.Optimizer, + fsdp_model: nn.Module, + fsdp_optim: torch.optim.Optimizer, + local_inp: torch.Tensor, + config: Float8LinearConfig, + precompute: bool = False, + compile_transformer_block: bool = False, +): + # check that requires_grad matches ref module + for ref_param, fsdp_param in zip(ref_model.parameters(), fsdp_model.parameters()): + test_cls.assertEqual( + ref_param.requires_grad, + fsdp_param.requires_grad, + msg=f"ref_param.requires_grad: {ref_param.requires_grad}, fsdp_param.requires_grad: {fsdp_param.requires_grad}", + ) + + # TODO(before land): reorder args and make config not optional + for iter_idx in range(10): + losses: List[torch.Tensor] = [] + for model, optim in ((ref_model, ref_optim), (fsdp_model, fsdp_optim)): + optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) + losses.append(model(local_inp).sum()) + losses[-1].backward() + if model is ref_model: + for param in model.parameters(): + if param.requires_grad: + dist.all_reduce(param.grad) + param.grad.div_(dist.get_world_size()) + + optim.step() + if ( + model is fsdp_model + and precompute + and config.cast_config_weight.scaling_type is ScalingType.DYNAMIC + ): + precompute_float8_dynamic_scale_for_fsdp(model) + + test_cls.assertEqual( + losses[0], + losses[1], + msg=f"iter: {iter_idx}, loss-ref: {losses[0]}, loss-fp8: {losses[1]}", + ) + + +def check_parity_bf16_mp( + test_cls, + ref_model: nn.Module, + ref_model_bf16: nn.Module, + ref_optim: torch.optim.Optimizer, + fsdp_model: nn.Module, + fsdp_optim: torch.optim.Optimizer, + local_inp: torch.Tensor, +): + for iter_idx in range(10): + losses: List[torch.Tensor] = [] + for model, optim in ( + (ref_model_bf16, ref_optim), + (fsdp_model, fsdp_optim), + ): + optim.zero_grad(set_to_none=(iter_idx % 2 == 0)) + losses.append(model(local_inp).sum()) + losses[-1].backward() + if model is ref_model_bf16: + for param_bf16, param_fp32 in zip( + ref_model_bf16.parameters(), ref_model.parameters() + ): + dist.all_reduce(param_bf16.grad) + param_bf16.grad.div_(dist.get_world_size()) + param_fp32.grad = param_bf16.grad.float() + param_bf16.grad = None + optim.step() + for param_fp32, param_bf16 in zip( + ref_model.parameters(), ref_model_bf16.parameters() + ): + param_bf16.detach().copy_(param_fp32) + test_cls.assertEqual( + losses[0], + losses[1], + msg=f"iter: {iter_idx}, loss-ref: {losses[0]}, loss-fp8: {losses[1]}", + ) diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/roofline_utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/roofline_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..286803dbf25d1cf19894b38812100bfe12a1d18a --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/roofline_utils.py @@ -0,0 +1,342 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. + +from typing import List, Optional, Union + +import sympy +import torch + +BYTES_PER_EL_FLOAT8 = 1 +BYTES_PER_EL_BF16 = 2 + +gpu_name_to_specs = { + "NVIDIA H100": { + # https://www.nvidia.com/en-us/data-center/h100/, divide by 2 because no sparsity + "bf16_peak_tops": 989e12, + "fp8_peak_tops": 1979e12, + # 2.4 TB per second, custom to Meta's H100 variant + "peak_mem_bw_bytes_sec": 2.4e12, + # based on experimental observation with sample large inputs + "pct_achievable_gemm_tops": 0.78, + # based on previous experience looking at pointwise triton kernels with large inputs, + # which would hit about 2.2k GBPS on Meta's H100 variant + "pct_achievable_mem_bw": 0.92, + }, + "NVIDIA B200": { + # https://resources.nvidia.com/en-us-blackwell-architecture, page 19, + # divide by 2 because no sparsity + "bf16_peak_tops": 2.25e15, + "fp8_peak_tops": 4.5e15, + "fp4_peak_tops": 9.0e15, + # https://resources.nvidia.com/en-us-blackwell-architecture, page 20 + # 8.0 TB per second + "peak_mem_bw_bytes_sec": 8.0e12, + # for now, copy over from H100 + # TODO(future): measure once we have the hardware + "pct_achievable_gemm_tops": 0.78, + # for now, copy over from H100 + # TODO(future): measure once we have the hardware + "pct_achievable_mem_bw": 0.92, + }, + "AMD Instinct MI300X": { + # https://www.amd.com/content/dam/amd/en/documents/instinct-tech-docs/data-sheets/amd-instinct-mi300x-data-sheet.pdf, page 1, + "bf16_peak_tops": 1307e12, + "fp8_peak_tops": 2614e12, + # 5.3 TB per second + "peak_mem_bw_bytes_sec": 5.3e12, + # for now, copy over from H100 + # TODO(future): run measurement on hardware + "pct_achievable_gemm_tops": 0.78, + # for now, copy over from H100 + # TODO(future): run measurement on hardware + "pct_achievable_mem_bw": 0.92, + }, + "NVIDIA GeForce RTX 5090": { + # https://images.nvidia.com/aem-dam/Solutions/geforce/blackwell/nvidia-rtx-blackwell-gpu-architecture.pdf + "bf16_peak_tops": 209.5e12, + "fp8_peak_tops": 419e12, + "fp4_peak_tops": 1676e12, + "peak_mem_bw_bytes_sec": 1.792e15, + }, + # TODO(future): more GPU names +} + + +def get_specs(): + gpu_name = torch.cuda.get_device_name(0) + return gpu_name_to_specs[gpu_name] + + +# Source: run a triton kernel with a single element read/write on an H100 and +# measure GPU time from the trace +# TODO(future): audit this across different hardware and triton/non-triton +KERNEL_LAUNCH_OVERHEAD_SEC = 0.002 * 0.001 + + +def get_tensor_memory_traffic_ovhd_s( + specs, + dim0, + dim1, + tensor_role: str, + float8_recipe_name: Optional[str], + mx_recipe_name: Optional[str], + fuse_with_prev=False, +) -> List[Union[sympy.Symbol, float]]: + """ + Calculates the roofline estimate of casting one of the gemm inputs + (input, weight or grad_output) to float8 in fwd+bwd. + + Inputs: dim0 and dim1 (shape), tensor_role (input|weight|grad_output), recipe names + Outputs: list of read/write traffic overhead in seconds, one for each kernel + """ + # assumes input bf16, output f8 + numel = dim0 * dim1 + + res_bytes = None + if float8_recipe_name == "tensorwise": + if tensor_role == "weight": + # x_bf16 = ... + # kernel 1: x_bf16 -> max_abs_stage_1 -> tmp + # kernel 2 (mem traffic not modeled): tmp -> max_abs_stage_2 -> max_abs + # kernel 3 (fwd): x_bf16, max_abs -> to_float8 -> x_fp8_dim0 + # kernel 4 (bwd): x_bf16, max_abs -> to_float8 -> x_fp8_dim1 + if fuse_with_prev: + kernel_1_rw = 0 + else: + # kernel 1: read numel, write 0 (assume size(tmp) ~ 0) + kernel_1_rw = BYTES_PER_EL_BF16 * numel + # kernel 3: read in bf16, write twice in float8 (row-major and col-major) + kernel_3_rw = BYTES_PER_EL_BF16 * numel + BYTES_PER_EL_FLOAT8 * numel + kernel_4_rw = kernel_3_rw + res_bytes = [kernel_1_rw, 0, kernel_3_rw, kernel_4_rw] + else: + # x_bf16 = ... + # kernel 1: x_bf16 -> max_abs_stage_1 -> tmp + # kernel 2 (mem traffic not modeled): tmp -> max_abs_stage_2 -> max_abs + # kernel 3: x_bf16, max_abs -> to_float8 -> x_fp8_dim0, x_fp8_dim1 + if fuse_with_prev: + kernel_1_rw = 0 + else: + # kernel 1: read numel, write 0 (assume size(tmp) ~ 0) + kernel_1_rw = BYTES_PER_EL_BF16 * numel + # kernel 3: read in bf16, write twice in float8 (row-major and col-major) + kernel_3_rw = BYTES_PER_EL_BF16 * numel + 2 * BYTES_PER_EL_FLOAT8 * numel + res_bytes = [kernel_1_rw, 0, kernel_3_rw] + + elif float8_recipe_name == "rowwise": + if tensor_role == "weight": + # x_bf16 = ... + # kernel 1 (fwd): x_bf16_dim0 -> x_float8_dim0 + # kernel 2 (bwd): x_bf16_dim0 -> x_bf16_dim1 + # kernel 3 (bwd): x_bf16_dim1 -> x_float8_dim1 + # assume that we can't fuse 2 and 3 because that would require loading + # the entire tensor to shared memory + if fuse_with_prev: + # assume we can fuse one of the reads with previous op + kernel_1_rw = 0 + BYTES_PER_EL_FLOAT8 * numel + else: + kernel_1_rw = BYTES_PER_EL_BF16 * numel + BYTES_PER_EL_FLOAT8 * numel + kernel_2_rw = BYTES_PER_EL_BF16 * numel * 2 + kernel_3_rw = BYTES_PER_EL_BF16 * numel + BYTES_PER_EL_FLOAT8 * numel + res_bytes = [kernel_1_rw, kernel_2_rw, kernel_3_rw] + else: + # x_bf16 = ... + # kernel 1: x_bf16_dim0 -> x_float8_dim0, x_bf16_dim1 + # kernel 2: x_bf16_dim1 -> x_float8_dim1 + # assume that we can't fuse 1 and 2 because that would require loading + # the entire tensor to shared memory + if fuse_with_prev: + # assume we can fuse one of the reads with previous op + kernel_1_rw = ( + 0 + BYTES_PER_EL_FLOAT8 * numel + BYTES_PER_EL_BF16 * numel + ) + else: + kernel_1_rw = ( + BYTES_PER_EL_BF16 * numel + + BYTES_PER_EL_FLOAT8 * numel + + BYTES_PER_EL_BF16 * numel + ) + kernel_2_rw = BYTES_PER_EL_BF16 * numel + BYTES_PER_EL_FLOAT8 * numel + res_bytes = [kernel_1_rw, kernel_2_rw] + + elif float8_recipe_name == "rowwise_with_gw_hp": + if tensor_role in ("input", "grad_output"): + # x_bf16 = ... + # kernel 1 (fwd): x_bf16_dim0 -> x_float8_dim0 + # bwd: no-op + if fuse_with_prev: + kernel_1_rw = 0 + BYTES_PER_EL_FLOAT8 * numel + else: + kernel_1_rw = BYTES_PER_EL_BF16 * numel + BYTES_PER_EL_FLOAT8 * numel + res_bytes = [kernel_1_rw] + elif tensor_role == "weight": + # x_bf16 = ... + # kernel 1 (fwd): w_bf16 -> w_float8_dim0, w_scale_dim0 + # kernel 2 (bwd): w_scale_dim0 -> w_scale_tensorwise + # kernel 3 (bwd): w_bf16, w_scale_tensorwise -> w_float8_dim1 + kernel_1_rw = BYTES_PER_EL_BF16 * numel + BYTES_PER_EL_FLOAT8 * numel + kernel_2_rw = 0 + kernel_3_rw = BYTES_PER_EL_BF16 * numel + BYTES_PER_EL_FLOAT8 * numel + res_bytes = [kernel_1_rw, kernel_2_rw, kernel_3_rw] + else: + assert False, "unsupported" + + else: + assert mx_recipe_name in ( + "mxfp8_emulated", + "mxfp8_cublas", + ), "unsupported" + # For now, assume that we can't profitably fuse kernel 1 and kernel 2 + # x_bf16 = ... + # kernel 1: x_bf16 -> x_mxfp8_dim0 + # kernel 2: x_bf16 -> x_mxfp8_dim1 + if fuse_with_prev: + kernel_1_rw = 0 + BYTES_PER_EL_FLOAT8 * numel + else: + kernel_1_rw = BYTES_PER_EL_BF16 * numel + BYTES_PER_EL_FLOAT8 * numel + kernel_2_rw = BYTES_PER_EL_BF16 * numel + BYTES_PER_EL_FLOAT8 * numel + res_bytes = [kernel_1_rw, kernel_2_rw] + + # convert from bytes to seconds + res_s = [ + x / specs["peak_mem_bw_bytes_sec"] / specs["pct_achievable_mem_bw"] + for x in res_bytes + ] + + # take max of kernel_overhead, r/w time + res_s = [sympy.Max(x, KERNEL_LAUNCH_OVERHEAD_SEC) for x in res_s] + + return res_s + + +def get_individual_gemm_time_sympy( + M: sympy.Symbol, K: sympy.Symbol, N: sympy.Symbol, dtype, mx_recipe_name +) -> sympy.Symbol: + # compute bound + specs = get_specs() + gemm_ops = 2 * M * K * N + if dtype is torch.bfloat16: + peak_tops = specs["bf16_peak_tops"] + elif dtype in (torch.float8_e4m3fn, torch.float8_e5m2): + peak_tops = specs["fp8_peak_tops"] + else: + assert False, "unsupported" + compute_gemm_time_s = gemm_ops / peak_tops / specs["pct_achievable_gemm_tops"] + + # memory bound + num_reads = M * K + K * N + num_writes = M * N + + if mx_recipe_name is not None: + assert mx_recipe_name in ( + "mxfp8_emulated", + "mxfp8_cublas", + ), "unsupported" + assert dtype in (torch.float8_e4m3fn, torch.float8_e5m2), "unsupported" + # adjust reads for MX scaling + block_size = 32 + num_scale_reads = num_reads // block_size + # note: e8m0 bytes per element is the same as for e4m3|e5m2 + num_reads = num_reads + num_scale_reads + + if dtype is torch.bfloat16: + bytes_rw = num_reads * BYTES_PER_EL_BF16 + num_writes * BYTES_PER_EL_BF16 + elif dtype in (torch.float8_e4m3fn, torch.float8_e5m2): + # read in float8, output in bfloat16 + bytes_rw = num_reads * BYTES_PER_EL_FLOAT8 + num_writes * BYTES_PER_EL_BF16 + else: + assert False, "unsupported" + mem_gemm_time_s = ( + bytes_rw / specs["peak_mem_bw_bytes_sec"] / specs["pct_achievable_mem_bw"] + ) + + return sympy.Max(compute_gemm_time_s, mem_gemm_time_s, KERNEL_LAUNCH_OVERHEAD_SEC) + + +def get_gemm_time_sympy( + M: sympy.Symbol, + K: sympy.Symbol, + N: sympy.Symbol, + dtype, + float8_recipe_name: Optional[str], + mx_recipe_name: Optional[str], +): + # next: add rowwise_with_gw_hp here + # note: this function is currently not super accurate for small shapes: + # when M,K,N <= 1k,1k,1k it undercounts by around 2x + + gemm_dtype_input, gemm_dtype_grad_input, gemm_dtype_grad_weight = ( + dtype, + dtype, + dtype, + ) + if float8_recipe_name == "rowwise_with_gw_hp": + gemm_dtype_grad_weight = torch.bfloat16 + + gemm_output_time_s = get_individual_gemm_time_sympy( + M, K, N, gemm_dtype_input, mx_recipe_name + ) + gemm_grad_input_time_s = get_individual_gemm_time_sympy( + M, N, K, gemm_dtype_grad_input, mx_recipe_name + ) + gemm_grad_weight_time_s = get_individual_gemm_time_sympy( + K, M, N, gemm_dtype_grad_weight, mx_recipe_name + ) + total = gemm_output_time_s + gemm_grad_input_time_s + gemm_grad_weight_time_s + return total + + +def get_float8_mem_sympy( + M, + K, + N, + float8_recipe_name: Optional[str], + mx_recipe_name: Optional[str], + enable_fusion_modeling: bool, +): + specs = get_specs() + + # there are three gemms in the fwd/bwd of a linear: + # + # input @ weight_t = output + # MxK @ KxN => MxN + # + # grad_output @ weight = grad_input + # MxN @ NxK => MxK + # + # input_t @ grad_output = grad_weight + # KxM @ MxN => KxN + + fwd_fp8_input_mem = get_tensor_memory_traffic_ovhd_s( + specs, + M, + K, + tensor_role="input", + float8_recipe_name=float8_recipe_name, + mx_recipe_name=mx_recipe_name, + fuse_with_prev=enable_fusion_modeling, + ) + fwd_fp8_weight_mem = get_tensor_memory_traffic_ovhd_s( + specs, + K, + N, + tensor_role="weight", + float8_recipe_name=float8_recipe_name, + mx_recipe_name=mx_recipe_name, + fuse_with_prev=False, + ) + gi_fp8_grad_output_mem = get_tensor_memory_traffic_ovhd_s( + specs, + M, + N, + tensor_role="grad_output", + float8_recipe_name=float8_recipe_name, + mx_recipe_name=mx_recipe_name, + fuse_with_prev=enable_fusion_modeling, + ) + + res = sum([*fwd_fp8_input_mem, *fwd_fp8_weight_mem, *gi_fp8_grad_output_mem]) + return res diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/test_utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4a30931c9e08165cfc1af0e2641c2d170d20f874 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/training/test_utils.py @@ -0,0 +1,34 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +from torchao.float8.config import ( + CastConfig, + Float8LinearConfig, +) + + +def get_test_float8_linear_config( + scaling_type_input, + scaling_type_weight, + scaling_type_grad_output, + emulate: bool, +): + cast_config_input = CastConfig( + scaling_type=scaling_type_input, + ) + cast_config_weight = CastConfig( + scaling_type=scaling_type_weight, + ) + cast_config_grad_output = CastConfig( + scaling_type=scaling_type_grad_output, + ) + + config = Float8LinearConfig( + cast_config_input=cast_config_input, + cast_config_weight=cast_config_weight, + cast_config_grad_output=cast_config_grad_output, + emulate=emulate, + ) + return config diff --git a/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/utils.py b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..26a738c53bdc5c8a621013d0e57d9641c40a8559 --- /dev/null +++ b/tasks/kfc/wro-torchao-int8-rowwise-quant-loop16/task/environment/repo/torchao/testing/utils.py @@ -0,0 +1,430 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# All rights reserved. +# +# This source code is licensed under the BSD 3-Clause license found in the +# LICENSE file in the root directory of this source tree. +import copy +import functools +import unittest + +import torch +from torch.distributed._tensor import DeviceMesh, DTensor, Replicate, Shard +from torch.testing._internal import common_utils +from torch.testing._internal.distributed._tensor.common_dtensor import ( + DTensorTestBase, + with_comms, +) + +import torchao +from torchao.dtypes import AffineQuantizedTensor, to_affine_quantized_intx +from torchao.quantization import int8_weight_only, quantize_ +from torchao.quantization.quant_primitives import MappingType +from torchao.utils import TORCH_VERSION_AT_LEAST_2_6, get_compute_capability + +""" +How to use: + +import unittest +from torchao.testing.utils import TorchAOBasicTestCase, copy_tests +from torch.testing._internal import common_utils + +# TODO: currently there is no way to set COMMON_DEVICES/COMMON_DTYPES +# we can figure out this a bit later + +# change arguments +class MyTestCase(TorchAOBasicTestCase): + TENSOR_SUBCLASS = MyDTypeTensor + FACTOR_FN = to_my_dtype + kwargs = {"target_dtype": torch.uint8} + LINEAR_MIN_SQNR = 30 + +# copy the instantiated tests +copy_tests(TorchAOBasicTestCase, MyTestCase, "my_test_case") + +if __name__ == "__main__": + unittest.main() +""" + + +def skip_if_compute_capability_less_than(min_capability): + import unittest + + def decorator(test_func): + def wrapper(*args, **kwargs): + if get_compute_capability() < min_capability: + raise unittest.SkipTest( + f"Compute capability is less than {min_capability}" + ) + return test_func(*args, **kwargs) + + return wrapper + + return decorator + + +def skip_if_rocm(message=None): + """Decorator to skip tests on ROCm platform with custom message. + + Args: + message (str, optional): Additional information about why the test is skipped. + """ + import pytest + + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + if torch.version.hip is not None: + skip_message = "Skipping the test in ROCm" + if message: + skip_message += f": {message}" + pytest.skip(skip_message) + return func(*args, **kwargs) + + return wrapper + + # Handle both @skip_if_rocm and @skip_if_rocm() syntax + if callable(message): + func = message + message = None + return decorator(func) + return decorator + + +def skip_if_no_cuda(): + import unittest + + def decorator(test_func): + @functools.wraps(test_func) + def wrapper(*args, **kwargs): + if not torch.cuda.is_available(): + raise unittest.SkipTest("No cuda available") + return test_func(*args, **kwargs) + + return wrapper + + return decorator + + +def skip_if_no_gemlite(): + import unittest + + def decorator(test_func): + @functools.wraps(test_func) + def wrapper(*args, **kwargs): + try: + import gemlite # noqa: F401 + except: + raise unittest.SkipTest("No gemlite available") + return test_func(*args, **kwargs) + + return wrapper + + return decorator + + +# copied from https://github.com/pytorch/pytorch/blob/941d094dd1b507dacf06ddc6ed3485a9537e09b7/test/inductor/test_torchinductor.py#L11389 +def copy_tests(my_cls, other_cls, suffix, test_failures=None, xfail_prop=None): # noqa: B902 + for name, value in my_cls.__dict__.items(): + if name.startswith("test_"): + # You cannot copy functions in Python, so we use closures here to + # create objects with different ids. Otherwise, unittest.skip + # would modify all methods sharing the same object id. Also, by + # using a default argument, we create a copy instead of a + # reference. Otherwise, we would lose access to the value. + + @functools.wraps(value) + def new_test(self, value=value): + return value(self) + + # Copy __dict__ which may contain test metadata + new_test.__dict__ = copy.deepcopy(value.__dict__) + + if xfail_prop is not None and hasattr(value, xfail_prop): + new_test = unittest.expectedFailure(new_test) + + tf = test_failures and test_failures.get(name) + if tf is not None and suffix in tf.suffixes: + skip_func = ( + unittest.skip("Skipped!") + if tf.is_skip + else unittest.expectedFailure + ) + new_test = skip_func(new_test) + + setattr(other_cls, f"{name}_{suffix}", new_test) + + +class TorchAOBasicTestCase(common_utils.TestCase): + COMMON_DEVICES = ["cpu"] + (["cuda"] if torch.cuda.is_available() else []) + COMMON_DTYPES = [torch.float32, torch.float16, torch.bfloat16] + + TENSOR_SUBCLASS = AffineQuantizedTensor + FACTORY_FN = to_affine_quantized_intx + kwargs = { + "mapping_type": MappingType.ASYMMETRIC, + "block_size": (1, 32), + "target_dtype": torch.uint8, + } + # minimum sqnr for linear operation when the weight is quantized to low precision + # with the above setting + LINEAR_MIN_SQNR = 40 + + def test_flatten_unflatten(self): + hp_tensor = torch.randn(4, 128) + lp_tensor = self.FACTORY_FN(hp_tensor, **self.kwargs) + tensor_data_name_dict, tensor_attributes = lp_tensor.__tensor_flatten__() + tensor_data_dict = { + name: getattr(lp_tensor, name) for name in tensor_data_name_dict + } + outer_size = lp_tensor.size() + outer_stride = lp_tensor.stride() + reconstructed = self.TENSOR_SUBCLASS.__tensor_unflatten__( + tensor_data_dict, tensor_attributes, outer_size, outer_stride + ) + self.assertEqual(lp_tensor.dequantize(), reconstructed.dequantize()) + + @common_utils.parametrize("device", COMMON_DEVICES) + @common_utils.parametrize("dtype", COMMON_DTYPES) + def test_hp_tensor_device_dtype(self, device, dtype): + hp_tensor = torch.randn(4, 128, device=device, dtype=dtype) + self.FACTORY_FN(hp_tensor, **self.kwargs) + + @common_utils.parametrize("device1", COMMON_DEVICES) + @common_utils.parametrize("device2", COMMON_DEVICES) + def test_device1_to_device2(self, device1, device2): + """Note: this should be parametrized with device1 and device2 + e.g. device1 = ["cpu", "cuda"], device2 = ["cpu", "cuda"] + """ + hp_tensor = torch.randn(4, 128, device=device1, dtype=torch.bfloat16) + lp_tensor = self.FACTORY_FN(hp_tensor, **self.kwargs) + lp_tensor.to(device=device2) + + hp_tensor = torch.randn(4, 128, device=device1, dtype=torch.bfloat16) + lp_tensor = self.FACTORY_FN(hp_tensor, **self.kwargs) + lp_tensor.to(device2) + + hp_tensor = torch.randn(4, 128, device=device1, dtype=torch.bfloat16) + lp_tensor = self.FACTORY_FN(hp_tensor, **self.kwargs) + lp_tensor.cuda() + + hp_tensor = torch.randn(4, 128, device=device1, dtype=torch.bfloat16) + lp_tensor = self.FACTORY_FN(hp_tensor, **self.kwargs) + lp_tensor.cpu() + + @common_utils.parametrize("device", COMMON_DEVICES) + @common_utils.parametrize("dtype", COMMON_DTYPES) + def test_transpose(self, device, dtype): + hp_tensor = torch.randn(4, 128, device=device, dtype=dtype) + lp_tensor = self.FACTORY_FN(hp_tensor, **self.kwargs) + lp_tensor = lp_tensor.t() + self.assertEqual(lp_tensor.shape, (128, 4)) + + @common_utils.parametrize("device", COMMON_DEVICES) + @common_utils.parametrize("dtype", COMMON_DTYPES) + def test_linear(self, device, dtype): + hp_tensor = torch.randn(4, 128, device=device, dtype=dtype) + lp_tensor = self.FACTORY_FN(hp_tensor, **self.kwargs) + + hp_act_tensor = torch.randn(32, 128, device=device, dtype=dtype) + hp_res = torch.nn.functional.linear(hp_act_tensor, hp_tensor) + lp_res = torch.nn.functional.linear(hp_act_tensor, lp_tensor) + self.assertGreater( + torchao.quantization.utils.compute_error(hp_res, lp_res), + self.LINEAR_MIN_SQNR, + ) + + +class TorchAOCompileTestCase(common_utils.TestCase): + COMMON_DEVICES = ["cpu"] + (["cuda"] if torch.cuda.is_available() else []) + COMMON_DTYPES = [torch.float32, torch.float16, torch.bfloat16] + + TENSOR_SUBCLASS = AffineQuantizedTensor + FACTORY_FN = to_affine_quantized_intx + kwargs = { + "mapping_type": MappingType.ASYMMETRIC, + "block_size": (1, 32), + "target_dtype": torch.uint8, + } + # minimum sqnr for linear operation when the weight is quantized to low precision + # with the above setting + LINEAR_MIN_SQNR = 40 + COMPILE_MIN_SQNR = 50 + + @common_utils.parametrize("device", COMMON_DEVICES) + @common_utils.parametrize("dtype", COMMON_DTYPES) + def test_input_output_tensor_subclass(self, device, dtype): + hp_tensor = torch.randn(4, 128, device=device, dtype=dtype) + lp_tensor = self.FACTORY_FN(hp_tensor, **self.kwargs) + + def f(tensor): + return tensor + + ref = f(lp_tensor) + f = torch.compile(f) + compiled = f(lp_tensor) + self.assertTrue(isinstance(f(lp_tensor), self.TENSOR_SUBCLASS)) + self.assertEqual(ref.dequantize(), compiled.dequantize()) + + @common_utils.parametrize("device", COMMON_DEVICES) + @common_utils.parametrize("dtype", COMMON_DTYPES) + def test_input_tensor_subclass(self, device, dtype): + hp_tensor = torch.randn(4, 128, device=device, dtype=dtype) + lp_tensor = self.FACTORY_FN(hp_tensor, **self.kwargs) + + def f(tensor): + return tensor.dequantize() + + ref = f(lp_tensor) + f = torch.compile(f) + compiled = f(lp_tensor) + self.assertFalse(isinstance(f(lp_tensor), self.TENSOR_SUBCLASS)) + self.assertEqual(ref, compiled) + + @common_utils.parametrize("device", COMMON_DEVICES) + @common_utils.parametrize("dtype", COMMON_DTYPES) + def test_output_tensor_subclass(self, device, dtype): + hp_tensor = torch.randn(4, 128, device=device, dtype=dtype) + + def f(hp_tensor): + return self.FACTORY_FN(hp_tensor, **self.kwargs) + + ref = f(hp_tensor) + f = torch.compile(f) + compiled = f(hp_tensor) + self.assertTrue(isinstance(f(hp_tensor), self.TENSOR_SUBCLASS)) + # bfloat16 seems to result in much larger numerical differences + if dtype != torch.bfloat16: + self.assertGreater( + torchao.quantization.utils.compute_error( + ref.dequantize(), compiled.dequantize() + ), + self.COMPILE_MIN_SQNR, + ) + + @common_utils.parametrize("device", COMMON_DEVICES) + @common_utils.parametrize("dtype", COMMON_DTYPES) + def test_linear_compile(self, device, dtype): + hp_tensor = torch.randn(4, 128, device=device, dtype=dtype) + lp_tensor = self.FACTORY_FN(hp_tensor, **self.kwargs) + + hp_act_tensor = torch.randn(32, 128, device=device, dtype=dtype) + hp_res = torch.nn.functional.linear(hp_act_tensor, hp_tensor) + linear = torch.nn.Linear(128, 4, bias=False, device=device, dtype=dtype) + linear.weight = torch.nn.Parameter(lp_tensor) + lp_res = torch.compile(linear)(hp_act_tensor) + self.assertGreater( + torchao.quantization.utils.compute_error(hp_res, lp_res), + self.LINEAR_MIN_SQNR, + ) + + +class TorchAOTensorParallelTestCase(DTensorTestBase): + """Basic test case for tensor subclasses""" + + COMMON_DTYPES = [torch.float32, torch.float16, torch.bfloat16] + + TENSOR_SUBCLASS = AffineQuantizedTensor + QUANT_METHOD_FN = staticmethod(int8_weight_only) + QUANT_METHOD_KWARGS = {} + + @staticmethod + def colwise_shard(m: torch.nn.Module, mesh: DeviceMesh) -> torch.nn.Module: + """ + Shard linear layer of the model in column-wise fashion + """ + # Column-wise is wrt to A^T, so for A it is row-wise. + # Number of rows per rank + orig_weight = m.linear.weight + n_local_rows = orig_weight.size(0) // mesh.size() + rank = mesh.get_local_rank() + local_shard = orig_weight[rank * n_local_rows : (rank + 1) * n_local_rows, :] + # Construct DTensor from local shard + dtensor = DTensor.from_local(local_shard, mesh, [Shard(0)]) + # Replace parameter in module + m.linear.weight = torch.nn.Parameter(dtensor, requires_grad=False) + return m + + @staticmethod + def rowwise_shard(m: torch.nn.Module, mesh: DeviceMesh) -> torch.nn.Module: + """ + Shard linear layer of the model in row-wise fashion + """ + # Row-wise is wrt to A^T, so for A it is column-wise. + # Number of rows per rank + orig_weight = m.linear.weight + n_local_cols = orig_weight.size(1) // mesh.size() + rank = mesh.get_local_rank() + local_shard = orig_weight[:, rank * n_local_cols : (rank + 1) * n_local_cols] + # Construct DTensor from local shard + dtensor = DTensor.from_local(local_shard, mesh, [Shard(1)]) + # Replace parameter in module + m.linear.weight = torch.nn.Parameter(dtensor, requires_grad=False) + return m + + def quantize(self, m: torch.nn.Module) -> torch.nn.Module: + """ + Quantize the model + """ + quantize_(m, self.QUANT_METHOD_FN(**self.QUANT_METHOD_KWARGS)) + return m + + @common_utils.parametrize("dtype", COMMON_DTYPES) + @with_comms + @unittest.skipIf(not torch.cuda.is_available(), "Need CUDA available") + def test_tp(self, dtype): + device = "cuda" + # To make sure different ranks create the same module + torch.manual_seed(5) + + class M(torch.nn.Module): + def __init__(self, in_features, out_features, **kwargs) -> None: + super().__init__(**kwargs) + self.linear = torch.nn.Linear( + in_features, out_features, bias=False, device="cuda" + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.linear(x) + + # Get rank and device + device = torch.device(f"cuda:{self.rank % torch.cuda.device_count()}") + + # Original model + proj_up = M(1024, 2048).to(device).to(dtype) + proj_dn = M(2048, 1024).to(device).to(dtype) + example_input = 100 * torch.randn(128, 1024, device=device, dtype=dtype) + proj_dn(proj_up(example_input)) + + # Quantize the model + up_quant = self.quantize(proj_up) + dn_quant = self.quantize(proj_dn) + dn_quant(up_quant(example_input)) + + mesh = self.build_device_mesh() + mesh.device_type = "cuda" + + # Shard the models + up_dist = self.colwise_shard(up_quant, mesh) + dn_dist = self.rowwise_shard(dn_quant, mesh) + + # We need to turn inputs into DTensor form as well -- just a format change + input_dtensor = DTensor.from_local(example_input, mesh, [Replicate()]) + + dn_dist(up_dist(input_dtensor)) + + if not TORCH_VERSION_AT_LEAST_2_6: + # Need torch 2.6 to support compiled tensor parallelism + return + + up_compiled = torch.compile(up_dist) + y_up = up_compiled(input_dtensor) + dn_compiled = torch.compile(dn_dist) + dn_compiled(y_up) + + +common_utils.instantiate_parametrized_tests(TorchAOBasicTestCase) +common_utils.instantiate_parametrized_tests(TorchAOCompileTestCase) +common_utils.instantiate_parametrized_tests(TorchAOTensorParallelTestCase) + +if __name__ == "__main__": + unittest.main()