Frankenstein-Labs commited on
Commit
a82e5d8
·
1 Parent(s): 66e3394

feat(cortex-ai): add native vision fusion prototype

Browse files
README.md CHANGED
@@ -403,6 +403,22 @@ is not a documented configuration.
403
 
404
  ---
405
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
406
  ## First executable vision path
407
 
408
  The first operational step is now available through `cortex_ai.vision.bridge`. It uses an
 
403
 
404
  ---
405
 
406
+ ## Native fusion prototype status
407
+
408
+ A real tensor-level native fusion prototype is now implemented in `cortex_ai/vision/native.py`:
409
+
410
+ ```text
411
+ IMAGE → VISION ENCODER → IMAGE EMBEDDINGS → PROJECTOR
412
+ → PREFIX MULTIMODAL FUSION → inputs_embeds → LANGUAGE CORE
413
+ ```
414
+
415
+ `NativeVisionFusion` executes this path with any compatible language core that exposes
416
+ `get_input_embeddings()` and accepts `inputs_embeds`. A minimal test core verifies the actual
417
+ embedding shapes, prefix concatenation and attention mask. This is a **functional prototype**, not
418
+ a claim that the 1.65T DeepSeek-V4 checkpoint is already natively multimodal: that checkpoint has
419
+ not been modified, and its runtime compatibility with this path remains unverified until a suitable
420
+ full inference environment is available. The BLIP caption bridge remains the functional fallback.
421
+
422
  ## First executable vision path
423
 
424
  The first operational step is now available through `cortex_ai.vision.bridge`. It uses an
cortex_ai/vision/__init__.py CHANGED
@@ -1,9 +1,16 @@
1
  from .bridge import CortexVisionBridge, TransformersImageCaptioner, VisionObservation, build_default_bridge
 
 
 
 
2
 
3
  __all__ = [
4
  "CortexVisionBridge", "TransformersImageCaptioner", "VisionObservation", "build_default_bridge",
5
  ]
6
 
 
 
 
7
  try:
