Skip to content

Commit dda6ed5

Browse files
committed
fix: remove dead halftone code + fix docstring + switch to from_hf()
7 fixes from code review: REMOVED (dead code producing wrong results if called): 1. HALFTONE_POS + HALFTONE_TO_BIN consts — only used by dead function 2. project_row_bf16_strided() — halftone version with interpolated odd bins. Production uses project_1row_bf16_strided (all 17 real bins). Same-ish name, wrong results = trap. 3. read_tensor_bf16_raw() — loads full tensor as Vec<u16>. Replaced by inline chunked reads. OOM on 10.7 GB expert tensors. 4. test_halftone_positions_coverage — tested dead const 5. SCOUT_SHARD_SIZES — no longer needed (from_hf gets exact sizes) FIXED: 6. project_tensor_bf16_simd docstring: "9 halftone bins" → "17 bins", "9 zmm" → "17 zmm", "171 vaddpd" → "323 vaddpd" 7. test_strided_vs_full_agreement: compared dead project_row_bf16_strided → now compares project_1row_bf16_strided (production path) FIXED (hardcoded URLs): 8. run_llama4_shard: hardcoded URL → HttpRangeReader::from_hf(repo, filename) 9. Maverick test: hardcoded URL → HttpRangeReader::from_hf(repo, filename) Gets exact CDN URLs, exact sizes, benefits from re-resolve on token expiry. OK (production path verified correct): - project_8rows_bf16_simd: all 17 bins, SIMD gather, correct - project_1row_bf16_strided: all 17 bins, scalar fallback, correct - stream_index_gguf_bf16_with_header: chunked 128 MB, correct 20 tests pass, 8 ignored (network-dependent). https://claude.ai/code/session_019RzHP8tpJu55ESTxhfUy1A
1 parent bd7ce5e commit dda6ed5

1 file changed

Lines changed: 12 additions & 121 deletions

File tree

src/hpc/gguf_indexer.rs

