Skip to content

Commit 1f0894b

Browse files
committed
Apply lintrunner auto-fixes more
1 parent 41de477 commit 1f0894b

8 files changed

Lines changed: 104 additions & 71 deletions

File tree

examples/models/gemma4_31b/CMakeLists.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ target_include_directories(
7474
)
7575
target_link_libraries(gemma4_31b_worker PUBLIC ${link_libraries})
7676

77-
# Standalone C++ DFlash benchmark runner using the Module API.
77+
# Standalone C++ DFlash benchmark runner using the Module API.
7878
add_executable(dflash_cpp_driver dflash_cpp_driver.cpp)
7979
target_include_directories(
8080
dflash_cpp_driver PUBLIC ${_common_include_directories} ${_json_include}

examples/models/gemma4_31b/dflash_cpp_driver.cpp

Lines changed: 73 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
// C++ DFlash runner for benchmarking the exported Gemma4-31B target and draft models.
1+
// C++ DFlash runner for benchmarking the exported Gemma4-31B target and draft
2+
// models.
23

34
#include <gflags/gflags.h>
45

@@ -10,25 +11,34 @@
1011
#include <algorithm>
1112
#include <chrono>
1213
#include <cstdint>
13-
#include <cstring>
1414
#include <cstdio>
15+
#include <cstring>
1516
#include <set>
1617
#include <string>
1718
#include <vector>
1819

19-
using executorch::extension::Module;
2020
using executorch::extension::make_tensor_ptr;
21+
using executorch::extension::Module;
2122
using executorch::extension::TensorPtr;
22-
using executorch::runtime::EValue;
2323
using executorch::runtime::Error;
24+
using executorch::runtime::EValue;
2425

25-
DEFINE_string(target_pte, "gemma4_31b_dflash_exports_mlx/model.pte", "Target .pte path.");
26+
DEFINE_string(
27+
target_pte,
28+
"gemma4_31b_dflash_exports_mlx/model.pte",
29+
"Target .pte path.");
2630
DEFINE_string(draft_pte, "gemma4_31b_dflash_draft.pte", "Draft .pte path.");
27-
DEFINE_string(tokenizer_path, "gemma-4-31B-it-HQQ-INT4/tokenizer.json", "Tokenizer path.");
31+
DEFINE_string(
32+
tokenizer_path,
33+
"gemma-4-31B-it-HQQ-INT4/tokenizer.json",
34+
"Tokenizer path.");
2835
DEFINE_string(prompt, "The capital of France is", "Prompt text.");
2936
DEFINE_int32(max_new_tokens, 64, "Maximum tokens to generate.");
3037
DEFINE_int32(block_size, 16, "DFlash draft block size.");
31-
DEFINE_int32(mask_id, 4, "DFlash mask token id (from draft checkpoint config).");
38+
DEFINE_int32(
39+
mask_id,
40+
4,
41+
"DFlash mask token id (from draft checkpoint config).");
3242
DEFINE_bool(raw_prompt, false, "Skip chat-template wrapping.");
3343
DEFINE_bool(verbose, false, "Print per-round timing/acceptance debug output.");
3444

@@ -72,7 +82,8 @@ int64_t first_mismatch(
7282
return static_cast<int64_t>(draft_ids.size());
7383
}
7484

75-
// Convert BF16 hidden states returned by the target model to FP32 for the draft model.
85+
// Convert BF16 hidden states returned by the target model to FP32 for the draft
86+
// model.
7687
std::vector<float> bf16_tensor_to_fp32(const executorch::aten::Tensor& t) {
7788
int64_t numel = t.numel();
7889
const uint16_t* src = reinterpret_cast<const uint16_t*>(t.const_data_ptr());
@@ -84,7 +95,7 @@ std::vector<float> bf16_tensor_to_fp32(const executorch::aten::Tensor& t) {
8495
return out;
8596
}
8697

87-
}
98+
} // namespace
8899

