pescador developer on retainer: pescador.Streamer() passed a generator object instead of a generator function — Streamer exhausted after epoch 0 — 99 training epochs iterate 0 batches — model trains on 1% of data — validation accuracy 0.52 instead of 0.89 — 3 weeks — pescador developer on monthly retainer
pescador 2.1.0 • Python 3.10 • PyTorch 1.13; pescador.Streamer(gen_expr) passes a generator object — not a generator function; generator exhausted after epoch 0; epochs 1–99 each yield 0 batches; model trains on 1 of 100 intended epochs; • Southfield Pescador Ltd. (music instrument recognition; 100,000 audio clips/month; 10 classes; validation accuracy 0.52 instead of 0.89; 3 weeks of hyperparameter tuning; fix: Streamer(gen_func, clips); 1.5h retainer engagement)
Southfield Pescador Ltd. built a music instrument recognition training pipeline using pescador 2.1.0 to handle data streaming from a 100,000-clip audio corpus. The pipeline trained a convolutional neural network on 10 instrument classes (Piano, Guitar, Violin, Cello, Flute, Trumpet, Drums, Saxophone, Viola, Double Bass) over 100 epochs with a batch size of 64. To apply random pitch-shift augmentation without loading the entire corpus into memory, the developer created a generator expression and passed it directly to pescador.Streamer(): streamer = pescador.Streamer(augment(c) for c in clips). The training loop ran without raising any exception. After epoch 0, training loss appeared to stabilise completely and remained flat for epochs 1 through 99. The developer interpreted this as rapid convergence. At the end of epoch 99, validation accuracy was 0.52 against an expected 0.89. Three weeks of hyperparameter tuning — learning rate, dropout, weight decay, model depth — produced no improvement, with all runs returning validation accuracy between 0.49 and 0.56.
pescador 2.1.0 pescador.Streamer(streamer, *args, **kwargs) is designed to wrap a generator function plus its arguments. When iterate() is called, Streamer invokes streamer(*args, **kwargs) to obtain a fresh generator instance, exhausts it, and then returns. Because the generator function can be called again, each call to iterate() produces a new generator with a fresh iteration over the data — the intended behaviour for multi-epoch training loops. The failure mode occurs when a generator object (the result of evaluating a generator expression or calling a generator function) is passed instead of the function reference. A generator expression such as (augment(c) for c in clips) creates a generator object at construction time. Streamer stores this object. On the first call to iterate(), Streamer detects that the stored object is not callable in the expected way and iterates through it directly — this succeeds, yielding all 1,562 batches for epoch 0. On the second call to iterate(), the same exhausted generator object is used again; its first next() call raises StopIteration immediately; iterate() returns without yielding a single item. Epochs 1 through 99 each receive exactly zero batches. The training loop — for epoch in range(100): for batch in streamer.iterate(): ... — silently completes 99 empty epochs. No exception is raised. No warning is logged. The loss curve remains perfectly flat from epoch 1 onwards because no gradient updates occur.
The annotated buggy and fixed pescador training loop, with per-epoch batch count validation:
# Southfield Pescador Ltd. — pescador 2.1.0 Streamer generator-object fix
# pescador 2.1.0; Python 3.10; PyTorch 1.13
# Music instrument recognition; 100,000 clips/month; 10 classes; 100 epochs
#
# Problem: Streamer(gen_expr) stores a generator OBJECT (not a function)
# Generator exhausted after epoch 0; epochs 1-99 yield 0 batches
# Training loss flat from epoch 1; interpreted as convergence
# Validation accuracy 0.52 not 0.89
# Fix: Streamer(gen_func, clips) — pass function reference + args
import types
import numpy as np
import pescador
import torch
def load_and_augment(filepath: str, pitch_shift_range: float = 2.0) -> np.ndarray:
"""Load audio clip and apply random pitch shift augmentation."""
audio = load_audio(filepath) # returns float32 (n_samples,)
shift = np.random.uniform(-pitch_shift_range, pitch_shift_range)
return apply_pitch_shift(audio, shift)
# ── BUGGY training loop ──────────────────────────────────────────────────────
def train_buggy(clip_paths: list, model, optimizer, n_epochs: int = 100) -> None:
"""Train model — BUGGY: passes generator object to Streamer."""
batch_size = 64
# BUG: generator expression creates a generator OBJECT at this line
# (augment(p) for p in clip_paths) is evaluated NOW, producing a generator
# that will be exhausted after one full pass.
gen_obj = (load_and_augment(p) for p in clip_paths)
streamer = pescador.Streamer(gen_obj) # stores generator object — not function
for epoch in range(n_epochs):
batches_this_epoch = 0
for sample in streamer.iterate():
# epoch 0: works — iterates through all clips
# epoch 1-99: StopIteration on first next(); loop body never runs
if batches_this_epoch % batch_size == 0 and batches_this_epoch > 0:
update_weights(model, optimizer)
batches_this_epoch += 1
# NOTE: batches_this_epoch == 0 for epochs 1-99
# Training loop does not check this; loss curve appears flat (no updates)
# ── FIXED training loop ──────────────────────────────────────────────────────
def augmented_clip_generator(clip_paths: list, pitch_shift_range: float = 2.0):
"""Generator FUNCTION (not object) — can be called repeatedly for new epochs."""
for path in clip_paths:
yield load_and_augment(path, pitch_shift_range)
# Each call to augmented_clip_generator(clip_paths) produces a NEW generator
# Streamer calls this function at the start of each iterate(), fresh each epoch
def train_fixed(clip_paths: list, model, optimizer, n_epochs: int = 100) -> None:
"""Train model — FIXED: passes generator function + args to Streamer."""
batch_size = 64
expected_batches_per_epoch = len(clip_paths) // batch_size
# FIX: pass function reference + args — Streamer calls the function each iterate()
# augmented_clip_generator is a function (not a generator object)
streamer = pescador.Streamer(augmented_clip_generator, clip_paths)
# Safety: verify Streamer holds a callable, not a generator object
assert callable(streamer._streamer) or isinstance(
streamer._streamer, types.FunctionType
), (
"pescador.Streamer must receive a generator function, not a generator object. "
"Replace (x for x in data) with a def generator_func(data): yield from data "
"and pass the function reference: Streamer(generator_func, data)."
)
for epoch in range(n_epochs):
batches_this_epoch = 0
batch_buffer = []
for sample in streamer.iterate():
batch_buffer.append(sample)
if len(batch_buffer) == batch_size:
update_weights(model, optimizer, batch_buffer)
batch_buffer = []
batches_this_epoch += 1
# Validate that this epoch processed a reasonable number of batches
if batches_this_epoch == 0:
raise RuntimeError(
f"Epoch {epoch}: 0 batches processed. "
"Check that Streamer received a generator function (not object). "
f"Expected ~{expected_batches_per_epoch} batches."
)
if batches_this_epoch < expected_batches_per_epoch * 0.95:
import warnings
warnings.warn(
f"Epoch {epoch}: {batches_this_epoch} batches (expected "
f"~{expected_batches_per_epoch}). Check data pipeline."
)
How passing a generator expression to pescador.Streamer(), a flat training loss curve, the absence of per-epoch batch count logging, and 99 silent empty epochs combine to produce a severely undertrained model — and the correct pescador pattern for multi-epoch training
The core failure combines four independent gaps: pescador’s Streamer does not raise an error when given a generator object instead of a generator function (both are accepted at construction time, but only the function can be re-called for subsequent epochs); a flat training loss curve from epoch 1 onwards is visually indistinguishable from true convergence when the developer does not also track the number of batches processed per epoch; the training loop contained no assertion on per-epoch batch count; and the validation accuracy check was deferred to the end of epoch 99, by which time three weeks of hyperparameter experiments had been run. Any one of these gaps fixed independently would have immediately surfaced the problem: a per-epoch batch count assertion that raises if batches == 0 would trigger on epoch 1, one second into training; a loss-curve sanity check comparing epoch 0 loss to epoch 1 loss would reveal that no update occurred; a startup smoke test that calls list(streamer.iterate(max_iter=10)) twice and asserts the second call also yields 10 items would catch the generator-object anti-pattern before training begins. The correct pattern is to always pass a generator function reference (a def whose body contains yield, or a functools.partial wrapping such a function) as the first argument to pescador.Streamer(), along with the arguments the function requires. The function is called fresh at the start of each iterate() call, producing a new generator instance with an independent iteration state — this is what allows multi-epoch training to work. A generator expression such as (augment(c) for c in clips) is syntactic sugar for a generator object created at that line; it cannot be called again after exhaustion. The recovery effort was low in terms of data (the original corpus was intact) but significant in wall-clock time: three weeks of hyperparameter experiments had to be re-run on the corrected pipeline. The retainer engagement was 1.5h: 0.25h triage (per-epoch batch count logging added; epoch 0 = 1,562 batches; epochs 1–99 = 0 batches); 0.5h root cause (Streamer stores generator object; exhausted after epoch 0; function reference required); 0.25h fix (Streamer(gen_func, clips) + per-epoch assert + startup smoke test); 0.5h validation (100-epoch training run; validation accuracy 0.89; per-epoch batch count 1,540–1,562 all epochs; 1.5h total). Hours logged to HourTab with per-session breakdown.
Related retainer posts
- audiomentations developer on retainer — audiomentations 0.33.0; Python 3.9; PyTorch 1.12; TimeStretch leave_length_unchanged=False produces variable-length clips; DataLoader collate_fn RuntimeError on 15% of batches; broad except silently skips; model trains on 85% of data; accuracy 0.76 not 0.89 — 2.0h
- kapre developer on retainer — kapre 0.3.7; Python 3.9; TensorFlow 2.8; load_model() without custom_objects raises ValueError; broad handler falls back to untrained model; 100,000 tracks/month predicted as ‘Electronic’; 4 weeks — 1.5h
- librosa developer on retainer — librosa 0.9.2; Python 3.9; y, sr = librosa.load(path) default sr=22050 resamples silently; model trained at 44100 Hz; production audio resampled 2× before inference; pitch shifted one octave; accuracy drops 34% — 2.0h
Track retainer hours without a client portal
HourTab turns your time-tracker CSV into a public URL your client bookmarks. No login. No portal. CSV in, URL out.
See pricing →