Lines changed: 12 additions & 121 deletions
Original file line numberDiff line numberDiff line change
@@ -149,25 +149,6 @@ pub fn project_row_to_base17(row: &[f32]) -> Base17 {
149149
// BF16-direct optimizations: skip f32 intermediate, strided octave sampling
150150
// ============================================================================
151151

152-
/// Halftone-dropped golden positions: keep every other step (9 of 17).
153-
/// Well-distributed across 0..16; max gap = 3. Odd bins interpolated.
154-
const HALFTONE_POS: [u8; 9] = {
155-
let mut t = [0u8; 9];
156-
let mut i = 0;
157-
let mut j = 0;
158-
while i < BASE_DIM {
159-
if i % 2 == 0 {
160-
t[j] = ((i * GOLDEN_STEP) % BASE_DIM) as u8;
161-
j += 1;
162-
}
163-
i += 1;
164-
}
165-
t
166-
};
167-
168-
/// Which of the 17 Base17 bins each halftone position maps to.
169-
const HALFTONE_TO_BIN: [u8; 9] = [0, 2, 4, 6, 8, 10, 12, 14, 16];
170-
171152
/// Convert one BF16 u16 to f64. Zero allocation.
172153
#[inline(always)]
173154
fn bf16_to_f64(bits: u16) -> f64 {
@@ -205,52 +186,6 @@ pub fn project_row_bf16_direct(row: &[u16]) -> Base17 {
205186
Base17 { dims }
206187
}
207188

208-
/// Project a BF16 row with octave stride and halftone dropping.
209-
///
210-
/// For a 5120-element row at stride=16:
211-
/// 302 octaves / 16 = 19 sampled × 9 halftone = 171 BF16→f64 conversions
212-
/// vs 5120 in the full path (97% reduction).
213-
/// Odd bins interpolated from neighbors.
214-
pub fn project_row_bf16_strided(row: &[u16], octave_stride: usize) -> Base17 {
215-
let d = row.len();
216-
let n_octaves = (d + BASE_DIM - 1) / BASE_DIM;
217-
218-
let mut half_sum = [0.0f64; 9];
219-
let mut half_count = [0u32; 9];
220-
221-
let mut octave = 0;
222-
while octave < n_octaves {
223-
for hi in 0..9 {
224-
let dim = octave * BASE_DIM + HALFTONE_POS[hi] as usize;
225-
if dim < d {
226-
half_sum[hi] += bf16_to_f64(row[dim]);
227-
half_count[hi] += 1;
228-
}
229-
}
230-
octave += octave_stride;
231-
}
232-
233-
let mut dims = [0i16; BASE_DIM];
234-
235-
// Even bins: direct from halftone samples
236-
for hi in 0..9 {
237-
let bin = HALFTONE_TO_BIN[hi] as usize;
238-
if half_count[hi] > 0 {
239-
let mean = half_sum[hi] / half_count[hi] as f64;
240-
dims[bin] = (mean * FP_SCALE).round().clamp(-32768.0, 32767.0) as i16;
241-
}
242-
}
243-
244-
// Odd bins: interpolate from neighbors (circular)
245-
for odd in (1..BASE_DIM).step_by(2) {
246-
let left = dims[odd - 1] as i32;
247-
let right = dims[(odd + 1) % BASE_DIM] as i32;
248-
dims[odd] = ((left + right) / 2) as i16;
249-
}
250-
251-
Base17 { dims }
252-
}
253-
254189
// ── F64x8 SIMD: 8 rows → 8 Base17 in parallel ──
255190

256191
/// Gather 8 BF16 values from 8 rows at the same column, convert to F64x8.
@@ -364,11 +299,11 @@ pub fn project_1row_bf16_strided(row: &[u16], octave_stride: usize) -> Base17 {
364299

365300
/// Project an entire BF16 tensor to Base17 using F64x8 SIMD.
366301
///
367-
/// Processes 8 rows in parallel per SIMD batch. Each of the 9 halftone bins
368-
/// holds an F64x8 accumulator (8 rows × 9 bins = 72 f64 lanes = 9 zmm registers).
302+
/// Processes 8 rows in parallel per SIMD batch. Each of the 17 bins
303+
/// holds an F64x8 accumulator (8 rows × 17 bins = 136 f64 lanes = 17 zmm registers).
369304
///
370-
/// Per sampled octave: 9 halftone positions × 8 bf16_to_f64 gathers → 9 vaddpd.
371-
/// For 5120-col rows at stride=16: 19 octaves × 9 = 171 vaddpd per 8-row batch.
305+
/// Per sampled octave: 17 positions × 8 bf16_to_f64 gathers → 17 vaddpd.
306+
/// For 5120-col rows at stride=16: 19 octaves × 17 = 323 vaddpd per 8-row batch.
372307
pub fn project_tensor_bf16_simd(
373308
buf: &[u16],
374309
n_rows: usize,
@@ -401,31 +336,6 @@ pub fn project_tensor_bf16_simd(
401336
result
402337
}
403338

404-
/// Read a BF16 tensor as raw u16 values. NO f32 conversion.
405-
/// `buf` is reusable — caller allocates once, passes to every tensor.
406-
pub fn read_tensor_bf16_raw<R: Read + Seek>(
407-
reader: &mut R,
408-
gguf_file: &gguf::GgufFile,
409-
tensor: &gguf::TensorInfo,
410-
buf: &mut Vec<u16>,
411-
) -> Result<usize, String> {
412-
let abs_offset = gguf_file.tensor_data_offset + tensor.offset;
413-
reader.seek(std::io::SeekFrom::Start(abs_offset)).map_err(|e| e.to_string())?;
414-
415-
let n_elements = tensor.element_count() as usize;
416-
if buf.len() < n_elements {
417-
buf.resize(n_elements, 0);
418-
}
419-
420-
// SAFETY: u16 and [u8; 2] have the same layout on little-endian (x86/ARM).
421-
let byte_slice = unsafe {
422-
std::slice::from_raw_parts_mut(buf.as_mut_ptr() as *mut u8, n_elements * 2)
423-
};
424-
reader.read_exact(byte_slice).map_err(|e| e.to_string())?;
425-
426-
Ok(n_elements)
427-
}
428-
429339
/// Helper: tensor dimensions → (rows, cols) without needing data.
430340
fn tensor_to_rows_dims(dims: &[u64], layer_type: &LayerType) -> (usize, usize) {
431341
match layer_type {
@@ -1206,14 +1116,6 @@ mod tests {
12061116
}
12071117

12081118
/// Exact Scout BF16 shard sizes (verified via HuggingFace HEAD).
1209-
const SCOUT_SHARD_SIZES: [u64; 5] = [
1210-
48_940_000_000, // shard 1: layers 0-10 + embeddings
1211-
49_960_000_000, // shard 2: layers 11-21
1212-
48_660_000_000, // shard 3: layers 22-32
1213-
49_790_000_000, // shard 4: layers 33-43
1214-
18_220_000_000, // shard 5: layers 44-47 + output
1215-
];
1216-
12171119
/// Run one shard of Llama 4 Scout BF16 through the BF16-direct indexer.
12181120
///
12191121
/// Uses stream_index_gguf_bf16 with F64x8 SIMD and strided octave sampling.
@@ -1226,14 +1128,13 @@ mod tests {
12261128
let filename = format!(
12271129
"BF16/Llama-4-Scout-17B-16E-Instruct-BF16-{:05}-of-00005.gguf", shard
12281130
);
1229-
let size = SCOUT_SHARD_SIZES[(shard - 1) as usize];
1230-
let octave_stride: usize = 16; // 4 octaves higher + halftone drop
1131+
let octave_stride: usize = 16;
12311132

1232-
let url = format!("https://huggingface.co/{}/resolve/main/{}", repo, filename);
1233-
eprintln!("Streaming shard {}/5: {} ({:.2} GB)", shard, filename, size as f64 / 1e9);
1133+
eprintln!("Streaming shard {}/5: {}", shard, filename);
12341134
eprintln!(" BF16-direct, octave_stride={}, F64x8 SIMD", octave_stride);
12351135

1236-
let mut reader = HttpRangeReader::with_chunk_size(url, size, 256 * 1024 * 1024);
1136+
let mut reader = HttpRangeReader::from_hf(repo, &filename, 256 * 1024 * 1024)
1137+
.expect("failed to resolve HF URL — check repo/filename");
12371138

12381139
let out_path = format!("/tmp/llama4_scout_shard{}.bgz7", shard);
12391140
let out = std::fs::File::create(&out_path).expect("create output");
@@ -1296,14 +1197,6 @@ mod tests {
12961197

12971198
// ── BF16-direct optimization tests ──
12981199

1299-
#[test]
1300-
fn test_halftone_positions_coverage() {
1301-
let positions: Vec<u8> = HALFTONE_POS.to_vec();
1302-
let mut sorted = positions.clone();
1303-
sorted.sort();
1304-
assert_eq!(sorted, vec![0, 1, 3, 5, 6, 8, 10, 13, 15]);
1305-
}
1306-
13071200
#[test]
13081201
fn test_bf16_to_f64_accuracy() {
13091202
assert_eq!(bf16_to_f64(0x3F80), 1.0);
@@ -1318,7 +1211,7 @@ mod tests {
13181211
// Constant BF16 row → stride shouldn't matter
13191212
let row: Vec<u16> = vec![0x3F80; 5120]; // all 1.0
13201213
let full = project_row_bf16_direct(&row);
1321-
let strided = project_row_bf16_strided(&row, 16);
1214+
let strided = project_1row_bf16_strided(&row, 16);
13221215

13231216
for i in 0..17 {
13241217
let diff = (full.dims[i] as i32 - strided.dims[i] as i32).abs();
@@ -1443,14 +1336,12 @@ mod tests {
14431336
eprintln!();
14441337

14451338
for (shard_num, filename, size) in shards.iter() {
1446-
let url = format!("https://huggingface.co/{}/resolve/main/{}", repo, filename);
14471339
let out_path = format!("/tmp/llama4_maverick_shard{:02}.bgz7", shard_num);
14481340

1449-
eprintln!("━━━ Shard {:02}/18 ({:.2} GB) ━━━", shard_num, *size as f64 / 1e9);
1341+
eprintln!("━━━ Shard {:02}/18 ━━━", shard_num);
14501342

1451-
let mut reader = HttpRangeReader::with_chunk_size(
1452-
url.clone(), *size, 256 * 1024 * 1024
1453-
);
1343+
let mut reader = HttpRangeReader::from_hf(repo, filename, 256 * 1024 * 1024)
1344+
.expect("failed to resolve HF URL");
14541345

14551346
let out = std::fs::File::create(&out_path).expect("create output");
14561347
let mut writer = BufWriter::new(out);

0 commit comments

Comments
 (0)