torch.memory.formatBytes
function formatBytes(bytes: number): stringFormats a byte count as a human-readable string.
Converts bytes to the most appropriate unit (B, KB, MB, GB) with 2 decimal places. Useful for displaying memory statistics to users or in logs.
Unit Selection:
- < 1 KB: Bytes
- < 1 MB: Kilobytes
- < 1 GB: Megabytes
- >= 1 GB: Gigabytes
Examples:
- 512 → "512 B"
- 1536 → "1.50 KB"
- 1048576 → "1.00 MB"
- 1073741824 → "1.00 GB"
- Fixed precision: Always shows 2 decimal places
- Integer bytes: Rounds down to nearest byte
- Positive values: Designed for non-negative bytes
- Pure function: No side effects, can be called freely
Parameters
bytesnumber- Number of bytes to format
Returns
string– Formatted string with appropriate unitExamples
// Format memory statistics
const stats = torch.memory.stats();
console.log(`Active: ${torch.memory.formatBytes(stats.activeBytes)}`);
console.log(`Pooled: ${torch.memory.formatBytes(stats.pooledBytes)}`);
console.log(`Peak: ${torch.memory.formatBytes(stats.peakBytes)}`);
// Display in UI
function displayMemory() {
const stats = torch.memory.stats();
document.getElementById('memory-info').innerHTML = `
<p>Active: ${torch.memory.formatBytes(stats.activeBytes)}</p>
<p>Pooled: ${torch.memory.formatBytes(stats.pooledBytes)}</p>
<p>Total: ${torch.memory.formatBytes(stats.activeBytes + stats.pooledBytes)}</p>
`;
}
// Logging with formatted sizes
const before = torch.memory.stats();
// ...do work...
const after = torch.memory.stats();
const increase = after.activeBytes - before.activeBytes;
console.log(`Memory increased by ${torch.memory.formatBytes(Math.max(0, increase))}`);
// Batch size estimation
const available = 8 * 1024 * 1024 * 1024; // 8 GB
const perSample = 1024 * 1024; // 1 MB per sample
const maxBatch = Math.floor(available / perSample);
console.log(`Max batch size: ${maxBatch} (${torch.memory.formatBytes(available)})`);See Also
- [PyTorch N/A (torch.js specific)](https://pytorch.org/docs/stable/generated/N/A .html)
- stats - Get memory statistics to format