8
  from .core import (
9
  ImageProcessor,
 
1
  from .bridge import CortexVisionBridge, TransformersImageCaptioner, VisionObservation, build_default_bridge
2
+ try:
3
+ from .native import NativeFusionResult, NativeVisionFusion, build_native_fusion
4
+ except ImportError:
5
+ pass
6
 
7
  __all__ = [
8
  "CortexVisionBridge", "TransformersImageCaptioner", "VisionObservation", "build_default_bridge",
9
  ]
10
 
11
+ if "NativeVisionFusion" in globals():
12
+ __all__ += ["NativeFusionResult", "NativeVisionFusion", "build_native_fusion"]
13
+
14
  try:
15
  from .core import (
16
  ImageProcessor,
cortex_ai/vision/config.json CHANGED
@@ -7,6 +7,12 @@
7
  "requires": ["torch", "transformers", "Pillow"],
8
  "status": "implemented, requires external model download"
9
  },
 
 
 
 
 
 
10
  "core_model_unchanged": true,
11
  "vision_encoder": {
12
  "interface": "VisionEncoder",
 
7
  "requires": ["torch", "transformers", "Pillow"],
8
  "status": "implemented, requires external model download"
9
  },
10
+ "native_fusion_prototype": {
11
+ "implementation": "cortex_ai.vision.native.NativeVisionFusion",
12
+ "path": "image -> vision embeddings -> projector -> inputs_embeds -> compatible language core",
13
+ "status": "functional on the minimal test core; not connected to the 1.65T DeepSeek checkpoint",
14
+ "compatibility_requirement": "language core must expose get_input_embeddings() and accept inputs_embeds"
15
+ },
16
  "core_model_unchanged": true,
17
  "vision_encoder": {
18
  "interface": "VisionEncoder",
cortex_ai/vision/native.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Native image-embedding fusion path for CORTEX-compatible language cores.
2
+
3
+ This module performs the real tensor path IMAGE -> encoder -> projector ->
4
+ inputs_embeds -> language core. It is intentionally model-agnostic: the
5
+ existing 1.65T DeepSeek checkpoint is not modified, and a core is only
6
+ accepted when its runtime exposes the required inputs_embeds contract.
7
+ """
8
+
9
+ from dataclasses import dataclass
10
+ from typing import Any, Callable
11
+
12
+ import torch
13
+ from torch import Tensor, nn
14
+
15
+ from .core import PrefixFusion, VisionConfig, VisionProjector
16
+
17
+
18
+ @dataclass(frozen=True)
19
+ class NativeFusionResult:
20
+ """Output of a native fusion forward pass."""
21
+
22
+ outputs: Any
23
+ image_token_count: int
24
+ text_token_count: int
25
+
26
+
27
+ class NativeVisionFusion(nn.Module):
28
+ """Fuse projected image tokens into a language core via ``inputs_embeds``."""
29
+
30
+ def __init__(
31
+ self,
32
+ vision_encoder: Callable[..., Any],
33
+ config: VisionConfig,
34
+ core: nn.Module,
35
+ image_processor: Callable[..., Any] | None = None,
36
+ ) -> None:
37
+ super().__init__()
38
+ self.vision_encoder = vision_encoder
39
+ self.projector = VisionProjector(config)
40
+ self.core = core
41
+ self.image_processor = image_processor
42
+ self.fusion = PrefixFusion()
43
+
44
+ def encode_image(self, image: Any) -> Tensor:
45
+ model_input = (
46
+ self.image_processor(image, return_tensors="pt")
47
+ if self.image_processor is not None
48
+ else image
49
+ )
50
+ encoded = self.vision_encoder(**model_input) if isinstance(model_input, dict) else self.vision_encoder(model_input)
51
+ if hasattr(encoded, "last_hidden_state"):
52
+ encoded = encoded.last_hidden_state
53
+ if not isinstance(encoded, Tensor) or encoded.ndim != 3:
54
+ raise ValueError("vision_encoder must return [batch, image_tokens, vision_hidden_size]")
55
+ return self.projector(encoded)
56
+
57
+ def build_inputs_embeds(self, input_ids: Tensor, image: Any) -> tuple[Tensor, Tensor]:
58
+ if input_ids.ndim != 2:
59
+ raise ValueError("input_ids must have shape [batch, text_tokens]")
60
+ image_embeds = self.encode_image(image)
61
+ token_embedding = getattr(self.core, "get_input_embeddings", None)
62
+ if token_embedding is None or not callable(token_embedding):
63
+ raise TypeError("core must expose get_input_embeddings() for native fusion")
64
+ text_embeds = token_embedding()(input_ids)
65
+ fused = self.fusion.fuse(text_embeds, image_embeds)
66
+ attention_mask = torch.ones(fused.shape[:2], dtype=torch.long, device=fused.device)
67
+ return fused, attention_mask
68
+
69
+ def forward(self, input_ids: Tensor, image: Any, **kwargs: Any) -> NativeFusionResult:
70
+ inputs_embeds, attention_mask = self.build_inputs_embeds(input_ids, image)
71
+ try:
72
+ outputs = self.core(inputs_embeds=inputs_embeds, attention_mask=attention_mask, **kwargs)
73
+ except TypeError as exc:
74
+ raise TypeError(
75
+ "core does not accept inputs_embeds; native fusion cannot be claimed for this core"
76
+ ) from exc
77
+ return NativeFusionResult(outputs, inputs_embeds.shape[1] - input_ids.shape[1], input_ids.shape[1])
78
+
79
+
80
+ def build_native_fusion(
81
+ vision_encoder: Callable[..., Any],
82
+ core: nn.Module,
83
+ vision_hidden_size: int,
84
+ cortex_hidden_size: int,
85
+ image_processor: Callable[..., Any] | None = None,
86
+ ) -> NativeVisionFusion:
87
+ """Construct the native path around externally supplied encoder and core modules."""
88
+ config = VisionConfig(vision_hidden_size=vision_hidden_size, cortex_hidden_size=cortex_hidden_size)
89
+ return NativeVisionFusion(vision_encoder, config, core, image_processor)
tests/test_native_fusion.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+ from cortex_ai.vision.native import build_native_fusion
5
+
6
+
7
+ class TinyCore(nn.Module):
8
+ def __init__(self):
9
+ super().__init__()
10
+ self.embedding = nn.Embedding(32, 8)
11
+ self.last_inputs_embeds = None
12
+
13
+ def get_input_embeddings(self):
14
+ return self.embedding
15
+
16
+ def forward(self, inputs_embeds, attention_mask):
17
+ self.last_inputs_embeds = inputs_embeds
18
+ return {"hidden_states": inputs_embeds, "attention_mask": attention_mask}
19
+
20
+
21
+ class TinyVisionEncoder(nn.Module):
22
+ def forward(self, image):
23
+ return torch.ones(image.shape[0], 3, 4)
24
+
25
+
26
+ def test_native_image_embedding_fusion_executes_real_tensor_path():
27
+ core = TinyCore()
28
+ fusion = build_native_fusion(TinyVisionEncoder(), core, vision_hidden_size=4, cortex_hidden_size=8)
29
+ result = fusion(input_ids=torch.tensor([[1, 2]]), image=torch.zeros(1, 3, 16, 16))
30
+ assert result.image_token_count == 3
31
+ assert result.text_token_count == 2
32
+ assert core.last_inputs_embeds.shape == (1, 5, 8)
33
+ assert result.outputs["attention_mask"].shape == (1, 5)