Skip to content

Commit 4d4ffb9

Browse files
committed
Apply black
1 parent d9abf9d commit 4d4ffb9

32 files changed

Lines changed: 372 additions & 385 deletions

onecomp/analyzer/quantization_error.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -107,15 +107,21 @@ def _plot_layer_type(ax, layer_type, label_points, colors):
107107
cy = min(y, ylim * 0.92)
108108
text = f"{k} ({x:.1f}, {y:.2f})"
109109
ax.annotate(
110-
text, (cx, cy),
111-
fontsize=6, color=color, fontstyle="italic",
110+
text,
111+
(cx, cy),
112+
fontsize=6,
113+
color=color,
114+
fontstyle="italic",
112115
bbox=dict(boxstyle="round,pad=0.2", fc="white", ec=color, alpha=0.8),
113116
)
114117
else:
115118
ax.annotate(
116-
str(k), (x, y),
117-
textcoords="offset points", xytext=(5, 3),
118-
fontsize=7, color=color,
119+
str(k),
120+
(x, y),
121+
textcoords="offset points",
122+
xytext=(5, 3),
123+
fontsize=7,
124+
color=color,
119125
)
120126

121127
ax.set_xlim(0, xlim)

onecomp/lpcd/_gradient_solver.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
Copyright 2025-2026 Fujitsu Ltd.
33
44
"""
5+
56
from abc import ABC, abstractmethod
67

78
import torch
@@ -19,7 +20,7 @@ class PenaltyFn(ABC):
1920
@abstractmethod
2021
def __call__(self, module_q: LpcdMetric, module_f: LpcdMetric) -> torch.Tensor:
2122
pass
22-
23+
2324

2425
def gradient_solver(
2526
lpcd_config: LPCDConfig,
@@ -35,19 +36,21 @@ def gradient_solver(
3536
device = lpcd_config.device
3637
batch_size = 16
3738

38-
assert lpcd_config.gd_batch_size % batch_size == 0, \
39-
f"gd_batch_size should be divisible by batch_size, " + \
40-
f"but got {lpcd_config.gd_batch_size} and {batch_size}"
41-
42-
assert target_modules[0].weight.data.dtype in [torch.float32, torch.bfloat16], \
43-
"The model must be loaded in float32 or bfloat16 " + \
44-
"for gradient-based LPCD refinement due to numerical stability."
45-
39+
assert lpcd_config.gd_batch_size % batch_size == 0, (
40+
f"gd_batch_size should be divisible by batch_size, "
41+
+ f"but got {lpcd_config.gd_batch_size} and {batch_size}"
42+
)
43+
44+
assert target_modules[0].weight.data.dtype in [torch.float32, torch.bfloat16], (
45+
"The model must be loaded in float32 or bfloat16 "
46+
+ "for gradient-based LPCD refinement due to numerical stability."
47+
)
48+
4649
# backup and configure grad state
4750
grad_state_q = [p.requires_grad for p in metric_q.parameters()]
4851
grad_state_f = [p.requires_grad for p in metric_f.parameters()]
4952

50-
# set target modules as trainablethe
53+
# set target modules as trainablethe
5154
metric_q.requires_grad_(False)
5255
metric_f.requires_grad_(False)
5356
for module in target_modules:
@@ -60,13 +63,11 @@ def gradient_solver(
6063

6164
optimizer = optim.Adam(metric_q.parameters(), lr=lpcd_config.gd_base_lr)
6265
scheduler = get_cosine_schedule_with_warmup(
63-
optimizer,
64-
num_warmup_steps=int(total_iters * 0.1),
65-
num_training_steps=total_iters
66+
optimizer, num_warmup_steps=int(total_iters * 0.1), num_training_steps=total_iters
6667
)
6768

6869
# Perform gradient descent to relax the weights
69-
for epoch in range(1, lpcd_config.gd_steps+1):
70+
for epoch in range(1, lpcd_config.gd_steps + 1):
7071

7172
chunked_inps = zip(
7273
inps_q.split(batch_size),
@@ -75,7 +76,7 @@ def gradient_solver(
7576

7677
# TODO: shuffle the inputs for better convergence
7778
for iter, (inp_q, inp_f) in enumerate(chunked_inps):
78-
79+
7980
with torch.no_grad():
8081
out_f = metric_f(inp_f.to(device), **kwargs)
8182

@@ -95,4 +96,4 @@ def gradient_solver(
9596
for p, requires_grad in zip(metric_q.parameters(), grad_state_q):
9697
p.requires_grad_(requires_grad)
9798
for p, requires_grad in zip(metric_f.parameters(), grad_state_f):
98-
p.requires_grad_(requires_grad)
99+
p.requires_grad_(requires_grad)

onecomp/lpcd/_lpcd_config.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,4 +54,3 @@ class LPCDConfig:
5454
gd_batch_size: int = 16
5555
gd_base_lr: float = 1e-4
5656
device: str = "cuda:0"
57-

onecomp/lpcd/_lpcd_runner.py

Lines changed: 16 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def run_quantize_with_lpcd(
4545
lpcd_config: LPCDConfig,
4646
calibration_config: CalibrationConfig,
4747
):
48-
""" Run quantization with LPCD.
48+
"""Run quantization with LPCD.
4949
5050
Args:
5151
model_config (ModelConfig): Model configuration
@@ -55,8 +55,9 @@ def run_quantize_with_lpcd(
5555
calibration_config (CalibrationConfig): Calibration configuration
5656
"""
5757

