{"record":{"id":"84c35b7fdd10dc3f","repo":"huggingface/pytorch-image-models","slug":"scheduledbatchsampler-requires-a-sampler-with-a-le","errorCode":null,"errorMessage":"ScheduledBatchSampler requires a sampler with a length.","messagePattern":"ScheduledBatchSampler requires a sampler with a length\\.","errorType":"validation","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"timm/data/scheduled_sampler.py","lineNumber":61,"sourceCode":"            choices mixed into the progressive choice probabilities.\n    \"\"\"\n\n    def __init__(\n            self,\n            sampler: Sampler,\n            batch_sizes: Sequence[int],\n            choice_weights: Optional[Sequence[float]] = None,\n            seed: int = 0,\n            drop_last: bool = True,\n            shuffle_schedule: bool = True,\n            num_batches: Optional[int] = None,\n            choice_schedule: str = 'constant',\n            schedule_epochs: Optional[int] = None,\n            schedule_spread: float = 0.65,\n            schedule_random_mix: float = 0.1,\n    ) -> None:\n        if not hasattr(sampler, '__len__'):\n            raise TypeError('ScheduledBatchSampler requires a sampler with a length.')\n        if len(sampler) <= 0:\n            raise ValueError('ScheduledBatchSampler requires a non-empty sampler.')\n        if not batch_sizes:\n            raise ValueError('batch_sizes must contain at least one value.')\n        if any(int(batch_size) != batch_size or batch_size <= 0 for batch_size in batch_sizes):\n            raise ValueError('All scheduled batch sizes must be positive integers.')\n        if num_batches is not None and (int(num_batches) != num_batches or num_batches <= 0):\n            raise ValueError('num_batches must be a positive integer when specified.')\n        if choice_schedule not in ('constant', 'progressive'):\n            raise ValueError(\"choice_schedule must be 'constant' or 'progressive'.\")\n        if choice_schedule == 'progressive':\n            if len(batch_sizes) < 2:\n                raise ValueError('A progressive schedule requires at least two choices.')\n            if schedule_epochs is None or int(schedule_epochs) != schedule_epochs or schedule_epochs <= 0:\n                raise ValueError('schedule_epochs must be a positive integer for a progressive schedule.')\n            if schedule_spread < 0:\n                raise ValueError('schedule_spread must be non-negative.')\n            if not 0 <= schedule_random_mix <= 1:","sourceCodeStart":43,"sourceCodeEnd":79,"githubUrl":"https://github.com/huggingface/pytorch-image-models/blob/9a5261e31b3b5128526eb2658333b4c0a54464ae/timm/data/scheduled_sampler.py#L43-L79","documentation":"ScheduledBatchSampler must iterate a sized sampler to compute batch counts and budgets; the passed sampler lacks __len__ (e.g. an infinite or generator-backed sampler), so a TypeError is raised at construction.","triggerScenarios":"Passing sampler=iter(dataset), a custom Sampler without __len__, or a DistributedSamplerWrapper built over an unsized iterable to ScheduledBatchSampler.__init__.","commonSituations":"Wrapping streaming/infinite samplers; custom sampler subclasses that forgot to implement __len__; adapting example code that used itertools.cycle.","solutions":["Implement __len__ on the custom sampler (usually returning the underlying dataset length).","Use a sized sampler such as RandomSampler(dataset) or the dataset itself.","For infinite streams, pre-materialize an index list and wrap it in a sized Sampler."],"exampleFix":"# before\nclass MySampler(Sampler):\n    def __iter__(self):\n        while True:\n            yield random.randrange(n)\n\n# after\nclass MySampler(Sampler):\n    def __init__(self, n): self.n = n\n    def __iter__(self):\n        for _ in range(self.n):\n            yield random.randrange(self.n)\n    def __len__(self):\n        return self.n","handlingStrategy":"type-guard","validationCode":"assert hasattr(sampler, '__len__') and callable(getattr(sampler, '__len__')), 'sampler must be sized'","typeGuard":"def is_sized_sampler(s) -> bool:\n    return hasattr(s, '__iter__') and hasattr(s, '__len__') and callable(s.__len__)","tryCatchPattern":"try:\n    sched = ScheduledBatchSampler(sampler, batch_sizes=[128])\nexcept TypeError as e:\n    if 'sampler with a length' in str(e):\n        sampler = RandomSampler(dataset)  # sized fallback\n        sched = ScheduledBatchSampler(sampler, batch_sizes=[128])\n    else:\n        raise","preventionTips":["Implement __len__ on custom samplers.","Use framework-provided sized samplers where possible.","Unit-test custom samplers for len() support."],"tags":["timm","sampler","pytorch","type-validation"],"backgroundTag":"sampler-missing-length","analyzedSha":"9a5261e31b3b5128526eb2658333b4c0a54464ae","analyzedAt":"2026-08-27T02:34:25.417Z","schemaVersion":2},"datasetVersion":"2026-08-27T03:17:27.898Z"}