-
Notifications
You must be signed in to change notification settings - Fork 330
Add Moondream architecture skeleton #2553
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BharathC0
wants to merge
2
commits into
keras-team:master
Choose a base branch
from
BharathC0:moondream-architecture
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| from keras_hub.src.models.moondream.moondream_backbone import MoondreamBackbone | ||
| from keras_hub.src.models.moondream.moondream_preprocessor import \ | ||
| MoondreamPreprocessor | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,68 @@ | ||
| import keras | ||
| from keras import ops | ||
|
|
||
| from keras_hub.src.api_export import keras_hub_export | ||
| from keras_hub.src.models.backbone import Backbone | ||
|
|
||
|
|
||
| @keras_hub_export("keras_hub.models.MoondreamBackbone") | ||
BharathC0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| class MoondreamBackbone(Backbone): | ||
| def __init__(self, vision_encoder, text_decoder, projection_dim=2048, **kwargs): | ||
BharathC0 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| super().__init__(**kwargs) | ||
|
|
||
| self.vision_encoder = vision_encoder | ||
| self.text_decoder = text_decoder | ||
|
|
||
| # The Connector | ||
| self.vision_projection = keras.layers.Dense( | ||
| projection_dim, name="vision_projection" | ||
| ) | ||
|
|
||
| def call(self, inputs): | ||
| images = inputs["images"] | ||
BharathC0 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| token_ids = inputs["token_ids"] | ||
| padding_mask = inputs["padding_mask"] | ||
|
|
||
| # 1. Image Features | ||
| image_features = self.vision_encoder(images) | ||
|
|
||
| # 2. Project | ||
| projected_images = self.vision_projection(image_features) | ||
|
|
||
| # 3. Text Embeddings | ||
| text_embeddings = self.text_decoder.get_input_embeddings(token_ids) | ||
|
|
||
| # 4. Concatenate | ||
| combined_embeddings = ops.concatenate( | ||
| [projected_images, text_embeddings], axis=1 | ||
| ) | ||
|
|
||
| # 5. Masking | ||
| batch_size = ops.shape(images)[0] | ||
| num_patches = ops.shape(projected_images)[1] | ||
|
|
||
| image_mask = ops.ones((batch_size, num_patches), dtype="bool") | ||
| combined_mask = ops.concatenate([image_mask, padding_mask], axis=1) | ||
BharathC0 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # 6. Decoder Pass | ||
| # Now compatible with our Subclass Mock Decoder | ||
| outputs = self.text_decoder( | ||
| inputs=None, | ||
| decoder_inputs_embeds=combined_embeddings, | ||
| padding_mask=combined_mask, | ||
| ) | ||
|
|
||
| return outputs | ||
|
|
||
| def get_config(self): | ||
| config = super().get_config() | ||
| config.update( | ||
| { | ||
| "vision_encoder": keras.saving.serialize_keras_object( | ||
| self.vision_encoder | ||
| ), | ||
| "text_decoder": keras.saving.serialize_keras_object(self.text_decoder), | ||
| "projection_dim": self.vision_projection.units, | ||
| } | ||
BharathC0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| ) | ||
| return config | ||
BharathC0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import keras | ||
|
|
||
| from keras_hub.src.api_export import keras_hub_export | ||
| from keras_hub.src.models.causal_lm import CausalLM | ||
| from keras_hub.src.models.moondream.moondream_backbone import MoondreamBackbone | ||
| from keras_hub.src.models.moondream.moondream_preprocessor import \ | ||
| MoondreamPreprocessor | ||
|
|
||
|
|
||
| @keras_hub_export("keras_hub.models.MoondreamCausalLM") | ||
BharathC0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| class MoondreamCausalLM(CausalLM): | ||
| backbone_cls = MoondreamBackbone | ||
| preprocessor_cls = MoondreamPreprocessor | ||
|
|
||
| def __init__( | ||
BharathC0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| self, | ||
| backbone, | ||
| preprocessor=None, | ||
| **kwargs, | ||
| ): | ||
| inputs = getattr(backbone, "input", None) | ||
|
|
||
| super().__init__(**kwargs) | ||
|
|
||
| # Manually set the attributes | ||
| self.backbone = backbone | ||
| self.preprocessor = preprocessor | ||
BharathC0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # Set tensor spec if available | ||
| if inputs is not None: | ||
| self.input_tensor_spec = inputs | ||
|
|
||
| def call(self, inputs, training=False): | ||
| if self.backbone is None: | ||
| raise ValueError("Backbone not initialized") | ||
| x = self.backbone(inputs) | ||
| return x | ||
BharathC0 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| import keras | ||
|
|
||
| from keras_hub.src.api_export import keras_hub_export | ||
| from keras_hub.src.models.causal_lm_preprocessor import CausalLMPreprocessor | ||
|
|
||
|
|
||
| @keras_hub_export("keras_hub.models.MoondreamPreprocessor") | ||
BharathC0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| class MoondreamPreprocessor(CausalLMPreprocessor): | ||
BharathC0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| def __init__( | ||
| self, | ||
| tokenizer, | ||
| image_converter=None, | ||
| sequence_length=1024, | ||
| add_start_token=True, | ||
| add_end_token=True, | ||
| **kwargs, | ||
| ): | ||
BharathC0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| super().__init__( | ||
| tokenizer=tokenizer, | ||
| sequence_length=sequence_length, | ||
| add_start_token=add_start_token, | ||
| add_end_token=add_end_token, | ||
| **kwargs, | ||
| ) | ||
| self.image_converter = image_converter | ||
|
|
||
| def call(self, x, y=None, sample_weight=None): | ||
| output = super().call(x, y, sample_weight) | ||
|
|
||
| # 1. Identify the input dictionary from the output | ||
| # If output is a tuple (x, y, sw), the first element is the input dict. | ||
| if isinstance(output, tuple): | ||
| x_out = output[0] | ||
| else: | ||
| x_out = output | ||
|
|
||
| # 2. Type Guard for Pylance | ||
| # We explicitly check if x_out IS a dictionary. | ||
| # This stops Pylance from thinking it might be a Tuple/List. | ||
| if isinstance(x_out, dict) and isinstance(x, dict) and "images" in x: | ||
| images = x["images"] | ||
| if self.image_converter: | ||
| images = self.image_converter(images) | ||
| x_out["images"] = images | ||
|
|
||
| return output | ||
BharathC0 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| def get_config(self): | ||
| config = super().get_config() | ||
| config.update( | ||
| { | ||
| "image_converter": keras.saving.serialize_keras_object( | ||
| self.image_converter | ||
| ), | ||
| } | ||
| ) | ||
| return config | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.