Skip to content

Commit 311e102

Browse files
style: apply pre-commit hooks (isort, black) to global_ptq
Ran `pre-commit install` and `pre-commit run --all-files` as requested in review. isort and black (line-length 99) reformat the `global_ptq/` package, which had not been run through the hooks before. No functional changes -- formatting only. Because the hooks run over every file, this also touches modules outside the scope of this PR: `_core/dbf_adapter.py`, `_core/gptq_adapter.py`, `_core/losses.py`, `example/example_global_ptq.py` and the two test modules under `global_ptq/tests/`. The other hooks (no-japanese, copyright-header, no-email-address) pass without changes.
1 parent b9940cc commit 311e102

11 files changed

Lines changed: 604 additions & 343 deletions

File tree

global_ptq/example/example_global_ptq.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,10 @@
55
66
"""
77

8-
from onecomp import Runner, ModelConfig, GPTQ, CalibrationConfig, setup_logger
98
from onecomp_globalptq import GlobalPTQ
109

10+
from onecomp import GPTQ, CalibrationConfig, ModelConfig, Runner, setup_logger
11+
1112
MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
1213

1314
setup_logger()

global_ptq/onecomp_globalptq/global_ptq/_core/core.py

Lines changed: 96 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,31 @@
2020
import torch.nn as nn
2121
import torch.nn.functional as F
2222

23+
from .dbf_adapter import (
24+
load_dbf_state,
25+
restore_dbf_original,
26+
save_dbf_state,
27+
setup_dbf_differentiable,
28+
setup_dbf_forwards_only,
29+
write_back_dbf_binary,
30+
write_back_dbf_scaling,
31+
)
32+
from .gptq_adapter import (
33+
find_gptq_modules,
34+
load_gptq_state,
35+
restore_gptq_original,
36+
save_gptq_state,
37+
setup_gptq_differentiable,
38+
setup_gptq_forwards_only,
39+
write_back_gptq_params,
40+
)
2341
from .helpers import (
2442
detect_quantization_method,
2543
disable_gradient_checkpointing,
2644
enable_gradient_checkpointing,
27-
remove_input_require_grads,
2845
get_language_model_backbone,
2946
get_logits,
47+
remove_input_require_grads,
3048
)
3149
from .losses import (
3250
clear_hooks,
@@ -36,24 +54,6 @@
3654
remove_hooks,
3755
setup_intermediate_hooks,
3856
)
39-
from .gptq_adapter import (
40-
find_gptq_modules,
41-
load_gptq_state,
42-
restore_gptq_original,
43-
save_gptq_state,
44-
setup_gptq_differentiable,
45-
setup_gptq_forwards_only,
46-
write_back_gptq_params,
47-
)
48-
from .dbf_adapter import (
49-
load_dbf_state,
50-
restore_dbf_original,
51-
save_dbf_state,
52-
setup_dbf_differentiable,
53-
setup_dbf_forwards_only,
54-
write_back_dbf_binary,
55-
write_back_dbf_scaling,
56-
)
5757
from .mdbf_adapter import (
5858
load_mdbf_state,
5959
restore_mdbf_original,
@@ -272,8 +272,7 @@ def build_param_to_layer_map(
272272
for p in mod.parameters():
273273
if p.requires_grad:
274274
param_to_layer[id(p)] = layer_idx
275-
for attr in ("_opt_scales", "_opt_zeros", "_opt_intweight",
276-
"_opt_bp1", "_opt_bp3"):
275+
for attr in ("_opt_scales", "_opt_zeros", "_opt_intweight", "_opt_bp1", "_opt_bp3"):
277276
if hasattr(mod, attr):
278277
param_to_layer[id(getattr(mod, attr))] = layer_idx
279278

@@ -333,8 +332,7 @@ def compute_fisher_diagonal(
333332
pid = id(p)
334333
if pid in param_to_layer:
335334
fisher_acc[param_to_layer[pid]] = (
336-
fisher_acc.get(param_to_layer[pid], 0.0)
337-
+ p.grad.float().pow(2).sum().item()
335+
fisher_acc.get(param_to_layer[pid], 0.0) + p.grad.float().pow(2).sum().item()
338336
)
339337

340338
model.zero_grad()
@@ -398,8 +396,7 @@ def set_layer_grad(
398396
if lidx in layer_idx_set:
399397
for p in mod.parameters():
400398
p.requires_grad_(enable)
401-
for attr in ("_opt_scales", "_opt_zeros", "_opt_intweight",
402-
"_opt_bp1", "_opt_bp3"):
399+
for attr in ("_opt_scales", "_opt_zeros", "_opt_intweight", "_opt_bp1", "_opt_bp3"):
403400
if hasattr(mod, attr):
404401
getattr(mod, attr).requires_grad_(enable)
405402

@@ -464,7 +461,10 @@ def eval_kl(
464461
logits_s = get_logits(model(input_ids))
465462
logits_t = _teacher_logits(teacher_model, input_ids, teacher_dev, dev)
466463
total += compute_kl_loss(
467-
logits_t, logits_s, temperature, attention_mask=attention_mask,
464+
logits_t,
465+
logits_s,
466+
temperature,
467+
attention_mask=attention_mask,
468468
).item()
469469
n += 1
470470
if was_training:
@@ -649,9 +649,7 @@ def run_kl_distillation(
649649
650650
The model is modified **in-place**. Returns a results dict.
651651
"""
652-
dev = torch.device(
653-
student_device or ("cuda" if torch.cuda.is_available() else "cpu")
654-
)
652+
dev = torch.device(student_device or ("cuda" if torch.cuda.is_available() else "cpu"))
655653
teacher_dev = torch.device(teacher_device) if teacher_device else dev
656654

