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61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
"""
Ekalavya Multi-Modal - Vision + Audio + Video + Text
Complete multi-modal AI that can see, hear, read, and understand
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Tuple, List, Union
import math


class VisionEncoder(nn.Module):
    """
    Vision Encoder - Processes images and video frames
    Converts images to embeddings that can be understood by the language model
    """
    def __init__(self, image_size=224, patch_size=16, embed_dim=1024):
        super().__init__()
        self.image_size = image_size
        self.patch_size = patch_size
        self.num_patches = (image_size // patch_size) ** 2
        
        # Patch embedding
        self.patch_embed = nn.Conv2d(
            in_channels=3,
            out_channels=embed_dim,
            kernel_size=patch_size,
            stride=patch_size
        )
        
        # Position embedding
        self.pos_embed = nn.Parameter(torch.zeros(1, self.num_patches + 1, embed_dim))
        self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
        
        # Transformer layers for vision
        self.layers = nn.ModuleList([
            VisionTransformerBlock(embed_dim) for _ in range(12)
        ])
        
        self.norm = nn.LayerNorm(embed_dim)
        
    def forward(self, x):
        """
        Args:
            x: Image tensor [batch, channels, height, width]
        Returns:
            Image embeddings [batch, num_patches+1, embed_dim]
        """
        batch_size = x.shape[0]
        
        # Patch embedding
        x = self.patch_embed(x)  # [B, embed_dim, H/P, W/P]
        x = x.flatten(2).transpose(1, 2)  # [B, num_patches, embed_dim]
        
        # Add CLS token
        cls_tokens = self.cls_token.expand(batch_size, -1, -1)
        x = torch.cat([cls_tokens, x], dim=1)  # [B, num_patches+1, embed_dim]
        
        # Add position embeddings
        x = x + self.pos_embed
        
        # Transformer layers
        for layer in self.layers:
            x = layer(x)
        
        x = self.norm(x)
        return x


class VisionTransformerBlock(nn.Module):
    """Transformer block for vision encoder"""
    def __init__(self, dim, num_heads=16, mlp_ratio=4.0):
        super().__init__()
        self.norm1 = nn.LayerNorm(dim)
        self.attn = nn.MultiheadAttention(dim, num_heads, batch_first=True)
        self.norm2 = nn.LayerNorm(dim)
        self.mlp = nn.Sequential(
            nn.Linear(dim, int(dim * mlp_ratio)),
            nn.GELU(),
            nn.Linear(int(dim * mlp_ratio), dim)
        )
        
    def forward(self, x):
        x = x + self.attn(self.norm1(x), self.norm1(x), self.norm1(x))[0]
        x = x + self.mlp(self.norm2(x))
        return x


class AudioEncoder(nn.Module):
    """
    Audio Encoder - Processes speech and audio
    Converts audio waveforms to embeddings
    """
    def __init__(self, embed_dim=1024, sample_rate=16000):
        super().__init__()
        self.sample_rate = sample_rate
        
        # Mel spectrogram conversion
        self.mel_transform = nn.Sequential(
            nn.Conv1d(1, 64, kernel_size=400, stride=160),
            nn.GELU(),
            nn.Conv1d(64, 128, kernel_size=3, stride=2),
            nn.GELU(),
            nn.Conv1d(128, 256, kernel_size=3, stride=2),
            nn.GELU()
        )
        
        # Project to embedding dimension
        self.proj = nn.Linear(256, embed_dim)
        
        # Transformer layers for audio
        self.layers = nn.ModuleList([
            AudioTransformerBlock(embed_dim) for _ in range(6)
        ])
        
        self.norm = nn.LayerNorm(embed_dim)
        
    def forward(self, x):
        """
        Args:
            x: Audio waveform [batch, samples]
        Returns:
            Audio embeddings [batch, time_steps, embed_dim]
        """
        # Add channel dimension
        x = x.unsqueeze(1)  # [B, 1, samples]
        
        # Convert to features
        x = self.mel_transform(x)  # [B, 256, time_steps]
        x = x.transpose(1, 2)  # [B, time_steps, 256]
        
        # Project to embedding dimension
        x = self.proj(x)  # [B, time_steps, embed_dim]
        
        # Transformer layers
        for layer in self.layers:
            x = layer(x)
        
        x = self.norm(x)
        return x


class AudioTransformerBlock(nn.Module):
    """Transformer block for audio encoder"""
    def __init__(self, dim, num_heads=16, mlp_ratio=4.0):
        super().__init__()
        self.norm1 = nn.LayerNorm(dim)
        self.attn = nn.MultiheadAttention(dim, num_heads, batch_first=True)
        self.norm2 = nn.LayerNorm(dim)
        self.mlp = nn.Sequential(
            nn.Linear(dim, int(dim * mlp_ratio)),
            nn.GELU(),
            nn.Linear(int(dim * mlp_ratio), dim)
        )
        
    def forward(self, x):
        x = x + self.attn(self.norm1(x), self.norm1(x), self.norm1(x))[0]
        x = x + self.mlp(self.norm2(x))
        return x


class MultiModalProjector(nn.Module):
    """
    Projects vision and audio embeddings to language model space
    """
    def __init__(self, vision_dim=1024, audio_dim=1024, llm_dim=2048):
        super().__init__()
        self.vision_proj = nn.Sequential(
            nn.Linear(vision_dim, llm_dim),
            nn.GELU(),
            nn.Linear(llm_dim, llm_dim)
        )
        self.audio_proj = nn.Sequential(
            nn.Linear(audio_dim, llm_dim),
            nn.GELU(),
            nn.Linear(llm_dim, llm_dim)
        )
        
    def forward(self, vision_embeds=None, audio_embeds=None):
        """
        Project multi-modal embeddings to LLM space
        """
        projected = {}
        if vision_embeds is not None:
            projected['vision'] = self.vision_proj(vision_embeds)
        if audio_embeds is not None:
            projected['audio'] = self.audio_proj(audio_embeds)
        return projected


class EkalavyaMultiModal(nn.Module):
    """
    Ekalavya Multi-Modal - Complete multi-modal AI
    
    Can process:
    - Text (language model)
    - Images (vision encoder)
    - Videos (multiple frames)
    - Audio/Voice (audio encoder)
    
    All modalities are fused and understood together
    """
    def __init__(
        self,
        llm_dim=2048,
        vision_dim=1024,
        audio_dim=1024,
        image_size=224,
        patch_size=16
    ):
        super().__init__()
        
        # Vision encoder
        self.vision_encoder = VisionEncoder(image_size, patch_size, vision_dim)
        
        # Audio encoder
        self.audio_encoder = AudioEncoder(audio_dim)
        
        # Multi-modal projector
        self.projector = MultiModalProjector(vision_dim, audio_dim, llm_dim)
        
        # Language model (simplified for demo)
        self.llm_dim = llm_dim
        self.text_embed = nn.Embedding(32000, llm_dim)
        
        # Fusion layers
        self.fusion = nn.ModuleList([
            FusionLayer(llm_dim) for _ in range(8)
        ])
        
        # Output head
        self.output_head = nn.Linear(llm_dim, 32000)
        
    def forward(
        self,
        text_tokens=None,
        image=None,
        audio=None,
        video_frames=None
    ):
        """
        Process multi-modal input
        
        Args:
            text_tokens: Text token IDs [batch, seq_len]
            image: Image tensor [batch, 3, height, width]
            audio: Audio waveform [batch, samples]
            video_frames: Video frames [batch, num_frames, 3, height, width]
        
        Returns:
            Fused multi-modal embeddings
        """
        batch_size = text_tokens.shape[0] if text_tokens is not None else 1
        embeddings = []
        
        # Process text
        if text_tokens is not None:
            text_embeds = self.text_embed(text_tokens)
            embeddings.append(text_embeds)
        
        # Process image
        if image is not None:
            vision_embeds = self.vision_encoder(image)
            vision_projected = self.projector(vision_embeds=vision_embeds)['vision']
            embeddings.append(vision_projected)
        
        # Process video (multiple frames)
        if video_frames is not None:
            num_frames = video_frames.shape[1]
            frame_embeds = []
            for i in range(num_frames):
                frame = video_frames[:, i]  # [B, 3, H, W]
                frame_embed = self.vision_encoder(frame)
                frame_embeds.append(frame_embed)
            # Average frame embeddings
            video_embeds = torch.stack(frame_embeds, dim=1).mean(dim=1)
            video_projected = self.projector(vision_embeds=video_embeds)['vision']
            embeddings.append(video_projected)
        
        # Process audio
        if audio is not None:
            audio_embeds = self.audio_encoder(audio)
            audio_projected = self.projector(audio_embeds=audio_embeds)['audio']
            embeddings.append(audio_projected)
        
        # Concatenate all embeddings
        if embeddings:
            combined = torch.cat(embeddings, dim=1)
            
            # Fusion layers
            for layer in self.fusion:
                combined = layer(combined)
            
            # Output
            logits = self.output_head(combined)
            return logits
        
        return None
    
    def generate_response(self, text_prompt, image=None, audio=None, video=None):
        """
        Generate response from multi-modal input
        """
        # Process inputs
        logits = self.forward(
            text_tokens=text_prompt,
            image=image,
            audio=audio,
            video_frames=video
        )
        
        if logits is not None:
            # Get last token predictions
            next_token_logits = logits[:, -1, :]
            next_token = torch.argmax(next_token_logits, dim=-1)
            return next_token
        
        return None


class FusionLayer(nn.Module):
    """Fusion layer for combining multi-modal embeddings"""
    def __init__(self, dim, num_heads=16):
        super().__init__()
        self.norm = nn.LayerNorm(dim)
        self.attn = nn.MultiheadAttention(dim, num_heads, batch_first=True)
        self.mlp = nn.Sequential(
            nn.Linear(dim, dim * 4),
            nn.GELU(),
            nn.Linear(dim * 4, dim)
        )
        
    def forward(self, x):
        x = x + self.attn(self.norm(x), self.norm(x), self.norm(x))[0]
        x = x + self.mlp(self.norm(x))
        return x


# Utility functions for processing different modalities

def process_image(image_path_or_tensor):
    """
    Process image for the model
    """
    import torchvision.transforms as T
    
    if isinstance(image_path_or_tensor, str):
        from PIL import Image
        image = Image.open(image_path_or_tensor).convert('RGB')
    else:
        image = image_path_or_tensor
    
    # Resize and normalize
    transform = T.Compose([
        T.Resize((224, 224)),
        T.ToTensor(),
        T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
    ])
    
    if isinstance(image, torch.Tensor):
        return image
    return transform(image).unsqueeze(0)


def process_audio(audio_path_or_tensor, sample_rate=16000):
    """
    Process audio for the model
    """
    if isinstance(audio_path_or_tensor, str):
        import torchaudio
        waveform, sr = torchaudio.load(audio_path_or_tensor)
        if sr != sample_rate:
            resampler = torchaudio.transforms.Resample(sr, sample_rate)
            waveform = resampler(waveform)
        waveform = waveform.mean(dim=0)  # Convert to mono
    else:
        waveform = audio_path_or_tensor
    
    return waveform.unsqueeze(0)


def process_video(video_path, num_frames=8):
    """
    Extract frames from video
    """
    import cv2
    import numpy as np
    
    cap = cv2.VideoCapture(video_path)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    
    # Sample frames evenly
    frame_indices = np.linspace(0, total_frames-1, num_frames, dtype=int)
    
    frames = []
    for idx in frame_indices:
        cap.set(cv2.CAP_PROP_POS_FRAMES, idx)
        ret, frame = cap.read()
        if ret:
            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frames.append(process_image(frame))
    
    cap.release()
    
    return torch.cat(frames, dim=0).unsqueeze(0)  # [1, num_frames, 3, H, W]


if __name__ == '__main__':
    print("="*70)
    print("EKALAVYA MYTHOS MULTI-MODAL")
    print("="*70)
    print("\n🎯 Capabilities:")
    print("  ✅ Image Understanding")
    print("  ✅ Video Analysis")
    print("  ✅ Voice/Audio Processing")
    print("  ✅ Text Generation")
    print("  ✅ Multi-modal Fusion")
    
    # Create model
    model = EkalavyaMultiModal()
    print(f"\n📊 Model Parameters: {sum(p.numel() for p in model.parameters()):,}")
    
    # Test with dummy inputs
    batch_size = 2
    text_tokens = torch.randint(0, 32000, (batch_size, 10))
    image = torch.randn(batch_size, 3, 224, 224)
    audio = torch.randn(batch_size, 16000)  # 1 second of audio
    
    print("\n🧪 Testing multi-modal processing...")
    output = model(text_tokens=text_tokens, image=image, audio=audio)
    print(f"✅ Output shape: {output.shape}")
    
    print("\n" + "="*70)
    print("✅ Multi-modal model ready!")
    print("="*70)