tico 0.1.0.dev250714__py3-none-any.whl → 0.1.0.dev251102__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. tico/__init__.py +9 -1
  2. tico/config/base.py +1 -1
  3. tico/config/v1.py +5 -0
  4. tico/passes/cast_aten_where_arg_type.py +1 -1
  5. tico/passes/cast_clamp_mixed_type_args.py +169 -0
  6. tico/passes/cast_mixed_type_args.py +4 -2
  7. tico/passes/const_prop_pass.py +1 -1
  8. tico/passes/convert_conv1d_to_conv2d.py +1 -1
  9. tico/passes/convert_expand_to_slice_cat.py +153 -0
  10. tico/passes/convert_matmul_to_linear.py +312 -0
  11. tico/passes/convert_to_relu6.py +1 -1
  12. tico/passes/decompose_addmm.py +0 -3
  13. tico/passes/decompose_batch_norm.py +2 -2
  14. tico/passes/decompose_fake_quantize.py +0 -3
  15. tico/passes/decompose_fake_quantize_tensor_qparams.py +5 -6
  16. tico/passes/decompose_group_norm.py +0 -3
  17. tico/passes/legalize_predefined_layout_operators.py +2 -11
  18. tico/passes/lower_to_resize_nearest_neighbor.py +1 -1
  19. tico/passes/lower_to_slice.py +1 -1
  20. tico/passes/merge_consecutive_cat.py +1 -1
  21. tico/passes/ops.py +1 -1
  22. tico/passes/remove_redundant_assert_nodes.py +3 -1
  23. tico/passes/remove_redundant_expand.py +3 -6
  24. tico/passes/remove_redundant_reshape.py +5 -5
  25. tico/passes/segment_index_select.py +1 -1
  26. tico/quantization/__init__.py +6 -0
  27. tico/{experimental/quantization → quantization}/algorithm/gptq/gptq.py +1 -1
  28. tico/quantization/algorithm/gptq/quantizer.py +292 -0
  29. tico/{experimental/quantization → quantization}/algorithm/gptq/utils.py +1 -1
  30. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/annotator.py +7 -14
  31. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/adaptive_avg_pool2d.py +4 -6
  32. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/add.py +4 -6
  33. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/conv2d.py +4 -6
  34. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/div.py +4 -6
  35. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/linear.py +5 -7
  36. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/mean.py +4 -6
  37. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/mul.py +4 -6
  38. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/relu6.py +4 -6
  39. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/rsqrt.py +4 -6
  40. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/sub.py +4 -6
  41. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/spec.py +1 -3
  42. tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/utils.py +1 -1
  43. tico/{experimental/quantization → quantization}/algorithm/pt2e/quantizer.py +5 -2
  44. tico/{experimental/quantization → quantization}/algorithm/pt2e/utils.py +1 -4
  45. tico/{experimental/quantization → quantization}/algorithm/smoothquant/observer.py +26 -8
  46. tico/{experimental/quantization → quantization}/algorithm/smoothquant/quantizer.py +28 -9
  47. tico/quantization/algorithm/smoothquant/smooth_quant.py +327 -0
  48. tico/quantization/config/base.py +26 -0
  49. tico/quantization/config/gptq.py +29 -0
  50. tico/quantization/config/pt2e.py +25 -0
  51. tico/quantization/config/ptq.py +119 -0
  52. tico/{experimental/quantization/config.py → quantization/config/smoothquant.py} +9 -36
  53. tico/{experimental/quantization → quantization}/evaluation/evaluate.py +8 -17
  54. tico/{experimental/quantization → quantization}/evaluation/executor/circle_executor.py +3 -4
  55. tico/{experimental/quantization → quantization}/evaluation/executor/triv24_executor.py +2 -4
  56. tico/quantization/evaluation/metric.py +146 -0
  57. tico/{experimental/quantization → quantization}/evaluation/utils.py +1 -1
  58. tico/quantization/passes/__init__.py +1 -0
  59. tico/{experimental/quantization → quantization}/passes/fold_quant_ops.py +0 -1
  60. tico/quantization/passes/insert_quantize_on_dtype_mismatch.py +459 -0
  61. tico/{experimental/quantization → quantization}/passes/quantize_bias.py +0 -1
  62. tico/{experimental/quantization → quantization}/passes/remove_weight_dequant_op.py +1 -1
  63. tico/{experimental/quantization → quantization}/public_interface.py +19 -18
  64. tico/{experimental/quantization → quantization}/quantizer.py +1 -1
  65. tico/quantization/quantizer_registry.py +73 -0
  66. tico/quantization/wrapq/__init__.py +1 -0
  67. tico/quantization/wrapq/dtypes.py +70 -0
  68. tico/quantization/wrapq/examples/__init__.py +1 -0
  69. tico/quantization/wrapq/examples/compare_ppl.py +230 -0
  70. tico/quantization/wrapq/examples/debug_quant_outputs.py +224 -0
  71. tico/quantization/wrapq/examples/quantize_linear.py +107 -0
  72. tico/quantization/wrapq/examples/quantize_llama_attn.py +101 -0
  73. tico/quantization/wrapq/examples/quantize_llama_decoder_layer.py +125 -0
  74. tico/quantization/wrapq/examples/quantize_llama_mlp.py +95 -0
  75. tico/quantization/wrapq/examples/quantize_with_gptq.py +265 -0
  76. tico/quantization/wrapq/mode.py +32 -0
  77. tico/quantization/wrapq/observers/__init__.py +1 -0
  78. tico/quantization/wrapq/observers/affine_base.py +128 -0
  79. tico/quantization/wrapq/observers/base.py +98 -0
  80. tico/quantization/wrapq/observers/ema.py +62 -0
  81. tico/quantization/wrapq/observers/identity.py +74 -0
  82. tico/quantization/wrapq/observers/minmax.py +39 -0
  83. tico/quantization/wrapq/observers/mx.py +60 -0
  84. tico/quantization/wrapq/qscheme.py +40 -0
  85. tico/quantization/wrapq/quantizer.py +179 -0
  86. tico/quantization/wrapq/utils/__init__.py +1 -0
  87. tico/quantization/wrapq/utils/introspection.py +167 -0
  88. tico/quantization/wrapq/utils/metrics.py +124 -0
  89. tico/quantization/wrapq/utils/reduce_utils.py +25 -0
  90. tico/quantization/wrapq/wrappers/__init__.py +1 -0
  91. tico/quantization/wrapq/wrappers/fairseq/__init__.py +5 -0
  92. tico/quantization/wrapq/wrappers/fairseq/decoder_export_single_step.py +234 -0
  93. tico/quantization/wrapq/wrappers/fairseq/quant_decoder.py +429 -0
  94. tico/quantization/wrapq/wrappers/fairseq/quant_decoder_layer.py +492 -0
  95. tico/quantization/wrapq/wrappers/fairseq/quant_encoder.py +331 -0
  96. tico/quantization/wrapq/wrappers/fairseq/quant_encoder_layer.py +163 -0
  97. tico/quantization/wrapq/wrappers/fairseq/quant_mha.py +381 -0
  98. tico/quantization/wrapq/wrappers/llama/__init__.py +1 -0
  99. tico/quantization/wrapq/wrappers/llama/quant_attn.py +276 -0
  100. tico/quantization/wrapq/wrappers/llama/quant_decoder_layer.py +176 -0
  101. tico/quantization/wrapq/wrappers/llama/quant_mlp.py +96 -0
  102. tico/quantization/wrapq/wrappers/nn/__init__.py +1 -0
  103. tico/quantization/wrapq/wrappers/nn/quant_layernorm.py +183 -0
  104. tico/quantization/wrapq/wrappers/nn/quant_linear.py +65 -0
  105. tico/quantization/wrapq/wrappers/nn/quant_silu.py +59 -0
  106. tico/quantization/wrapq/wrappers/ptq_wrapper.py +69 -0
  107. tico/quantization/wrapq/wrappers/quant_elementwise.py +111 -0
  108. tico/quantization/wrapq/wrappers/quant_module_base.py +168 -0
  109. tico/quantization/wrapq/wrappers/registry.py +125 -0
  110. tico/serialize/circle_graph.py +12 -4
  111. tico/serialize/circle_mapping.py +76 -2
  112. tico/serialize/circle_serializer.py +253 -148
  113. tico/serialize/operators/adapters/__init__.py +1 -0
  114. tico/serialize/operators/adapters/llama_rmsnorm.py +35 -0
  115. tico/serialize/operators/op_any.py +7 -14
  116. tico/serialize/operators/op_avg_pool2d.py +11 -4
  117. tico/serialize/operators/op_clamp.py +5 -7
  118. tico/serialize/operators/op_constant_pad_nd.py +41 -11
  119. tico/serialize/operators/op_conv2d.py +14 -6
  120. tico/serialize/operators/op_copy.py +26 -3
  121. tico/serialize/operators/op_cumsum.py +3 -1
  122. tico/serialize/operators/op_depthwise_conv2d.py +17 -7
  123. tico/serialize/operators/op_full_like.py +0 -2
  124. tico/serialize/operators/op_index_select.py +8 -1
  125. tico/serialize/operators/op_instance_norm.py +0 -6
  126. tico/serialize/operators/op_le.py +54 -0
  127. tico/serialize/operators/op_log1p.py +3 -2
  128. tico/serialize/operators/op_max_pool2d_with_indices.py +17 -7
  129. tico/serialize/operators/op_mm.py +15 -131
  130. tico/serialize/operators/op_mul.py +2 -8
  131. tico/serialize/operators/op_pow.py +3 -1
  132. tico/serialize/operators/op_repeat.py +12 -3
  133. tico/serialize/operators/op_reshape.py +1 -1
  134. tico/serialize/operators/op_rmsnorm.py +65 -0
  135. tico/serialize/operators/op_softmax.py +7 -14
  136. tico/serialize/operators/op_split_with_sizes.py +16 -8
  137. tico/serialize/operators/op_transpose_conv.py +11 -8
  138. tico/serialize/operators/op_view.py +2 -1
  139. tico/serialize/quant_param.py +5 -5
  140. tico/utils/convert.py +30 -17
  141. tico/utils/dtype.py +42 -0
  142. tico/utils/graph.py +1 -1
  143. tico/utils/model.py +2 -1
  144. tico/utils/padding.py +2 -2
  145. tico/utils/pytree_utils.py +134 -0
  146. tico/utils/record_input.py +102 -0
  147. tico/utils/register_custom_op.py +29 -4
  148. tico/utils/serialize.py +16 -3
  149. tico/utils/signature.py +247 -0
  150. tico/utils/torch_compat.py +52 -0
  151. tico/utils/utils.py +50 -58
  152. tico/utils/validate_args_kwargs.py +38 -3
  153. {tico-0.1.0.dev250714.dist-info → tico-0.1.0.dev251102.dist-info}/METADATA +49 -2
  154. tico-0.1.0.dev251102.dist-info/RECORD +271 -0
  155. tico/experimental/quantization/__init__.py +0 -1
  156. tico/experimental/quantization/algorithm/gptq/quantizer.py +0 -225
  157. tico/experimental/quantization/algorithm/smoothquant/smooth_quant.py +0 -164
  158. tico/experimental/quantization/evaluation/metric.py +0 -109
  159. tico/experimental/quantization/passes/insert_quantize_on_dtype_mismatch.py +0 -437
  160. tico-0.1.0.dev250714.dist-info/RECORD +0 -209
  161. /tico/{experimental/quantization → quantization}/algorithm/__init__.py +0 -0
  162. /tico/{experimental/quantization → quantization}/algorithm/gptq/__init__.py +0 -0
  163. /tico/{experimental/quantization → quantization}/algorithm/gptq/quant.py +0 -0
  164. /tico/{experimental/quantization → quantization}/algorithm/pt2e/__init__.py +0 -0
  165. /tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/__init__.py +0 -0
  166. /tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/config.py +0 -0
  167. /tico/{experimental/quantization → quantization}/algorithm/pt2e/annotation/op/__init__.py +0 -0
  168. /tico/{experimental/quantization → quantization}/algorithm/pt2e/transformation/__init__.py +0 -0
  169. /tico/{experimental/quantization → quantization}/algorithm/pt2e/transformation/convert_scalars_to_attrs.py +0 -0
  170. /tico/{experimental/quantization → quantization}/algorithm/smoothquant/__init__.py +0 -0
  171. /tico/{experimental/quantization/evaluation → quantization/config}/__init__.py +0 -0
  172. /tico/{experimental/quantization/evaluation/executor → quantization/evaluation}/__init__.py +0 -0
  173. /tico/{experimental/quantization → quantization}/evaluation/backend.py +0 -0
  174. /tico/{experimental/quantization/passes → quantization/evaluation/executor}/__init__.py +0 -0
  175. /tico/{experimental/quantization → quantization}/evaluation/executor/backend_executor.py +0 -0
  176. /tico/{experimental/quantization → quantization}/passes/propagate_qparam_backward.py +0 -0
  177. /tico/{experimental/quantization → quantization}/passes/propagate_qparam_forward.py +0 -0
  178. {tico-0.1.0.dev250714.dist-info → tico-0.1.0.dev251102.dist-info}/LICENSE +0 -0
  179. {tico-0.1.0.dev250714.dist-info → tico-0.1.0.dev251102.dist-info}/WHEEL +0 -0
  180. {tico-0.1.0.dev250714.dist-info → tico-0.1.0.dev251102.dist-info}/entry_points.txt +0 -0
  181. {tico-0.1.0.dev250714.dist-info → tico-0.1.0.dev251102.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,101 @@
1
+ # Copyright (c) 2025 Samsung Electronics Co., Ltd. All Rights Reserved
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import pathlib
16
+
17
+ import torch
18
+ from transformers import AutoModelForCausalLM, AutoTokenizer
19
+
20
+ from tico.quantization import convert, prepare
21
+ from tico.quantization.config.ptq import PTQConfig
22
+ from tico.quantization.evaluation.metric import compute_peir
23
+ from tico.quantization.evaluation.utils import plot_two_outputs
24
+ from tico.quantization.wrapq.mode import Mode
25
+ from tico.quantization.wrapq.wrappers.llama.quant_attn import QuantLlamaAttention
26
+ from tico.utils.utils import SuppressWarning
27
+
28
+ name = "Maykeye/TinyLLama-v0"
29
+ model = AutoModelForCausalLM.from_pretrained(name)
30
+ tokenizer = AutoTokenizer.from_pretrained(name)
31
+
32
+ # -------------------------------------------------------------------------
33
+ # 1. Replace layer-0’s MLP with QuantLlamaMLP
34
+ # -------------------------------------------------------------------------
35
+ orig_attn = model.model.layers[0].self_attn
36
+ model.model.layers[0].self_attn = prepare(orig_attn, PTQConfig())
37
+ model.eval()
38
+
39
+ attn_q = model.model.layers[0].self_attn # quant wrapper
40
+ assert isinstance(attn_q.wrapped, QuantLlamaAttention)
41
+ rotary = model.model.rotary_emb
42
+
43
+ # -------------------------------------------------------------------------
44
+ # 2. Single-pass calibration
45
+ # -------------------------------------------------------------------------
46
+ PROMPTS = [
47
+ "The quick brown fox jumps over the lazy dog.",
48
+ "In 2025, AI systems accelerated hardware-software co-design at scale.",
49
+ "양자화는 왜 어려울까? 분포, 길이, 마스크가 관건이다.",
50
+ "今日はいい天気ですね。ところでRoPE角度は長さに依存します。",
51
+ "def quicksort(arr):\n if len(arr) <= 1: return arr\n ...",
52
+ "Prices rose 3.14% — see Figure 2; emails: foo@bar.com!",
53
+ ]
54
+
55
+ with torch.no_grad():
56
+ for prompt in PROMPTS:
57
+ ids = tokenizer(prompt, return_tensors="pt")
58
+ embeds = model.model.embed_tokens(ids["input_ids"])
59
+ cos_sin = rotary(embeds, ids["input_ids"])
60
+ S = cos_sin[0].shape[1]
61
+ float_mask = torch.zeros(1, 1, S, S)
62
+ _ = attn_q(embeds, cos_sin) # observers collect
63
+
64
+ convert(attn_q)
65
+
66
+ assert attn_q._mode is Mode.QUANT, "Quantization mode should be active now."
67
+
68
+ # -------------------------------------------------------------------------
69
+ # 3. Quick diff check (INT-sim vs FP32)
70
+ # -------------------------------------------------------------------------
71
+ ids = tokenizer("check", return_tensors="pt")
72
+ emb = model.model.embed_tokens(ids["input_ids"])
73
+ pos = rotary(emb, ids["input_ids"])
74
+ S = pos[0].shape[1]
75
+ float_mask = torch.zeros(1, 1, S, S)
76
+ with torch.no_grad():
77
+ int8 = attn_q(emb, pos)[0]
78
+ fp32 = orig_attn(emb, position_embeddings=pos, attention_mask=None)[0]
79
+
80
+ print("┌───────────── Quantization Error Summary ─────────────")
81
+ print(f"│ Mean |diff|: {(int8 - fp32).abs().mean().item():.6f}")
82
+ print(f"│ PEIR : {compute_peir(fp32, int8) * 100:.6f} %")
83
+ print("└──────────────────────────────────────────────────────")
84
+ print(plot_two_outputs(fp32, int8))
85
+
86
+ # -------------------------------------------------------------------------
87
+ # 4. Export the quantized block
88
+ # -------------------------------------------------------------------------
89
+ import tico
90
+
91
+ save_path = pathlib.Path("attn.q.circle")
92
+ B, S, D = 1, 4, model.config.hidden_size
93
+ example = torch.randn(B, S, D)
94
+ example_pos = rotary(example, torch.arange(S)[None, :])
95
+ float_mask = torch.zeros(1, 1, S, S)
96
+
97
+ with SuppressWarning(UserWarning, ".*"):
98
+ cm = tico.convert(attn_q, (example, example_pos))
99
+ cm.save(save_path)
100
+
101
+ print(f"Quantized Circle model saved to {save_path.resolve()}")
@@ -0,0 +1,125 @@
1
+ # Copyright (c) 2025 Samsung Electronics Co., Ltd. All Rights Reserved
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # =============================================================================
16
+ # POST-TRAINING QUANTIZATION EXAMPLE — Llama Decoder Layer (Self-Attn + MLP)
17
+ # -----------------------------------------------------------------------------
18
+ # This demo shows how to:
19
+ # 1. Replace a single FP32 `LlamaDecoderLayer` with `QuantLlamaDecoderLayer`.
20
+ # 2. Collect activation statistics in one calibration sweep.
21
+ # 3. Freeze scales / zero-points and switch to INT-simulation mode.
22
+ # 4. Compare INT-8 vs FP32 outputs with a quick mean-absolute-diff check.
23
+ # 5. Export the calibrated, quantized block to a Circle model.
24
+ # -----------------------------------------------------------------------------
25
+ # Style / layout is kept identical to the `quantize_llama_attn.py` and
26
+ # `quantize_llama_mlp.py` examples for easy side-by-side reading.
27
+ # =============================================================================
28
+
29
+ import pathlib
30
+
31
+ import torch
32
+ from transformers import AutoModelForCausalLM, AutoTokenizer
33
+
34
+ from tico.quantization import convert, prepare
35
+ from tico.quantization.config.ptq import PTQConfig
36
+ from tico.quantization.evaluation.metric import compute_peir
37
+ from tico.quantization.evaluation.utils import plot_two_outputs
38
+ from tico.quantization.wrapq.mode import Mode
39
+ from tico.quantization.wrapq.wrappers.llama.quant_decoder_layer import (
40
+ QuantLlamaDecoderLayer,
41
+ )
42
+ from tico.utils.utils import SuppressWarning
43
+
44
+ MODEL_NAME = "Maykeye/TinyLLama-v0"
45
+ model = AutoModelForCausalLM.from_pretrained(MODEL_NAME)
46
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
47
+
48
+ model.eval() # disable dropout, etc.
49
+ rotary = model.model.rotary_emb # RoPE helper
50
+
51
+ # -------------------------------------------------------------------------
52
+ # 1. Swap in the quant wrapper
53
+ # -------------------------------------------------------------------------
54
+ fp32_layer = model.model.layers[0] # keep a reference for diff check
55
+ model.model.layers[0] = prepare(fp32_layer, PTQConfig())
56
+ model.eval()
57
+
58
+ qlayer = model.model.layers[0] # alias for brevity
59
+ assert isinstance(qlayer.wrapped, QuantLlamaDecoderLayer)
60
+
61
+ # -------------------------------------------------------------------------
62
+ # 2. Single-pass calibration (gather activation ranges)
63
+ # -------------------------------------------------------------------------
64
+ PROMPTS = [
65
+ "The quick brown fox jumps over the lazy dog.",
66
+ "In 2025, AI systems accelerated hardware-software co-design at scale.",
67
+ "양자화는 왜 어려울까? 분포, 길이, 마스크가 관건이다.",
68
+ "今日はいい天気ですね。ところでRoPE角度は長さに依存します。",
69
+ "def quicksort(arr):\n if len(arr) <= 1: return arr\n ...",
70
+ "Prices rose 3.14% — see Figure 2; emails: foo@bar.com!",
71
+ ]
72
+
73
+ with torch.no_grad():
74
+ for prompt in PROMPTS:
75
+ ids = tokenizer(prompt, return_tensors="pt")
76
+ hidden = model.model.embed_tokens(ids["input_ids"])
77
+ pos = rotary(hidden, ids["input_ids"]) # (cos, sin) tuple
78
+ S = pos[0].shape[1]
79
+ attn_mask = torch.zeros(1, 1, S, S) # causal-mask placeholder
80
+ _ = qlayer(hidden, attention_mask=attn_mask, position_embeddings=pos)
81
+
82
+ convert(qlayer)
83
+
84
+ assert qlayer._mode is Mode.QUANT, "Quantization mode should be active now."
85
+
86
+ # -------------------------------------------------------------------------
87
+ # 3. Quick INT-sim vs FP32 sanity check
88
+ # -------------------------------------------------------------------------
89
+ ids = tokenizer("check", return_tensors="pt")
90
+ hidden = model.model.embed_tokens(ids["input_ids"])
91
+ pos = rotary(hidden, ids["input_ids"])
92
+ S = pos[0].shape[1]
93
+ attn_mask = torch.zeros(1, 1, S, S)
94
+
95
+ with torch.no_grad():
96
+ int8_out = qlayer(hidden, attention_mask=attn_mask, position_embeddings=pos)
97
+ int8 = int8_out[0] if isinstance(int8_out, tuple) else int8_out
98
+ fp32_out = fp32_layer(hidden, attention_mask=attn_mask, position_embeddings=pos)
99
+ fp32 = fp32_out[0] if isinstance(fp32_out, tuple) else fp32_out
100
+
101
+ print("┌───────────── Quantization Error Summary ─────────────")
102
+ print(f"│ Mean |diff|: {(int8 - fp32).abs().mean().item():.6f}")
103
+ print(f"│ PEIR : {compute_peir(fp32, int8) * 100:.6f} %")
104
+ print("└──────────────────────────────────────────────────────")
105
+ print(plot_two_outputs(fp32, int8))
106
+
107
+ # -------------------------------------------------------------------------
108
+ # 4. Export the calibrated layer to Circle
109
+ # -------------------------------------------------------------------------
110
+ import tico
111
+
112
+ save_path = pathlib.Path("decoder_layer.q.circle")
113
+ B, S, D = 1, 4, model.config.hidden_size
114
+ example_hidden = torch.randn(B, S, D)
115
+ example_pos = rotary(example_hidden, torch.arange(S)[None, :])
116
+ attn_mask = torch.zeros(1, 1, S, S)
117
+
118
+ with SuppressWarning(UserWarning, ".*"):
119
+ cm = tico.convert(
120
+ qlayer, (example_hidden, attn_mask), {"position_embeddings": example_pos}
121
+ )
122
+ # Note that the model is not fully quantized.
123
+ cm.save(save_path)
124
+
125
+ print(f"Quantized Circle model saved to {save_path.resolve()}")
@@ -0,0 +1,95 @@
1
+ # Copyright (c) 2025 Samsung Electronics Co., Ltd. All Rights Reserved
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import pathlib
16
+
17
+ import torch
18
+ from transformers import AutoModelForCausalLM, AutoTokenizer
19
+
20
+ import tico
21
+ from tico.quantization import convert, prepare
22
+ from tico.quantization.config.ptq import PTQConfig
23
+ from tico.quantization.evaluation.metric import compute_peir
24
+ from tico.quantization.evaluation.utils import plot_two_outputs
25
+ from tico.quantization.wrapq.dtypes import INT16
26
+ from tico.quantization.wrapq.mode import Mode
27
+ from tico.quantization.wrapq.qscheme import QScheme
28
+ from tico.quantization.wrapq.wrappers.llama.quant_mlp import QuantLlamaMLP
29
+ from tico.utils.utils import SuppressWarning
30
+
31
+ name = "Maykeye/TinyLLama-v0"
32
+ model = AutoModelForCausalLM.from_pretrained(name)
33
+ tokenizer = AutoTokenizer.from_pretrained(name)
34
+ model.eval()
35
+
36
+ # -------------------------------------------------------------------------
37
+ # 1. Replace layer-0’s MLP with QuantLlamaMLP
38
+ # -------------------------------------------------------------------------
39
+ fp32_mlp = model.model.layers[0].mlp
40
+ model.model.layers[0].mlp = prepare(
41
+ fp32_mlp, PTQConfig(default_dtype=INT16, default_qscheme=QScheme.PER_TENSOR_SYMM)
42
+ )
43
+ model.eval()
44
+
45
+ mlp_q = model.model.layers[0].mlp
46
+ assert isinstance(mlp_q.wrapped, QuantLlamaMLP)
47
+
48
+ # -------------------------------------------------------------------------
49
+ # 2. Single-pass calibration
50
+ # -------------------------------------------------------------------------
51
+ PROMPTS = [
52
+ "The quick brown fox jumps over the lazy dog.",
53
+ "In 2025, AI systems accelerated hardware-software co-design at scale.",
54
+ "양자화는 왜 어려울까? 분포, 길이, 마스크가 관건이다.",
55
+ "今日はいい天気ですね。ところでRoPE角度は長さに依存します。",
56
+ "def quicksort(arr):\n if len(arr) <= 1: return arr\n ...",
57
+ "Prices rose 3.14% — see Figure 2; emails: foo@bar.com!",
58
+ ]
59
+
60
+ with torch.no_grad():
61
+ for prompt in PROMPTS:
62
+ enc = tokenizer(prompt, return_tensors="pt")
63
+ emb = model.model.embed_tokens(enc["input_ids"])
64
+ _ = mlp_q(emb)
65
+
66
+ convert(mlp_q)
67
+
68
+ assert mlp_q._mode is Mode.QUANT, "Quantization mode should be active now."
69
+
70
+ # -------------------------------------------------------------------------
71
+ # 3. Quick diff check (INT-sim vs FP32)
72
+ # -------------------------------------------------------------------------
73
+ with torch.no_grad():
74
+ ids = tokenizer("quant all tensors!", return_tensors="pt")
75
+ emb = model.model.embed_tokens(ids["input_ids"])
76
+ int16 = mlp_q(emb) # INT-sim
77
+ fp32 = fp32_mlp(emb) # baseline reference
78
+
79
+ print("┌───────────── Quantization Error Summary ─────────────")
80
+ print(f"│ Mean |diff|: {(int16 - fp32).abs().mean().item():.6f}")
81
+ print(f"│ PEIR : {compute_peir(fp32, int16) * 100:.6f} %")
82
+ print("└──────────────────────────────────────────────────────")
83
+ print(plot_two_outputs(fp32, int16))
84
+
85
+ # -------------------------------------------------------------------------
86
+ # 4. Export the quantized block
87
+ # -------------------------------------------------------------------------
88
+ save_path = pathlib.Path("mlp.q.circle")
89
+ example_in = (torch.randn(1, 1, model.config.hidden_size),)
90
+
91
+ with SuppressWarning(UserWarning, ".*"):
92
+ cm = tico.convert(mlp_q, example_in)
93
+ cm.save(save_path)
94
+
95
+ print(f"Quantized Circle model saved to {save_path.resolve()}")
@@ -0,0 +1,265 @@
1
+ # Copyright (c) 2025 Samsung Electronics Co., Ltd. All Rights Reserved
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # =============================================================================
16
+ # PTQ + GPTQ HYBRID QUANTIZATION PIPELINE
17
+ # -----------------------------------------------------------------------------
18
+ # This script shows how to:
19
+ # 1. Load a pretrained FP Llama-3 model.
20
+ # 2. Run GPTQ to quantize weights only.
21
+ # 3. Wrap every Transformer layer with a PTQWrapper to quantize activations.
22
+ # 4. Calibrate UINT-8 observers in a single pass over a text corpus.
23
+ # 5. Inject GPTQ’s per-tensor weight scales / zero-points into the PTQ graph.
24
+ # 6. Freeze all Q-params and compute Wikitext-2 perplexity.
25
+ # =============================================================================
26
+
27
+ import argparse
28
+ import sys
29
+ from typing import Any
30
+
31
+ import torch
32
+ import tqdm
33
+ from datasets import load_dataset
34
+ from transformers import AutoModelForCausalLM, AutoTokenizer
35
+
36
+ from tico.quantization import convert, prepare
37
+ from tico.quantization.config.gptq import GPTQConfig
38
+ from tico.quantization.config.ptq import PTQConfig
39
+ from tico.quantization.wrapq.observers.affine_base import AffineObserverBase
40
+ from tico.quantization.wrapq.utils.introspection import build_fqn_map
41
+ from tico.quantization.wrapq.utils.metrics import perplexity
42
+ from tico.quantization.wrapq.wrappers.ptq_wrapper import PTQWrapper
43
+ from tico.quantization.wrapq.wrappers.quant_module_base import QuantModuleBase
44
+
45
+
46
+ # Token-budget presets for activation calibration
47
+ TOKENS: dict[str, int] = {
48
+ # Smoke test (<1 min turnaround on CPU/GPU)
49
+ "debug": 2_000, # ≈16 × 128-seq batches
50
+ # Good default for 1-7B models (≲3 % ppl delta)
51
+ "baseline": 50_000,
52
+ # Production / 4-bit observer smoothing
53
+ "production": 200_000,
54
+ }
55
+
56
+ DTYPE_MAP = {
57
+ "float32": torch.float32,
58
+ "bfloat16": torch.bfloat16,
59
+ "float16": torch.float16,
60
+ }
61
+
62
+ # Hardcoded dataset settings
63
+ DATASET_NAME = "wikitext"
64
+ DATASET_CONFIG = "wikitext-2-raw-v1"
65
+ TRAIN_SPLIT = "train"
66
+ TEST_SPLIT = "test"
67
+
68
+ # -------------------------------------------------------------------------
69
+ # 1. Helper — copy GPTQ (scale, zp) into PTQ observers
70
+ # -------------------------------------------------------------------------
71
+ def inject_gptq_qparams(
72
+ root: torch.nn.Module,
73
+ gptq_quantizers: dict[str, Any], # {fp_name: quantizer}
74
+ weight_obs_name: str = "weight",
75
+ ):
76
+ """
77
+ For every `QuantModuleBase` whose `fp_name` matches a GPTQ key,
78
+ locate the observer called `weight_obs_name` and overwrite its
79
+ (scale, zero-point), then lock them against further updates.
80
+ """
81
+ for m in root.modules():
82
+ if not isinstance(m, QuantModuleBase):
83
+ continue
84
+ if m.fp_name is None:
85
+ continue
86
+ quantizer = gptq_quantizers.get(m.fp_name)
87
+ if quantizer is None:
88
+ continue
89
+ obs = m.get_observer(weight_obs_name)
90
+ if obs is None:
91
+ continue
92
+ assert isinstance(obs, AffineObserverBase)
93
+ # GPTQ quantizer attributes
94
+ obs.load_qparams(quantizer.scale, quantizer.zero, lock=True)
95
+
96
+
97
+ def main():
98
+ parser = argparse.ArgumentParser(
99
+ description="GPTQ+PTQ pipeline (weight-only + activation UINT8)"
100
+ )
101
+ parser.add_argument(
102
+ "--model", type=str, required=True, help="HF repo name or local path."
103
+ )
104
+ parser.add_argument(
105
+ "--device",
106
+ type=str,
107
+ default="cuda" if torch.cuda.is_available() else "cpu",
108
+ help="Device to run on (cuda|cpu|mps).",
109
+ )
110
+ parser.add_argument(
111
+ "--dtype",
112
+ choices=list(DTYPE_MAP.keys()),
113
+ default="float32",
114
+ help="Model dtype for load.",
115
+ )
116
+ parser.add_argument(
117
+ "--stride",
118
+ type=int,
119
+ default=512,
120
+ help="Sliding-window stride used for calibration and eval.",
121
+ )
122
+ parser.add_argument(
123
+ "--calib-preset",
124
+ choices=list(TOKENS.keys()),
125
+ default="debug",
126
+ help="Activation calibration token budget preset.",
127
+ )
128
+ parser.add_argument("--seed", type=int, default=42, help="Random seed.")
129
+ parser.add_argument(
130
+ "--trust-remote-code",
131
+ action="store_true",
132
+ help="Enable only if you trust the model repo code.",
133
+ )
134
+ parser.add_argument(
135
+ "--hf-token",
136
+ type=str,
137
+ default=None,
138
+ help="Optional HF token for gated/private repos.",
139
+ )
140
+ parser.add_argument(
141
+ "--use-cache",
142
+ dest="use_cache",
143
+ action="store_true",
144
+ default=False,
145
+ help="Use model KV cache if enabled (off by default).",
146
+ )
147
+ parser.add_argument(
148
+ "--no-tqdm", action="store_true", help="Disable tqdm progress bars."
149
+ )
150
+
151
+ args = parser.parse_args()
152
+
153
+ # Basic setup
154
+ torch.manual_seed(args.seed)
155
+ device = torch.device(args.device)
156
+ dtype = DTYPE_MAP[args.dtype]
157
+
158
+ print("=== Config ===")
159
+ print(f"Model : {args.model}")
160
+ print(f"Device : {device.type}")
161
+ print(f"DType : {args.dtype}")
162
+ print(f"Stride : {args.stride}")
163
+ print(
164
+ f"Calib preset : {args.calib_preset} ({TOKENS[args.calib_preset]:,} tokens)"
165
+ )
166
+ print(f"Use HF cache? : {args.use_cache}")
167
+ print()
168
+
169
+ # -------------------------------------------------------------------------
170
+ # 2. Load the FP backbone and tokenizer
171
+ # -------------------------------------------------------------------------
172
+ print("Loading FP model …")
173
+ tokenizer = AutoTokenizer.from_pretrained(
174
+ args.model,
175
+ trust_remote_code=args.trust_remote_code,
176
+ token=args.hf_token,
177
+ )
178
+ model = (
179
+ AutoModelForCausalLM.from_pretrained(
180
+ args.model,
181
+ torch_dtype=dtype,
182
+ trust_remote_code=args.trust_remote_code,
183
+ token=args.hf_token,
184
+ )
185
+ .to(device)
186
+ .eval()
187
+ )
188
+
189
+ model.config.use_cache = args.use_cache
190
+
191
+ # Build module -> FQN map BEFORE wrapping
192
+ m_to_fqn = build_fqn_map(model)
193
+
194
+ # -------------------------------------------------------------------------
195
+ # 3. Run GPTQ (weight-only) pass
196
+ # -------------------------------------------------------------------------
197
+ print("Applying GPTQ …")
198
+ dataset_test = load_dataset(DATASET_NAME, DATASET_CONFIG, split=TEST_SPLIT)
199
+ q_m = prepare(model, GPTQConfig(), inplace=True)
200
+
201
+ it = (
202
+ dataset_test
203
+ if args.no_tqdm
204
+ else tqdm.tqdm(dataset_test, desc="GPTQ calibration")
205
+ )
206
+ for d in it:
207
+ ids = tokenizer(d["text"], return_tensors="pt").input_ids.to(device)
208
+ q_m(ids) # observers gather weight stats
209
+
210
+ q_m = convert(q_m, inplace=True) # materialize INT-weight tensors
211
+
212
+ # -------------------------------------------------------------------------
213
+ # 4. Wrap every layer with PTQWrapper (activation UINT-8)
214
+ # -------------------------------------------------------------------------
215
+ print("Wrapping layers with PTQWrapper …")
216
+ qcfg = PTQConfig() # default: per-tensor UINT8
217
+ prepare(q_m, qcfg)
218
+
219
+ # -------------------------------------------------------------------------
220
+ # 5. Single-pass activation calibration
221
+ # -------------------------------------------------------------------------
222
+ print("Calibrating UINT-8 observers …")
223
+ CALIB_TOKENS = TOKENS[args.calib_preset]
224
+ print(f"Calibrating with {CALIB_TOKENS:,} tokens.\n")
225
+ dataset_train = load_dataset(DATASET_NAME, DATASET_CONFIG, split=TRAIN_SPLIT)
226
+ calib_txt = " ".join(dataset_train["text"])[:CALIB_TOKENS]
227
+ train_ids = tokenizer(calib_txt, return_tensors="pt").input_ids.to(device)
228
+
229
+ # Overwrite weight observers with GPTQ statistics
230
+ if hasattr(q_m, "quantizers") and isinstance(q_m.quantizers, dict):
231
+ inject_gptq_qparams(q_m, q_m.quantizers)
232
+ else:
233
+ print(
234
+ "[Warn] q_m.quantizers not found or not a dict; skipping GPTQ qparam injection."
235
+ )
236
+
237
+ # Forward passes to collect activation ranges
238
+ iterator = range(0, train_ids.size(1) - 1, args.stride)
239
+ if not args.no_tqdm:
240
+ iterator = tqdm.tqdm(iterator, desc="Act-calibration")
241
+ with torch.no_grad():
242
+ for i in iterator:
243
+ q_m(train_ids[:, i : i + args.stride])
244
+
245
+ # Freeze all Q-params (scale, zero-point)
246
+ convert(q_m)
247
+
248
+ # -------------------------------------------------------------------------
249
+ # 6. Evaluate perplexity on Wikitext-2
250
+ # -------------------------------------------------------------------------
251
+ print("\nCalculating perplexities …")
252
+ enc = tokenizer("\n\n".join(dataset_test["text"]), return_tensors="pt")
253
+ ppl_uint8 = perplexity(q_m, enc, device, stride=args.stride)
254
+
255
+ print("\n┌── Wikitext-2 test perplexity ─────────────")
256
+ print(f"│ UINT-8 : {ppl_uint8:8.2f}")
257
+ print("└───────────────────────────────────────────")
258
+
259
+
260
+ if __name__ == "__main__":
261
+ try:
262
+ main()
263
+ except Exception as e:
264
+ print(f"\n[Error] {e}", file=sys.stderr)
265
+ sys.exit(1)
@@ -0,0 +1,32 @@
1
+ # Copyright (c) 2025 Samsung Electronics Co., Ltd. All Rights Reserved
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from enum import auto, Enum
16
+
17
+
18
+ class Mode(Enum):
19
+ """
20
+ Mode — global FSM for PTQWrapper & Handlers.
21
+
22
+ • NO_QUANT : pure pass-through (no stats, no fake-quant)
23
+ • CALIB : collect observer statistics only
24
+ • QUANT : use cached (scale, zero-point) → fake-quant enabled
25
+ """
26
+
27
+ NO_QUANT = auto()
28
+ CALIB = auto()
29
+ QUANT = auto()
30
+
31
+ def __str__(self) -> str:
32
+ return self.name.lower()
@@ -0,0 +1 @@
1
+ # DO NOT REMOVE THIS FILE