657655
# ------------------------------------------------------------------
@@ -682,8 +680,11 @@ def run_kl_distillation(
682680
# ------------------------------------------------------------------
683681
logger.info("Loading calibration data (n=%d, len=%d)...", num_calibration_samples, max_length)
684682
dataloader = _prepare_dataloader(
685-
model_config, num_calibration_samples, max_length,
686-
calibration_strategy, calibration_seed,
683+
model_config,
684+
num_calibration_samples,
685+
max_length,
686+
calibration_strategy,
687+
calibration_seed,
687688
calibration_dataset=calibration_dataset,
688689
model=quantized_model,
689690
)
@@ -715,7 +716,10 @@ def run_kl_distillation(
715716
if method == "gptq":
716717
gptq_modules = detected_modules
717718
original_forwards, scaling_params, intweight_params = setup_gptq_differentiable(
718-
gptq_modules, dev, gptq_optimize_intweight, ste_k,
719+
gptq_modules,
720+
dev,
721+
gptq_optimize_intweight,
722+
ste_k,
719723
)
720724
param_groups = [{"params": scaling_params, "lr": gptq_lr}]
721725
if intweight_params:
@@ -730,7 +734,8 @@ def run_kl_distillation(
730734
elif method == "dbf":
731735
dbf_modules = detected_modules
732736
original_forwards, scaling_params, binary_params = setup_dbf_differentiable(
733-
dbf_modules, optimize_binary,
737+
dbf_modules,
738+
optimize_binary,
734739
)
735740
all_dbf_params = list(scaling_params)
736741
if binary_params:
@@ -746,7 +751,9 @@ def run_kl_distillation(
746751
elif method == "mdbf":
747752
mdbf_modules = detected_modules
748753
original_forwards, scaling_params, binary_params = setup_mdbf_differentiable(
749-
mdbf_modules, optimize_binary, ste_k=mdbf_ste_k,
754+
mdbf_modules,
755+
optimize_binary,
756+
ste_k=mdbf_ste_k,
750757
)
751758
logger.info("MDBF binary STE sharpness mdbf_ste_k=%.4g", mdbf_ste_k)
752759
all_mdbf_params = list(scaling_params)
@@ -783,27 +790,35 @@ def run_kl_distillation(
783790
logger.info("Computing Fisher diagonal for per-layer LR...")
784791
ptl_map = build_param_to_layer_map(detected_modules)
785792
fisher_diag = compute_fisher_diagonal(
786-
quantized_model, dataloader, dev, ptl_map, n_samples=fisher_n_samples,
793+
quantized_model,
794+
dataloader,
795+
dev,
796+
ptl_map,
797+
n_samples=fisher_n_samples,
787798
)
788799
fisher_mult = build_fisher_lr_multipliers(fisher_diag, fisher_min_mult, fisher_max_mult)
789800
if fisher_mult:
790801
logger.info(
791802
"Fisher LR multipliers: min=%.3f, max=%.3f, layers=%d",
792-
min(fisher_mult.values()), max(fisher_mult.values()), len(fisher_mult),
803+
min(fisher_mult.values()),
804+
max(fisher_mult.values()),
805+
len(fisher_mult),
793806
)
794807
# Determine default weight decay based on method (AdamW vs Adam)
795808
default_wd = 0.01 if method == "gptq" else 0.0
796-
809+
797810
new_groups: list = []
798811
for pg in param_groups:
799812
for p in pg["params"]:
800813
pid = id(p)
801814
mult = fisher_mult.get(ptl_map.get(pid, -1), 1.0)
802-
new_groups.append({
803-
"params": [p],
804-
"lr": pg["lr"] * mult,
805-
"weight_decay": pg.get("weight_decay", default_wd),
806-
})
815+
new_groups.append(
816+
{
817+
"params": [p],
818+
"lr": pg["lr"] * mult,
819+
"weight_decay": pg.get("weight_decay", default_wd),
820+
}
821+
)
807822
param_groups = new_groups
808823

809824
# ------------------------------------------------------------------
@@ -842,7 +857,8 @@ def run_kl_distillation(
842857
set_layer_grad(detected_modules, all_layer_indices - initial_active, False)
843858
logger.info(
844859
"Progressive unfreeze: %d/%d layers active initially",
845-
len(initial_active), total_layers,
860+
len(initial_active),
861+
total_layers,
846862
)
847863

848864
# ------------------------------------------------------------------
@@ -884,7 +900,9 @@ def run_kl_distillation(
884900
if use_lr_schedule:
885901
scheduler = torch.optim.lr_scheduler.LambdaLR(
886902
optimizer,
887-
lr_lambda=lambda step: cosine_warmup_lr_lambda(step, effective_total_steps, warmup_steps, min_lr_ratio),
903+
lr_lambda=lambda step: cosine_warmup_lr_lambda(
904+
step, effective_total_steps, warmup_steps, min_lr_ratio
905+
),
888906
)
889907

890908
# EMA tracker
@@ -932,7 +950,12 @@ def run_kl_distillation(
932950
restore_mdbf_original(mdbf_modules, original_forwards)
933951

934952
initial_kl = eval_kl(
935-
quantized_model, teacher_model, dataloader, dev, temperature, teacher_dev,
953+
quantized_model,
954+
teacher_model,
955+
dataloader,
956+
dev,
957+
temperature,
958+
teacher_dev,
936959
)
937960
logger.info("Initial KL = %.6f", initial_kl)
938961

@@ -974,9 +997,8 @@ def run_kl_distillation(
974997

975998
n_accum_steps += 1
976999
is_accum_boundary = (
977-
(batch_idx + 1) % grad_accum_steps == 0
978-
or batch_idx == total_batches - 1
979-
)
1000+
batch_idx + 1
1001+
) % grad_accum_steps == 0 or batch_idx == total_batches - 1
9801002
# Actual number of steps in this accumulation cycle
9811003
current_accum_steps = n_accum_steps if is_accum_boundary else grad_accum_steps
9821004

@@ -989,11 +1011,17 @@ def _forward_and_loss() -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
9891011
with amp_ctx:
9901012
logits_s = get_logits(quantized_model(input_ids))
9911013
logits_t = _teacher_logits(
992-
teacher_model, input_ids, teacher_dev, dev,
1014+
teacher_model,
1015+
input_ids,
1016+
teacher_dev,
1017+
dev,
9931018
)
9941019

9951020
kl = compute_kl_loss(
996-
logits_t, logits_s, temperature, attention_mask=attention_mask,
1021+
logits_t,
1022+
logits_s,
1023+
temperature,
1024+
attention_mask=attention_mask,
9971025
)
9981026

9991027
inter = torch.tensor(0.0, device=dev)
@@ -1057,7 +1085,7 @@ def _forward_and_loss() -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
10571085

10581086
# --- Standard path ---
10591087
else:
1060-
if (batch_idx % grad_accum_steps == 0):
1088+
if batch_idx % grad_accum_steps == 0:
10611089
optimizer.zero_grad()
10621090

10631091
loss, kl_loss, inter_loss = _forward_and_loss()
@@ -1085,7 +1113,7 @@ def _forward_and_loss() -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
10851113

10861114
if scheduler is not None:
10871115
scheduler.step()
1088-
1116+
10891117
optimizer.zero_grad()
10901118
n_accum_steps = 0
10911119

@@ -1094,7 +1122,9 @@ def _forward_and_loss() -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
10941122
ema_tracker.update(all_opt_params)
10951123

10961124
epoch_kl += kl_loss.item()
1097-
epoch_inter += inter_loss.item() if isinstance(inter_loss, torch.Tensor) else inter_loss
1125+
epoch_inter += (
1126+
inter_loss.item() if isinstance(inter_loss, torch.Tensor) else inter_loss
1127+
)
10981128
epoch_loss += loss.item()
10991129
n_batches += 1
11001130

@@ -1119,7 +1149,12 @@ def _forward_and_loss() -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
11191149
restore_mdbf_original(mdbf_modules, original_forwards)
11201150

11211151
current_kl = eval_kl(
1122-
quantized_model, teacher_model, dataloader, dev, temperature, teacher_dev,
1152+
quantized_model,
1153+
teacher_model,
1154+
dataloader,
1155+
dev,
1156+
temperature,
1157+
teacher_dev,
11231158
)
11241159

11251160
if current_kl < best_kl:
@@ -1221,7 +1256,12 @@ def _forward_and_loss() -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
12211256
# Final evaluation
12221257
quantized_model.eval()
12231258
final_kl = eval_kl(
1224-
quantized_model, teacher_model, dataloader, dev, temperature, teacher_dev,
1259+
quantized_model,
1260+
teacher_model,
1261+
dataloader,
1262+
dev,
1263+
temperature,
1264+
teacher_dev,
12251265
)
12261266

12271267
# Cleanup
@@ -1232,7 +1272,7 @@ def _forward_and_loss() -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
12321272
restore_dbf_original(dbf_modules, original_forwards, cleanup=True)
12331273
elif method == "mdbf":
12341274
restore_mdbf_original(mdbf_modules, original_forwards, cleanup=True)
1235-
1275+
12361276
del teacher_model
12371277
gc.collect()
12381278
torch.cuda.empty_cache()

0 commit comments

Comments
 (0)