58-
assert not (qep_config is not None and qep_config.general), \
59-
"qep_config.general must be False when qep is enabled."
58+
assert not (
59+
qep_config is not None and qep_config.general
60+
), "qep_config.general must be False when qep is enabled."
6061

6162
# TODO: Parameterize when necessary
6263
batch_size = 16
@@ -69,7 +70,7 @@ def run_quantize_with_lpcd(
6970

7071
model_inputs = prepare_calibration_dataset(
7172
tokenizer=tokenizer,
72-
device=torch.device('cpu'),
73+
device=torch.device("cpu"),
7374
calibration_config=calibration_config,
7475
model=model,
7576
logger=logger,
@@ -99,7 +100,7 @@ def run_quantize_with_lpcd(
99100
block_f = copy.deepcopy(block_q)
100101

101102
groups_q = make_grouped_module(block_q, inps_q, kwargs, device)
102-
103+
103104
# Build name→module map for block_f, then align groups_f to
104105
# groups_q by module name. Using make_grouped_module on
105106
# block_f independently can produce a different group ordering
@@ -112,12 +113,17 @@ def run_quantize_with_lpcd(
112113
name: mod for name, mod in block_q.named_modules() if isinstance(mod, nn.Linear)
113114
}
114115
groups_f = [
115-
[name_to_module_f[next(n for n, m2 in name_to_module_q.items() if m2 is m)] for m in gq]
116+
[
117+
name_to_module_f[next(n for n, m2 in name_to_module_q.items() if m2 is m)]
118+
for m in gq
119+
]
116120
for gq in groups_q
117121
]
118122

119123
lpcd_metrics = make_lpcd_metrics(lpcd_config, block_q, block_f)
120-
lpcd_modules_q = [module for metric, _ in lpcd_metrics.metrics for _, module in metric.named_targets()]
124+
lpcd_modules_q = [
125+
module for metric, _ in lpcd_metrics.metrics for _, module in metric.named_targets()
126+
]
121127

122128
# 3. For each group of layers, perform the following sequentially
123129
for group_q, group_f in zip(groups_q, groups_f):
@@ -149,13 +155,10 @@ def run_quantize_with_lpcd(
149155
# Skip layers not registered for quantization
150156
if module not in quantizer.module_to_name:
151157
skipped_name = module_q_to_name.get(module, "<unknown>")
152-
logger.info(
153-
"Skipping layer (not in quantization targets): %s", skipped_name
154-
)
158+
logger.info("Skipping layer (not in quantization targets): %s", skipped_name)
155159
continue
156160
name = quantizer.module_to_name[module]
157161

158-
159162
# Fall back to standard quantization if the module is not LPCD targets
160163
if not module in lpcd_modules_q:
161164

@@ -190,10 +193,7 @@ def run_quantize_with_lpcd(
190193
# Update the weights of the target layer
191194
dtype = module.weight.data.dtype
192195
module.weight.data = (
193-
quantizer.results[name]
194-
.compute_dequantized_weight()
195-
.to(device)
196-
.to(dtype)
196+
quantizer.results[name].compute_dequantized_weight().to(device).to(dtype)
197197
)
198198

199199
lpcd_metrics.mark_as_ready(module)
@@ -218,20 +218,11 @@ def run_quantize_with_lpcd(
218218
inps_f = forward_input(inps_f, block_f, kwargs, batch_size, device)
219219

220220
# DEBUG:Compute MSE between quantized and full-precision outputs
221-
mse = compute_mse(
222-
block_q,
223-
block_f,
224-
inps_q,
225-
inps_f,
226-
batch_size,
227-
device,
228-
kwargs
229-
)
221+
mse = compute_mse(block_q, block_f, inps_q, inps_f, batch_size, device, kwargs)
230222
logger.info(f"[INFO] Layer {block_idx + 1} MSE: {mse:.6e}")
231223

232224
# free memory
233225
block_q.cpu()
234226
torch.cuda.empty_cache()
235227

236228
quantizer.execute_post_processing()
237-

onecomp/lpcd/_metric.py

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
Copyright 2025-2026 Fujitsu Ltd.
33
44
"""
5+
56
import torch
67
from torch import nn
78
from transformers.models.llama.modeling_llama import LlamaDecoderLayer
@@ -11,6 +12,8 @@
1112
from typing import Callable
1213

1314
from ._lpcd_config import LPCDConfig
15+
16+
1417
@dataclass
1518
class ClosedFormSolverArgument:
1619
lpcd_config: LPCDConfig
@@ -36,12 +39,12 @@ def __init__(self, block: nn.Module):
3639

3740
def is_refineable(self) -> bool:
3841
return all(self.is_ready.values()) and not self.is_refined
39-
42+
4043
# Implement named targets of the metric
4144
@abstractmethod
4245
def named_targets(self) -> list[tuple[str, nn.Module]]:
4346
pass
44-
47+
4548
# Implement metric computation here
4649
@abstractmethod
4750
def forward(self, block_inps: torch.Tensor, kwargs: dict) -> torch.Tensor:
@@ -50,11 +53,10 @@ def forward(self, block_inps: torch.Tensor, kwargs: dict) -> torch.Tensor:
5053
# (optional) Implement closed-form solvers for specific cases (e.g., llama-out, etc.)
5154
def closed_form_solvers(self) -> list[Callable[[ClosedFormSolverArgument], None] | None]:
5255
return [None] * len(self.named_targets())
53-
56+
5457

5558
class LpcdMetricGroup:
56-
"""LpcdMetricGroup organizes LpcdMetrics for a block
57-
"""
59+
"""LpcdMetricGroup organizes LpcdMetrics for a block"""
5860

5961
def __init__(self, metrics: list[tuple[LpcdMetric, LpcdMetric]]):
6062
self.metrics = metrics
@@ -68,31 +70,32 @@ def mark_as_ready(self, module: nn.Module):
6870
self.module_to_metric[module].is_ready[module] = True
6971

7072
def get_refineable_metrics(self) -> list[LpcdMetric]:
71-
return [(metric_q, metric_f) for metric_q, metric_f in self.metrics if metric_q.is_refineable()]
72-
73+
return [
74+
(metric_q, metric_f) for metric_q, metric_f in self.metrics if metric_q.is_refineable()
75+
]
7376

7477

7578
from transformers.models.llama.modeling_llama import LlamaDecoderLayer
7679
from transformers.models.qwen3.modeling_qwen3 import Qwen3DecoderLayer
7780

81+
7882
def make_lpcd_metrics(
79-
lpcd_config: LPCDConfig,
80-
block_q: nn.Module,
81-
block_f: nn.Module
82-
) -> LpcdMetricGroup:
83+
lpcd_config: LPCDConfig, block_q: nn.Module, block_f: nn.Module
84+
) -> LpcdMetricGroup:
8385
# Implement logic to select and return the appropriate LpcdMetric subclass
8486
# based on the type of *block* (e.g., LlamaDecoderLayer, etc.)
8587
if isinstance(block_q, LlamaDecoderLayer):
8688
# Llama
8789
from .arch._llama import make_llama_lpcd_metrics
90+
8891
return make_llama_lpcd_metrics(lpcd_config, block_q, block_f)
8992
elif isinstance(block_q, Qwen3DecoderLayer):
9093
# Qwen3
9194
from .arch._qwen3 import make_qwen3_lpcd_metrics
95+
9296
return make_qwen3_lpcd_metrics(lpcd_config, block_q, block_f)
9397

9498
# Add more architecture-specific cases here
9599
else:
96100
cls_name = block_q.__class__.__name__
97101
raise NotImplementedError(f"No LPCD module group implemented for {cls_name}")
98-

0 commit comments

Comments
 (0)