Inference API
Conditional-inference utilities for discrete latent models: inpainting, super-resolution, masking helpers, large-volume tiling, and deployment-oriented optimizations (KV-cache, quantization, pruning, ONNX export).
Masking and Spatial Utilities
- medlatents.inference.create_spatial_mask(shape, mask_type, mask_ratio=0.5, **mask_kwargs)[source][source]
Create spatial masks for inpainting/super-resolution. True = keep, False = mask.
- medlatents.inference.spatial_to_sequence_mask(spatial_mask, rasterization_method='hilbert', **raster_kwargs)[source][source]
Convert spatial mask to sequence mask using rasterization.
- medlatents.inference.apply_token_mask(tokens, mask, mask_value)[source][source]
Apply mask to token sequence. True = keep, False = mask.
Accepts
maskas either a 1-D(seq,)tensor (broadcast across batch) or a 2-D(batch, seq)tensor (per-sample mask). Both are common in practice — a single shared mask is natural forcentre-maskinpainting of a fixed region, and per-sample masks are needed for anomaly-detection pipelines where each image has the anomaly at a different location.
- medlatents.inference.confidence_mask(logits, threshold)[source][source]
Create mask based on prediction confidence. True = high confidence, False = low.
Inpainting
End-to-end inpainting plus per-architecture entry points.
- medlatents.inference.inpaint_volume(model, tokenizer, volume, mask, model_type, rasterization_method='hilbert', **inpaint_kwargs)[source][source]
End-to-end volume inpainting: volume → tokens → inpaint → volume.
- medlatents.inference.inpaint_autoregressive(model, tokens, mask, mask_token, num_iterations=5, temperature=1.0, top_p=0.95, confidence_threshold=0.1)[source][source]
Inpaint using autoregressive model with iterative refinement.
- medlatents.inference.inpaint_maskgit(model, tokens, mask, mask_token, num_steps=12, temperature=1.0, schedule='cosine')[source][source]
Inpaint using MaskGIT with confidence-based scheduling.
maskis True at positions to keep (visible) and False at positions to inpaint. Accepts either a 1-D(seq,)mask (shared across the batch, natural for centre-mask demos) or a 2-D(batch, seq)mask (per-sample, natural for anomaly-detection pipelines where each image’s anomaly is at a different location).
- medlatents.inference.inpaint_flow_matching(model, tokens, mask, mask_token, num_steps=100, temperature=1.0, path_type='polynomial', source_dist_type='uniform', vocab_size=1024)[source][source]
Inpaint using flow matching with conditional generation.
- Parameters:
- Return type:
Int[Tensor, 'batch seq']
- medlatents.inference.inpaint_diffusion_repaint(model, diffusion, tokens, mask, num_steps=50, jump_length=10, jump_n_sample=10)[source][source]
Inpaint using RePaint algorithm for discrete diffusion (D3PM).
Super-Resolution
- medlatents.inference.super_resolve_slices(model, tokenizer, volume, target_slices, axis=0, model_type='maskgit', interpolation_mode='trilinear', rasterization_method='hilbert', **inpaint_kwargs)[source][source]
Super-resolve volume slices: upsample + inpaint interpolated slices.
- Parameters:
- Return type:
- medlatents.inference.anisotropic_super_resolution(model, tokenizer, volume, target_shape, model_type='maskgit', interpolation_mode='trilinear', rasterization_method='hilbert', **inpaint_kwargs)[source][source]
Super-resolve volume with anisotropic resolution.
- medlatents.inference.progressive_super_resolution(model, tokenizer, volume, target_slices, axis=0, num_stages=2, model_type='maskgit', **inpaint_kwargs)[source][source]
Progressive super-resolution: upsample in multiple stages.
Large-Volume Processing
- medlatents.inference.encode_large_volume(tokenizer, volume)[source][source]
Encode large volume. The tokenizer handles sliding window inference automatically.
- medlatents.inference.decode_large_volume(tokenizer, tokens)[source][source]
Decode large token volume. The tokenizer handles sliding window inference automatically.
KV-Cache
- class medlatents.inference.PagedKVCache(num_layers, num_heads, head_dim, block_size=16, num_blocks=1024, dtype=torch.float16, device='cuda')[source][source]
Bases:
objectPaged KV-cache for efficient memory management with variable-length sequences.
Inspired by vLLM’s PagedAttention. Allocates memory in fixed-size blocks to reduce fragmentation and enable efficient batched generation.
This is a simplified implementation - full paged attention requires custom CUDA kernels for optimal performance.
- Parameters:
- __init__(num_layers, num_heads, head_dim, block_size=16, num_blocks=1024, dtype=torch.float16, device='cuda')[source][source]
Initialize paged KV-cache.
- Parameters:
num_layers (
int) – Number of transformer layersnum_heads (
int) – Number of attention headshead_dim (
int) – Dimension per headblock_size (
int, default:16) – Tokens per block (default 16)num_blocks (
int, default:1024) – Total blocks in the pooldtype (
dtype, default:torch.float16) – Storage dtype
- class medlatents.inference.QuantizedKVCache(num_layers, config=None, max_length=None)[source][source]
Bases:
objectMemory-efficient KV-cache with INT8 quantization.
Reduces memory usage by ~4x compared to FP32 or ~2x compared to FP16. Uses per-token symmetric quantization for a good accuracy/speed tradeoff.
Usage:
cache = QuantizedKVCache(num_layers=12, config=QuantizationConfig()) # During generation for token in tokens: for layer_idx, block in enumerate(model.blocks): past_kv = cache.get(layer_idx) output, new_kv = block.forward_with_cache(x, freqs, past_kv) cache.update(layer_idx, new_kv)
- Parameters:
Quantization and Pruning
- class medlatents.inference.ModelQuantizer(config=None)[source][source]
Bases:
objectQuantize PyTorch models for efficient inference.
Supports: - Dynamic quantization (quick, no calibration needed) - Static quantization (requires calibration data) - SmoothQuant for transformer-friendly quantization
Example
quantizer = ModelQuantizer(config=QuantizationConfig(method=”dynamic”)) quantized_model = quantizer.quantize(model)
- Parameters:
config (
QuantizationConfig|None, default:None)
- __init__(config=None)[source][source]
Initialize quantizer.
- Parameters:
config (
QuantizationConfig|None, default:None) – Quantization configuration
- class medlatents.inference.QuantizationConfig(method=QuantizationMethod.DYNAMIC, dtype='int8', per_channel=True, symmetric=True, calibration_batches=100, modules_to_quantize=None, modules_to_skip=<factory>, smoothing_alpha=0.5)[source][source]
Bases:
objectConfiguration for model quantization.
- Variables:
method – Quantization method to use
dtype – Target dtype for quantized weights (int8/int4 for quantization, fp16/bf16 for casting)
per_channel – Use per-channel quantization (more accurate)
symmetric – Use symmetric quantization
calibration_batches – Number of batches for static quantization calibration
modules_to_quantize – List of module types to quantize (None = all supported)
modules_to_skip – List of module names to skip
smoothing_alpha – SmoothQuant smoothing factor (0.5 is typical)
- Parameters:
- method: medlatents.inference.quantization.QuantizationMethod = 'dynamic'
- dtype: Literal['int8', 'int4', 'fp16', 'bf16'] = 'int8'
- get_quant_dtype()[source][source]
Get quantization dtype, defaulting to int8 for non-quantized types.
- Return type:
Literal['int8','int4']
- __init__(method=QuantizationMethod.DYNAMIC, dtype='int8', per_channel=True, symmetric=True, calibration_batches=100, modules_to_quantize=None, modules_to_skip=<factory>, smoothing_alpha=0.5)[source]
- class medlatents.inference.ModelPruner(config=None)[source][source]
Bases:
objectPrune PyTorch models to reduce size and computation.
Supports: - Magnitude-based pruning (unstructured and structured) - WANDA pruning (weights + activations) - Iterative pruning with gradual sparsity increase
Example
pruner = ModelPruner(config=PruningConfig(sparsity=0.5)) pruned_model = pruner.prune(model)
- Parameters:
config (
PruningConfig|None, default:None)
- __init__(config=None)[source][source]
Initialize pruner.
- Parameters:
config (
PruningConfig|None, default:None) – Pruning configuration
- class medlatents.inference.PruningConfig(method=PruningMethod.MAGNITUDE, sparsity=0.5, structured_dim=0, granularity='element', iterative_steps=1, importance_scores=None)[source][source]
Bases:
objectConfiguration for model pruning.
- Variables:
method – Pruning method to use
sparsity – Target sparsity ratio (0.0 to 1.0)
structured_dim – Dimension for structured pruning (0=output, 1=input)
granularity – Pruning granularity (‘element’, ‘row’, ‘column’)
iterative_steps – Number of iterative pruning steps
importance_scores – Pre-computed importance scores (for custom pruning)
- Parameters:
- method: medlatents.inference.quantization.PruningMethod = 'magnitude'
- granularity: Literal['element', 'row', 'column'] = 'element'
- importance_scores: dict[str, torch.Tensor] | None = None
- medlatents.inference.prune_attention_heads(model, heads_to_prune, num_heads, head_dim)[source][source]
Prune specific attention heads from a model.
- Parameters:
- Return type:
- Returns:
Model with pruned heads (zeroed out)