How to get the filename of a sample from a DataLoader?
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
In PyTorch, DataLoader returns batches built from your dataset’s __getitem__ output. If you need each sample’s filename, the dataset must return it explicitly. Many users expect DataLoader to expose source file paths automatically, but it only collates what __getitem__ provides. The clean solution is to include metadata like filename/path in each sample and handle batching with a compatible collate function.
Core Sections
1. Return filename from dataset
Now filenames are part of each sample tuple.
2. Iterate DataLoader with filenames
Default collate stacks tensors and keeps string lists for filenames.
3. Return full path if needed
Replace path.name with str(path) when downstream steps need absolute/relative paths.
4. Dictionary-based sample format
For readability in larger projects:
Then batch loop uses dictionary keys.
5. Custom collate edge cases
If sample structure is complex (variable shapes, nested metadata), implement collate_fn to control batch assembly and preserve metadata exactly.
6. Logging and reproducibility
Persist filenames for misclassified samples and evaluation outputs. This enables traceability from model predictions back to source files.
Validation and production readiness
A working snippet is only the first step. To make the solution dependable, validate behavior under representative inputs and operating conditions. Build a small test matrix that includes normal cases, boundary values, and malformed data so failure modes are explicit. If the topic involves time, concurrency, or networking, add at least one test that simulates delayed execution and one test that verifies timeout handling. This catches race conditions and environment-specific bugs that rarely appear in local happy-path runs.
Operational clarity matters as much as correctness. Document assumptions near the implementation: runtime version, required dependencies, expected timezone or locale rules, and platform limitations. Ambiguous assumptions are a major source of production incidents because teammates run the same logic under different defaults. Use structured logs around critical branches and external calls so debugging does not require ad hoc reproduction. Logs should include identifiers and concise context, but avoid sensitive payloads.
For recurring jobs or frequently executed code paths, add observability and guardrails. Define simple success metrics, retry boundaries, and explicit rollback or fallback behavior. Silent retries with no upper limit can hide systemic failures and increase downstream impact. Keep a lightweight pre-deploy checklist in source control so changes remain auditable and repeatable across environments.
Teams that treat these checks as part of the default implementation workflow usually spend less time on incident triage and more time shipping stable improvements.
Common Pitfalls
- Expecting DataLoader to expose filenames automatically.
- Returning non-collatable metadata structures without custom
collate_fn. - Dropping filenames during transform wrappers or dataset adapters.
- Using shuffled loaders when deterministic filename order is required.
- Storing only basename when duplicate names exist across directories.
Summary
To get filenames from a DataLoader, include them in dataset __getitem__ output. DataLoader will batch whatever your dataset returns, including strings and dictionaries. For advanced metadata needs, define a custom collate function. This pattern keeps training and evaluation pipelines traceable and debuggable.
Related reading
- How to get the type of a Tensor?
- How to implement dropout in Pytorch, and where to apply it
- How to include batch size in pytorch basic example?
- How to iterate over layers in Pytorch
- How to get the global_step when restoring checkpoints in Tensorflow?
- How to get the value of a tensor? Python
- How to get the last N rows of a pandas DataFrame?
- How to get the line count of a large file cheaply in Python
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.