Update penta_vit_model_v1.py
Browse files12345678934 unmodified lines4445464748495019 unmodified lines70717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011131 unmodified lines1431441451461471481491508 unmodified lines15916016116216316416516626 unmodified lines19319419519619719819920016 unmodified lines2172182192202212222232242252267 unmodified lines23423523623723823924024124299 unmodified lines34234334434534634734834935035110 unmodified lines36236336436536636736884 unmodified lines4534544554564574584594 unmodified lines464465466467468469470107 unmodified lines578579580581582583584165 unmodified lines75075175275375475575675775875962 unmodified lines822823824825826827828829830831832833834835836837838839143 unmodified lines98398498598698798898951 unmodified lines10411042104310441045104610471048104910502 unmodified lines10531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093"""PentachoraViT: Vision Transformer with Pentachoron Geometric StructureEnhanced with Geometric Attention for improved head cohesion and generalizationAuthor: AbstractPhil"""import torch34 unmodified linesreturn (self.img_size // self.patch_size) ** 2# ============================================# GEOMETRIC ATTENTION COMPONENTS (OPTIMIZED)# ============================================def perfect_4simplex(device):19 unmodified linesfuse_alpha: float = 0.7phases: Tuple[float, ...] = (0.0, math.pi/2, math.pi, 3*math.pi/2)jitter: float = 0.02shift: float = 0.25rotate_cycle: int = 11use_phase_variance: bool = Falsegeometry_type: str = "pentachoron"class GeometricNavigator(nn.Module):"""Maps inputs to geometric regions in 4D space - OPTIMIZED with vectorized operations."""def __init__(self, input_dim: int, num_regions: int, config: GeometricConfig, num_heads: int = 1):super().__init__()self.input_dim = input_dimself.num_regions = num_regionsself.config = configself.num_heads = num_heads# Create separate parameters for each head if num_heads > 1if num_heads > 1:self.to_nav = nn.Parameter(torch.randn(num_heads, input_dim, 4) * 0.02)self.vertex_w = nn.Parameter(torch.zeros(num_heads, num_regions, 5))else:self.to_nav = nn.Linear(input_dim, 4, bias=False)self.vertex_w = nn.Parameter(torch.zeros(num_regions, 5))# Pre-compute phase tensors for vectorizationself.register_buffer('phase_cos', torch.cos(torch.tensor(config.phases, dtype=torch.float32)))self.register_buffer('phase_sin', torch.sin(torch.tensor(config.phases, dtype=torch.float32)))# Initialize geometry after module is createdself.register_parameter('D', None)self.register_parameter('S', None)def _lazy_init_geometry(self, device):"""Initialize geometry on first forward pass."""if self.D is not None:returnbase = perfect_4simplex(device)if self.num_heads > 1:31 unmodified linesdef navigate(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:"""Navigate inputs through geometric space - OPTIMIZED with vectorized phase computation."""self._lazy_init_geometry(x.device)if self.num_heads > 1:# Batched navigation for multiple headsBT, H, head_dim = x.shape8 unmodified liness_disp = -softmin_over_last(d_disp, self.config.softmin_tau)# OPTIMIZED: Vectorized phase computation (no loop)cos_phases = self.phase_cos.to(x.device).view(-1, 1, 1, 1, 1)sin_phases = self.phase_sin.to(x.device).view(-1, 1, 1, 1, 1)# Compute all phase variants at once [phases, H, regions, 5, 4]Vt_all = cos_phases * self.D.unsqueeze(0) + sin_phases * self.S.unsqueeze(0)26 unmodified linesw = F.softmax(self.vertex_w, dim=1)# OPTIMIZED: Vectorized phase computation for single headcos_phases = self.phase_cos.to(x.device).view(-1, 1, 1, 1)sin_phases = self.phase_sin.to(x.device).view(-1, 1, 1, 1)Vt_all = cos_phases * self.D.unsqueeze(0) + sin_phases * self.S.unsqueeze(0)w_expanded = w.unsqueeze(0).unsqueeze(-1)16 unmodified linesreturn {'scores': scores, 'diagnostics': diagnostics}class GeometricAttention(nn.Module):"""Multi-head geometric attention with Q-K alignment - OPTIMIZED with batched processing."""def __init__(self, dim: int, num_heads: int = 8, num_regions: Optional[int] = None,config: Optional[GeometricConfig] = None, dropout: float = 0.0):super().__init__()self.dim = dimself.num_heads = num_heads7 unmodified linesself.config = configself.to_qkv = nn.Linear(dim, dim * 3, bias=False)# Create batched navigatorsself.q_navigator = GeometricNavigator(self.head_dim, num_regions, config, num_heads=num_heads)self.k_navigator = GeometricNavigator(self.head_dim, num_regions, config, num_heads=num_heads)self.out_proj = nn.Linear(dim, dim)self.dropout = nn.Dropout(dropout)99 unmodified linesdef forward(self, batch_size: int, class_indices: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:"""Generate CLS tokens for batch."""if class_indices is not None and class_indices.shape[0] == batch_size:vertex_cls_vocab = self.class_pentachora[class_indices]else:vertex_cls_vocab = self.class_pentachora.mean(dim=0, keepdim=True)vertex_cls_vocab = vertex_cls_vocab.expand(batch_size, -1, -1)# Project from vocabulary dimension to model dimension10 unmodified linesdef get_class_prototypes(self) -> torch.Tensor:"""Get class prototypes in model dimension."""pentachora_model = self.vocab_to_model(self.class_pentachora)weights = F.softmax(self.vertex_weights, dim=0)prototypes = torch.einsum('cvd,v->cd', pentachora_model, weights)return prototypes84 unmodified lines"""ViT block with geometric attention for structured layers."""def __init__(self, dim: int, heads: int = 8, mlp_ratio: float = 4.0,use_mesh: bool = True, dropout: float = 0., attn_dropout: float = 0.,drop_path: float = 0.):super().__init__()self.norm1 = nn.LayerNorm(dim)4 unmodified linesnum_heads=heads,num_regions=min(dim // heads, 16),config=GeometricConfig(),dropout=attn_dropout)else:# Standard multi-head attention for later layers107 unmodified linesuse_mesh=(cfg.use_mesh_attention and i < cfg.preserve_structure_until_layer),dropout=cfg.dropout_rate,attn_dropout=cfg.dropout_rate,drop_path=dpr[i])for i in range(cfg.depth)])165 unmodified linesvertex_flat = features['vertex_cls'].reshape(B, -1)aux_logits = self.head_aux(vertex_flat)# Geometric alignment scores - use class_pentachora directlygeometric_alignments = self.geometric_proj(features['patches'],self.cls_tokens.class_pentachora # Back to original)return {62 unmodified linesdropout_rate=0.0, drop_path_rate=0.0),'pentachora_shock_xs_64d': PentachoraConfig(dim=64, depth=2, heads=8, mlp_ratio=4.0,preserve_structure_until_layer=4,dropout_rate=0.0, drop_path_rate=0.0),'pentachora_shock_xs_128d': PentachoraConfig(dim=128, depth=2, heads=8, mlp_ratio=4.0,preserve_structure_until_layer=4,dropout_rate=0.0, drop_path_rate=0.0),'pentachora_shock_xs_256d': PentachoraConfig(dim=256, depth=2, heads=8, mlp_ratio=4.0,preserve_structure_until_layer=4,dropout_rate=0.0, drop_path_rate=0.0),'pentachora_shock_xs_512d': PentachoraConfig(143 unmodified linesdef test_model():"""Test model creation and forward pass."""print("Testing Optimized PentachoraViT Model")print("=" * 50)# Test different variants51 unmodified linesif __name__ == "__main__":# Run tests#test_model()# Example: Create model for A100 trainingprint("\nExample: Creating optimized model for A100 training")model = pentachora_shock_xs_256d(img_size=32,num_classes=100,2 unmodified linesdrop_path_rate=0.0)# Move model to CUDA first if availableif torch.cuda.is_available():model = model.cuda()print("Model moved to CUDA")# Now try torch.compile (PyTorch 2.0+)# Model reformatted to allow eager compiling, speeds along training substantially.if hasattr(torch, 'compile'):print("Compiling model with torch.compile...")try:model = torch.compile(model, backend="eager")print("Model compiled successfully")except Exception as e:print(f"Compilation warning: {e}")print("Continuing without compilation - vectorized ops will still provide speedup")# Get parameter groups for optimizerparam_groups = get_parameter_groups(model, weight_decay=0.05)print(f"Number of parameter groups: {len(param_groups)}")# Example batch - FULL PRECISIONimages = torch.randn(4, 3, 32, 32)targets = torch.randint(0, 100, (4,))if torch.cuda.is_available():images = images.cuda()targets = targets.cuda()# Forward pass in FULL PRECISION (no autocast)outputs = model(images)# Compute losscriterion = PentachoraLoss(aux_weight=0.3, geo_weight=0.1)loss = criterion(outputs, targets)print(f"Training loss (full precision): {loss.item():.4f}")print("\nModel ready for full precision A100 training!")print("Eager initialization ensures all parameters are created upfront")123456734 unmodified lines4243444546474819 unmodified lines686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810931 unmodified lines1411421431441451468 unmodified lines15515615715815916016116226 unmodified lines18919019119219319419519616 unmodified lines2132142152162172182192202212227 unmodified lines23023123223323423523623723899 unmodified lines33833934034134234334434534634734834935010 unmodified lines36136236336436536636736884 unmodified lines4534544554564574584594 unmodified lines464465466467468469470471107 unmodified lines579580581582583584585586165 unmodified lines75275375475575675775875976076162 unmodified lines824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855143 unmodified lines99910001001100210031004100551 unmodified lines10571058105910601061106210631064106510662 unmodified lines10691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091"""PentachoraViT: Vision Transformer with Pentachoron Geometric StructureEnhanced with Geometric Attention for improved head cohesion and generalizationFIXED: All parameters initialized at module creation time (no lazy init)"""import torch34 unmodified linesreturn (self.img_size // self.patch_size) ** 2# ============================================# GEOMETRIC ATTENTION COMPONENTS (FIXED INIT)# ============================================def perfect_4simplex(device):19 unmodified linesfuse_alpha: float = 0.7phases: Tuple[float, ...] = (0.0, math.pi/2, math.pi, 3*math.pi/2)jitter: float = 0.02shift: float = 0.71rotate_cycle: int = 11use_phase_variance: bool = Falsegeometry_type: str = "pentachoron"class GeometricNavigator(nn.Module):"""Maps inputs to geometric regions in 4D space - FIXED with immediate initialization."""def __init__(self, input_dim: int, num_regions: int, config: GeometricConfig, num_heads: int = 1, device=None):super().__init__()self.input_dim = input_dimself.num_regions = num_regionsself.config = configself.num_heads = num_heads# Use CPU by default if device not specifiedif device is None:device = torch.device('cpu')# Create separate parameters for each head if num_heads > 1if num_heads > 1:self.to_nav = nn.Parameter(torch.randn(num_heads, input_dim, 4, device=device) * 0.02)self.vertex_w = nn.Parameter(torch.zeros(num_heads, num_regions, 5, device=device))else:self.to_nav = nn.Linear(input_dim, 4, bias=False)self.vertex_w = nn.Parameter(torch.zeros(num_regions, 5, device=device))# Pre-compute phase tensors for vectorizationself.register_buffer('phase_cos', torch.cos(torch.tensor(config.phases, dtype=torch.float32, device=device)))self.register_buffer('phase_sin', torch.sin(torch.tensor(config.phases, dtype=torch.float32, device=device)))# Initialize geometry immediately at creation timeself._init_geometry(device)def _init_geometry(self, device):"""Initialize geometry at module creation time."""base = perfect_4simplex(device)if self.num_heads > 1:31 unmodified linesdef navigate(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:"""Navigate inputs through geometric space - OPTIMIZED with vectorized phase computation."""if self.num_heads > 1:# Batched navigation for multiple headsBT, H, head_dim = x.shape8 unmodified liness_disp = -softmin_over_last(d_disp, self.config.softmin_tau)# OPTIMIZED: Vectorized phase computation (no loop)cos_phases = self.phase_cos.view(-1, 1, 1, 1, 1)sin_phases = self.phase_sin.view(-1, 1, 1, 1, 1)# Compute all phase variants at once [phases, H, regions, 5, 4]Vt_all = cos_phases * self.D.unsqueeze(0) + sin_phases * self.S.unsqueeze(0)26 unmodified linesw = F.softmax(self.vertex_w, dim=1)# OPTIMIZED: Vectorized phase computation for single headcos_phases = self.phase_cos.view(-1, 1, 1, 1)sin_phases = self.phase_sin.view(-1, 1, 1, 1)Vt_all = cos_phases * self.D.unsqueeze(0) + sin_phases * self.S.unsqueeze(0)w_expanded = w.unsqueeze(0).unsqueeze(-1)16 unmodified linesreturn {'scores': scores, 'diagnostics': diagnostics}class GeometricAttention(nn.Module):"""Multi-head geometric attention with Q-K alignment - FIXED with proper device handling."""def __init__(self, dim: int, num_heads: int = 8, num_regions: Optional[int] = None,config: Optional[GeometricConfig] = None, dropout: float = 0.0, device=None):super().__init__()self.dim = dimself.num_heads = num_heads7 unmodified linesself.config = configself.to_qkv = nn.Linear(dim, dim * 3, bias=False)# Create batched navigators with deviceself.q_navigator = GeometricNavigator(self.head_dim, num_regions, config, num_heads=num_heads, device=device)self.k_navigator = GeometricNavigator(self.head_dim, num_regions, config, num_heads=num_heads, device=device)self.out_proj = nn.Linear(dim, dim)self.dropout = nn.Dropout(dropout)99 unmodified linesdef forward(self, batch_size: int, class_indices: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:"""Generate CLS tokens for batch."""# Get class-specific pentachoraclass_pentachora = self.class_pentachora # This is now a computed propertyif class_indices is not None and class_indices.shape[0] == batch_size:vertex_cls_vocab = class_pentachora[class_indices]else:vertex_cls_vocab = class_pentachora.mean(dim=0, keepdim=True)vertex_cls_vocab = vertex_cls_vocab.expand(batch_size, -1, -1)# Project from vocabulary dimension to model dimension10 unmodified linesdef get_class_prototypes(self) -> torch.Tensor:"""Get class prototypes in model dimension."""class_pentachora = self.class_pentachora # Get computed pentachorapentachora_model = self.vocab_to_model(class_pentachora)weights = F.softmax(self.vertex_weights, dim=0)prototypes = torch.einsum('cvd,v->cd', pentachora_model, weights)return prototypes84 unmodified lines"""ViT block with geometric attention for structured layers."""def __init__(self, dim: int, heads: int = 8, mlp_ratio: float = 4.0,use_mesh: bool = True, dropout: float = 0., attn_dropout: float = 0.,drop_path: float = 0., device=None):super().__init__()self.norm1 = nn.LayerNorm(dim)4 unmodified linesnum_heads=heads,num_regions=min(dim // heads, 16),config=GeometricConfig(),dropout=attn_dropout,device=device)else:# Standard multi-head attention for later layers107 unmodified linesuse_mesh=(cfg.use_mesh_attention and i < cfg.preserve_structure_until_layer),dropout=cfg.dropout_rate,attn_dropout=cfg.dropout_rate,drop_path=dpr[i],device=torch.device('cpu') # Initialize on CPU, will be moved later)for i in range(cfg.depth)])165 unmodified linesvertex_flat = features['vertex_cls'].reshape(B, -1)aux_logits = self.head_aux(vertex_flat)# Geometric alignment scoresgeometric_alignments = self.geometric_proj(features['patches'],self.cls_tokens.class_pentachora)return {62 unmodified linesdropout_rate=0.0, drop_path_rate=0.0),'pentachora_shock_xs_64d': PentachoraConfig(dim=64, depth=2, heads=8, mlp_ratio=1.0,preserve_structure_until_layer=4,dropout_rate=0.0, drop_path_rate=0.0),'pentachora_shock_xs_128d': PentachoraConfig(dim=128, depth=2, heads=8, mlp_ratio=2.0,preserve_structure_until_layer=4,vocab_dim=256,dropout_rate=0.0, drop_path_rate=0.0),'vit_pixie_256_patch4': PentachoraConfig(dim=256, depth=10, heads=16, mlp_ratio=1.0,preserve_structure_until_layer=10,vocab_dim=256, patch_size=4,dropout_rate=0.0, drop_path_rate=0.0),'vit_pixie_256_patch2': PentachoraConfig(dim=256, depth=10, heads=16, mlp_ratio=1.0,preserve_structure_until_layer=10,vocab_dim=256, patch_size=2,dropout_rate=0.0, drop_path_rate=0.0),'pentachora_shock_xs_256d': PentachoraConfig(dim=256, depth=2, heads=8, mlp_ratio=4.0,preserve_structure_until_layer=4,vocab_dim=128,dropout_rate=0.0, drop_path_rate=0.0),'pentachora_shock_xs_512d': PentachoraConfig(143 unmodified linesdef test_model():"""Test model creation and forward pass."""print("Testing Fixed PentachoraViT Model")print("=" * 50)# Test different variants51 unmodified linesif __name__ == "__main__":# Run teststest_model()# Example: Create model for trainingprint("\nExample: Creating model with proper initialization")model = pentachora_shock_xs_256d(img_size=32,num_classes=100,2 unmodified linesdrop_path_rate=0.0)# All parameters are initialized immediatelyprint(f"Model has {count_parameters(model)['total']:,} parameters")print("All geometric parameters initialized at creation time")# Move model to CUDA if availableif torch.cuda.is_available():model = model.cuda()print("Model moved to CUDA")# Now torch.compile should work without issuesif hasattr(torch, 'compile'):print("Compiling model with torch.compile...")try:model = torch.compile(model)print("✓ Model compiled successfully")except Exception as e:print(f"Compilation warning: {e}")print("Continuing without compilation")print("\nModel ready for training with all parameters properly initialized!")
penta_vit_model_v1.py+72-74