89100
int main(int argc, char** argv) {
90101
gflags::ParseCommandLineFlags(&argc, &argv, true);
@@ -122,15 +133,20 @@ int main(int argc, char** argv) {
122133
printf("Prompt tokens: %lld\n", (long long)prompt_len);
123134

124135
std::vector<int64_t> input_pos_vec(prompt_len);
125-
for (int64_t i = 0; i < prompt_len; ++i) input_pos_vec[i] = i;
136+
for (int64_t i = 0; i < prompt_len; ++i)
137+
input_pos_vec[i] = i;
126138

127-
auto prompt_ids_tensor =
128-
make_tensor_ptr({1, (int)prompt_len}, prompt_ids.data(), executorch::aten::ScalarType::Long);
139+
auto prompt_ids_tensor = make_tensor_ptr(
140+
{1, (int)prompt_len},
141+
prompt_ids.data(),
142+
executorch::aten::ScalarType::Long);
129143
auto input_pos_tensor = make_tensor_ptr(
130-
{(int)prompt_len}, input_pos_vec.data(), executorch::aten::ScalarType::Long);
144+
{(int)prompt_len},
145+
input_pos_vec.data(),
146+
executorch::aten::ScalarType::Long);
131147

132-
auto prefill_result =
133-
target_module.forward({EValue(prompt_ids_tensor), EValue(input_pos_tensor)});
148+
auto prefill_result = target_module.forward(
149+
{EValue(prompt_ids_tensor), EValue(input_pos_tensor)});
134150
if (!prefill_result.ok()) {
135151
ET_LOG(Error, "Prefill forward failed");
136152
return 1;
@@ -148,31 +164,36 @@ int main(int argc, char** argv) {
148164
int64_t accepted_total = 0;
149165
int64_t emitted_total = 0;
150166

151-
152-
153167
int64_t hidden_concat_dim = hidden.sizes()[2];
154168
std::vector<float> hidden_history = bf16_tensor_to_fp32(hidden);
155169
int64_t hidden_len = prompt_len;
156170

157-
// Warm up the draft model to avoid including one-time MLX JIT compilation in benchmark timings.
171+
// Warm up the draft model to avoid including one-time MLX JIT compilation in
172+
// benchmark timings.
158173
{
159174
std::vector<int64_t> warm_input_vec(FLAGS_block_size);
160175
warm_input_vec[0] = last_token;
161-
for (int64_t i = 1; i < FLAGS_block_size; ++i) warm_input_vec[i] = FLAGS_mask_id;
176+
for (int64_t i = 1; i < FLAGS_block_size; ++i)
177+
warm_input_vec[i] = FLAGS_mask_id;
162178
auto warm_input_tensor = make_tensor_ptr(
163-
{1, (int)FLAGS_block_size}, warm_input_vec.data(), executorch::aten::ScalarType::Long);
179+
{1, (int)FLAGS_block_size},
180+
warm_input_vec.data(),
181+
executorch::aten::ScalarType::Long);
164182
auto warm_hidden_tensor = make_tensor_ptr(
165183
{1, (int)hidden_len, (int)hidden_concat_dim},
166184
hidden_history.data(),
167185
executorch::aten::ScalarType::Float);
168186
std::vector<int64_t> warm_pos_vec(hidden_len + FLAGS_block_size);
169-
for (int64_t i = 0; i < hidden_len + FLAGS_block_size; ++i) warm_pos_vec[i] = i;
187+
for (int64_t i = 0; i < hidden_len + FLAGS_block_size; ++i)
188+
warm_pos_vec[i] = i;
170189
auto warm_pos_tensor = make_tensor_ptr(
171190
{1, (int)(hidden_len + FLAGS_block_size)},
172191
warm_pos_vec.data(),
173192
executorch::aten::ScalarType::Long);
174193
auto warm_result = draft_module.forward(
175-
{EValue(warm_input_tensor), EValue(warm_hidden_tensor), EValue(warm_pos_tensor)});
194+
{EValue(warm_input_tensor),
195+
EValue(warm_hidden_tensor),
196+
EValue(warm_pos_tensor)});
176197
if (!warm_result.ok()) {
177198
ET_LOG(Error, "Draft warm-up forward failed");
178199
return 1;
@@ -188,23 +209,31 @@ int main(int argc, char** argv) {
188209

189210
std::vector<int64_t> draft_input_vec(bs);
190211
draft_input_vec[0] = last_token;
191-
for (int64_t i = 1; i < bs; ++i) draft_input_vec[i] = FLAGS_mask_id;
192-
auto draft_input_tensor =
193-
make_tensor_ptr({1, (int)bs}, draft_input_vec.data(), executorch::aten::ScalarType::Long);
212+
for (int64_t i = 1; i < bs; ++i)
213+
draft_input_vec[i] = FLAGS_mask_id;
214+
auto draft_input_tensor = make_tensor_ptr(
215+
{1, (int)bs},
216+
draft_input_vec.data(),
217+
executorch::aten::ScalarType::Long);
194218

195219
auto hidden_tensor = make_tensor_ptr(
196220
{1, (int)hidden_len, (int)hidden_concat_dim},
197221
hidden_history.data(),
198222
executorch::aten::ScalarType::Float);
199223

200224
std::vector<int64_t> draft_pos_vec(hidden_len + bs);
201-
for (int64_t i = 0; i < hidden_len + bs; ++i) draft_pos_vec[i] = i;
225+
for (int64_t i = 0; i < hidden_len + bs; ++i)
226+
draft_pos_vec[i] = i;
202227
auto draft_pos_tensor = make_tensor_ptr(
203-
{1, (int)(hidden_len + bs)}, draft_pos_vec.data(), executorch::aten::ScalarType::Long);
228+
{1, (int)(hidden_len + bs)},
229+
draft_pos_vec.data(),
230+
executorch::aten::ScalarType::Long);
204231

205232
double dt0 = now_ms();
206233
auto draft_result = draft_module.forward(
207-
{EValue(draft_input_tensor), EValue(hidden_tensor), EValue(draft_pos_tensor)});
234+
{EValue(draft_input_tensor),
235+
EValue(hidden_tensor),
236+
EValue(draft_pos_tensor)});
208237
double draft_exec_ms = now_ms() - dt0;
209238
if (!draft_result.ok()) {
210239
ET_LOG(Error, "Draft forward failed at round %lld", (long long)rounds);
@@ -215,15 +244,21 @@ int main(int argc, char** argv) {
215244

216245
std::vector<int64_t> verify_input_vec;
217246
verify_input_vec.push_back(last_token);
218-
verify_input_vec.insert(verify_input_vec.end(), draft_ids.begin(), draft_ids.end());
247+
verify_input_vec.insert(
248+
verify_input_vec.end(), draft_ids.begin(), draft_ids.end());
219249
int64_t verify_len = static_cast<int64_t>(verify_input_vec.size());
220250
auto verify_input_tensor = make_tensor_ptr(
221-
{1, (int)verify_len}, verify_input_vec.data(), executorch::aten::ScalarType::Long);
251+
{1, (int)verify_len},
252+
verify_input_vec.data(),
253+
executorch::aten::ScalarType::Long);
222254

223255
std::vector<int64_t> verify_pos_vec(verify_len);
224-
for (int64_t i = 0; i < verify_len; ++i) verify_pos_vec[i] = pos + i;
256+
for (int64_t i = 0; i < verify_len; ++i)
257+
verify_pos_vec[i] = pos + i;
225258
auto verify_pos_tensor = make_tensor_ptr(
226-
{(int)verify_len}, verify_pos_vec.data(), executorch::aten::ScalarType::Long);
259+
{(int)verify_len},
260+
verify_pos_vec.data(),
261+
executorch::aten::ScalarType::Long);
227262

228263
double vt0 = now_ms();
229264
auto verify_result = target_module.forward(
@@ -247,14 +282,16 @@ int main(int argc, char** argv) {
247282
(long long)hidden_len);
248283
}
249284

250-
std::vector<int64_t> new_tokens(draft_ids.begin(), draft_ids.begin() + accepted);
285+
std::vector<int64_t> new_tokens(
286+
draft_ids.begin(), draft_ids.begin() + accepted);
251287
new_tokens.push_back(target_ids[accepted]);
252288

253289
bool hit_eos = false;
254290
for (size_t i = 0; i < new_tokens.size(); ++i) {
255291
if (kEosIds.count(new_tokens[i])) {
256292
new_tokens.resize(i + 1);
257-
accepted = std::min(accepted, static_cast<int64_t>(new_tokens.size()) - 1);
293+
accepted =
294+
std::min(accepted, static_cast<int64_t>(new_tokens.size()) - 1);
258295
hit_eos = true;
259296
break;
260297
}
@@ -274,7 +311,8 @@ int main(int argc, char** argv) {
274311
new_hidden_fp32.begin() + append_len * hidden_concat_dim);
275312
hidden_len += append_len;
276313

277-
if (hit_eos) break;
314+
if (hit_eos)
315+
break;
278316
}
279317

280318
double total_ms = now_ms() - t0;

examples/models/gemma4_31b/dflash_export.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@
1010
import torch.nn as nn
1111

1212
from executorch.examples.models.gemma4_31b.mlx_source_transformations import (
13+
_replace_attention_forward,
14+
_replace_layer_forward,
1315
MLXKVCache,
1416
MLXRingKVCache,
1517
MLXTurboQuantKVCache,
16-
_replace_attention_forward,
17-
_replace_layer_forward,
1818
)
1919
from executorch.examples.models.gemma4_31b.model import Gemma4_31B, Gemma4_31BConfig
2020

@@ -32,8 +32,8 @@ def forward(
3232
tokens: torch.LongTensor,
3333
input_pos: torch.LongTensor,
3434
) -> Tuple[torch.Tensor, torch.Tensor]:
35-
"""Returns full-sequence logits and hidden states for DFlash block verification.
36-
Unlike the base implementation, which only returns the last token logits for single-token decoding, DFlash returns logits for every position in the drafted block so run_dflash.py can perform greedy verification and first-mismatch acceptance.
35+
"""Returns full-sequence logits and hidden states for DFlash block verification.
36+
Unlike the base implementation, which only returns the last token logits for single-token decoding, DFlash returns logits for every position in the drafted block so run_dflash.py can perform greedy verification and first-mismatch acceptance.
3737
"""
3838
x = self.embed_tokens(tokens) * self.embed_normalizer
3939
sliding_mask, full_mask = self._build_masks(input_pos)
@@ -65,9 +65,7 @@ def _replace_dflash_model_forward(model: nn.Module) -> None:
6565
The stock mlx_source_transformations' _replace_model_forward overwrites the model's forward entirely, discarding Gemma4_31BWithHidden.forward, so this reinstalls the same hidden-capturing logic on top of the MLX-optimized layers.
6666
"""
6767

68-
def _mlx_dflash_model_forward(
69-
self, tokens: torch.Tensor, input_pos: torch.Tensor
70-
):
68+
def _mlx_dflash_model_forward(self, tokens: torch.Tensor, input_pos: torch.Tensor):
7169
x = self.embed_tokens(tokens) * self.embed_normalizer
7270

7371
layer_id_set = set(self.dflash_layer_ids)
@@ -154,4 +152,4 @@ def dflash_mlx_source_transformations(
154152
_replace_attention_forward(attn)
155153
_replace_layer_forward(layer)
156154

157-
_replace_dflash_model_forward(model)
155+
_replace_dflash_model_forward(model)

examples/models/gemma4_31b/export_dflash_draft.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
import argparse
77
import json
8+
from pathlib import Path
89

910
import torch
1011

@@ -14,7 +15,6 @@
1415
)
1516
from executorch.examples.models.gemma4_31b.quant.quantize import dequantize_weight
1617
from huggingface_hub import snapshot_download
17-
from pathlib import Path
1818
from safetensors import safe_open
1919
from safetensors.torch import load_file
2020
from torch.export import Dim
@@ -23,8 +23,7 @@
2323
def _load_dequantized_tensor(
2424
safetensors_path: str, logical_name: str, dtype: torch.dtype = torch.bfloat16
2525
) -> torch.Tensor:
26-
"""Loads and dequantizes a named weight from a torchao-quantized safetensors checkpoint into a dense tensor.
27-
"""
26+
"""Loads and dequantizes a named weight from a torchao-quantized safetensors checkpoint into a dense tensor."""
2827
from torchao.prototype.safetensors.safetensors_support import (
2928
unflatten_tensor_state_dict,
3029
)
@@ -43,9 +42,7 @@ def _load_dequantized_tensor(
4342
prefix = f"{module_fqn}._{weight_name}_"
4443
partial = {k: f.get_tensor(k) for k in all_keys if k.startswith(prefix)}
4544
if not partial:
46-
raise KeyError(
47-
f"No keys found with prefix {prefix!r} for {logical_name!r}"
48-
)
45+
raise KeyError(f"No keys found with prefix {prefix!r} for {logical_name!r}")
4946
result, _ = unflatten_tensor_state_dict(partial, metadata)
5047

5148
reconstructed = result[logical_name]
@@ -102,7 +99,7 @@ def main():
10299
)
103100
model.eval()
104101

105-
# Quantize the draft model to match the target model.
102+
# Quantize the draft model to match the target model.
106103
from executorch.backends.mlx.llm.quantization import quantize_model_
107104

108105
quantize_model_(

examples/models/gemma4_31b/export_dflash_target.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,11 @@
55

66
import argparse
77
import gc
8-
import json
98
import os
109

1110
import torch
1211

13-
from executorch.examples.models.gemma4_31b.dflash_export import (
14-
Gemma4_31BWithHidden,
15-
)
12+
from executorch.examples.models.gemma4_31b.dflash_export import Gemma4_31BWithHidden
1613
from executorch.examples.models.gemma4_31b.export import _pack_for_backend
1714
from executorch.examples.models.gemma4_31b.model import (
1815
Gemma4_31BConfig,
@@ -25,8 +22,7 @@ def load_prequantized_dflash_target(
2522
layer_ids: list,
2623
max_seq_len: int = 4096,
2724
) -> tuple:
28-
"""Loads the prequantized target model with DFlash hidden-state outputs.
29-
"""
25+
"""Loads the prequantized target model with DFlash hidden-state outputs."""
3026
config = Gemma4_31BConfig.from_hf_config(
3127
os.path.join(prequantized_dir, "config.json")
3228
)
@@ -53,11 +49,9 @@ def export_dflash_target_mlx(
5349
config: Gemma4_31BConfig,
5450
output_dir: str,
5551
) -> None:
56-
"""Exports the DFlash target model through torch.export and the MLX backend.
57-
"""
52+
"""Exports the DFlash target model through torch.export and the MLX backend."""
5853
import executorch.backends.mlx.custom_kernel_ops.gguf.patterns
59-
import executorch.extension.llm.export.gguf
60-
import executorch.extension.llm.export.int4
54+
import executorch.extension.llm.export.gguf # noqa: F401
6155

6256
from executorch.backends.mlx import MLXPartitioner
6357
from executorch.backends.mlx.passes import get_default_passes
@@ -161,7 +155,11 @@ def main() -> None:
161155
"Comma separated 0-indexed layer IDs matching the draft checkpoint, e.g. 1,12,23,35,46,57."
162156
),
163157
)
164-
p.add_argument("--output-dir", required=True, help="Directory for the exported .pte and .ptd files.")
158+
p.add_argument(
159+
"--output-dir",
160+
required=True,
161+
help="Directory for the exported .pte and .ptd files.",
162+
)
165163
p.add_argument("--max-seq-len", type=int, default=4096)
166164
args = p.parse_args()
167165

0 commit comments

Comments
 (0)