akshit-g commited on
Commit
10581c4
·
1 Parent(s): af62a64

add : files

Browse files
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md CHANGED
@@ -4,8 +4,10 @@ emoji: 🏆
4
  colorFrom: indigo
5
  colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 5.7.1
8
- app_file: app.py
 
 
9
  pinned: false
10
  ---
11
 
 
4
  colorFrom: indigo
5
  colorTo: yellow
6
  sdk: gradio
7
+ # sdk_version: 5.7.1
8
+ sdk_version: 4.19.2
9
+ # app_file: app.py
10
+ app_file: webcam_gradio_demo.py
11
  pinned: false
12
  ---
13
 
batch_generate_example.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ from transformers import AutoTokenizer
3
+
4
+ from moondream.hf import LATEST_REVISION, Moondream, detect_device
5
+
6
+ device, dtype = detect_device()
7
+
8
+ model_id = "vikhyatk/moondream2"
9
+ tokenizer = AutoTokenizer.from_pretrained(model_id, revision=LATEST_REVISION)
10
+ moondream = Moondream.from_pretrained(
11
+ model_id,
12
+ revision=LATEST_REVISION,
13
+ torch_dtype=dtype,
14
+ ).to(device=device)
15
+ moondream.eval()
16
+
17
+ image1 = Image.open("assets/demo-1.jpg")
18
+ image2 = Image.open("assets/demo-2.jpg")
19
+ prompts = [
20
+ "What is the girl doing?",
21
+ "What color is the girl's hair?",
22
+ "What is this?",
23
+ "What is behind the stand?",
24
+ ]
25
+
26
+ answers = moondream.batch_answer(
27
+ images=[image1, image1, image2, image2],
28
+ prompts=prompts,
29
+ tokenizer=tokenizer,
30
+ )
31
+
32
+ for question, answer in zip(prompts, answers):
33
+ print(f"Q: {question}")
34
+ print(f"A: {answer}")
35
+ print()
clients/python/README.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Moondream Python Client Library
2
+
3
+ Python client library for moondream. This library is an alpha preview -- it is
4
+ in an early stage of development, and backward compatibility is not yet
5
+ guaranteed. If you are using this in production, please pin the revision you
6
+ are using.
7
+
8
+ This library currently offers optimized CPU inference, but will be slower than
9
+ the PyTorch implementation for CUDA and MPS backends. If you are running on a
10
+ Mac with M1/M2/M3 etc. chips, or if you have a GPU available, this library is
11
+ not recommended yet.
12
+
13
+ ## Setup
14
+
15
+ Install the library using pip:
16
+
17
+ ```bash
18
+ pip install moondream==0.0.2
19
+ ```
20
+
21
+ Then download the model weights:
22
+
23
+ ```bash
24
+ # int8 weights (recommended):
25
+ wget "https://huggingface.co/vikhyatk/moondream2/resolve/client/moondream-latest-int8.bin.gz?download=true" -O - | gunzip > moondream-latest-int8.bin
26
+ # ...or, for fp16 weights (full precision):
27
+ wget "https://huggingface.co/vikhyatk/moondream2/resolve/client/moondream-latest-f16.bin.gz?download=true" -O - | gunzip > moondream-latest-f16.bin
28
+ # ...or, for int4 weights (resource constrained environments):
29
+ wget "https://huggingface.co/vikhyatk/moondream2/resolve/client/moondream-latest-int4.bin.gz?download=true" -O - | gunzip > moondream-latest-int4.bin
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ ```python
35
+ import moondream as md
36
+ from PIL import Image
37
+
38
+ model = md.VL("moondream-latest-int8.bin")
39
+ image = Image.open("path/to/image.jpg").convert("RGB")
40
+
41
+ # Optional -- encode the image to efficiently run multiple queries on the same
42
+ # image. This is not mandatory, since the model will automatically encode the
43
+ # image if it is not already encoded.
44
+ encoded_image = model.encode_image(image)
45
+
46
+ # Caption the image.
47
+ caption = model.caption(encoded_image)
48
+
49
+ # ...or, if you want to stream the output:
50
+ for t in model.caption(encoded_image, stream=True)["caption"]:
51
+ print(t, end="", flush=True)
52
+
53
+ # Ask a question about the image.
54
+ question = "How many people are in this image?"
55
+ answer = model.query(encoded_image, question)["answer"]
56
+
57
+ # ...or again, if you want to stream the output:
58
+ for t in model.query(encoded_image, question, stream=True)["answer"]:
59
+ print(t, end="", flush=True)
60
+ ```
clients/python/moondream/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .vl import VL
clients/python/moondream/preprocess.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Tuple
2
+
3
+ import numpy as np
4
+ from PIL import Image
5
+
6
+
7
+ def im_resize(
8
+ image: Image.Image,
9
+ size: Tuple[int, int],
10
+ resample: int = Image.Resampling.BICUBIC,
11
+ ) -> Image.Image:
12
+ return image.resize(size, resample=resample)
13
+
14
+
15
+ def normalize(
16
+ image: np.ndarray,
17
+ mean: List[float] = [0.5, 0.5, 0.5],
18
+ std: List[float] = [0.5, 0.5, 0.5],
19
+ ) -> np.ndarray:
20
+ """
21
+ Normalize an image array.
22
+ """
23
+ return (image - np.array(mean)) / np.array(std)
24
+
25
+
26
+ def create_patches(image: Image.Image, image_patch_size=378) -> np.ndarray:
27
+ """
28
+ Split the given image into a variable number of patches depending upon its
29
+ resolution.
30
+ """
31
+ # Start off with the global patch.
32
+ patches = [im_resize(image, (image_patch_size, image_patch_size))]
33
+
34
+ # Find the closest resolution template.
35
+ res_templates = [(1, 2), (2, 1), (2, 2)]
36
+ im_width, im_height = image.size
37
+ max_dim = max(im_width, im_height)
38
+ if max_dim < image_patch_size * 1.4:
39
+ # If the image is already small, we just do a single patch that is a
40
+ # duplicate of the global patch. This creates a small amount of
41
+ # redundant computation now, but it is simpler and future-proofs us
42
+ # if/when we condition the vision encoder on the patch type.
43
+ patches.append(patches[0])
44
+ else:
45
+ aspect_ratio = im_width / im_height
46
+ res_template = min(
47
+ res_templates, key=lambda size: abs((size[1] / size[0]) - aspect_ratio)
48
+ )
49
+ # TODO: Actually implement patching... just going to put in the global
50
+ # patch for now to make progress on other aspects.
51
+ patches.append(patches[0])
52
+
53
+ return np.stack(
54
+ [
55
+ normalize(
56
+ (np.array(patch_img) / 255.0),
57
+ mean=[0.5, 0.5, 0.5],
58
+ std=[0.5, 0.5, 0.5],
59
+ ).transpose(2, 0, 1)
60
+ for patch_img in patches
61
+ ],
62
+ dtype=np.float16,
63
+ )
clients/python/moondream/vl.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import tarfile
4
+ from dataclasses import dataclass
5
+ from io import BytesIO
6
+ from typing import Any, Dict, Generator, List, Optional, TypedDict, Union
7
+
8
+ import numpy as np
9
+ import onnx
10
+ import onnxruntime as ort
11
+ from PIL import Image
12
+ from tokenizers import Tokenizer
13
+
14
+ from .preprocess import create_patches
15
+
16
+
17
+ @dataclass
18
+ class EncodedImage:
19
+ pos: int
20
+ kv_caches: List[np.ndarray]
21
+
22
+
23
+ SamplingSettings = TypedDict(
24
+ "SamplingSettings",
25
+ {"max_tokens": int},
26
+ total=False,
27
+ )
28
+
29
+ CaptionOutput = TypedDict(
30
+ "CaptionOutput", {"caption": Union[str, Generator[str, None, None]]}
31
+ )
32
+ QueryOutput = TypedDict(
33
+ "QueryOutput", {"answer": Union[str, Generator[str, None, None]]}
34
+ )
35
+
36
+ DEFAULT_MAX_TOKENS = 1024
37
+ MIN_SUPPORTED_VERSION = 1
38
+ MAX_SUPPORT_VERSION = 1
39
+
40
+
41
+ class Region:
42
+ pass
43
+
44
+
45
+ class VL:
46
+ def __init__(self, model_path: Optional[str], ort_settings: Dict[str, Any] = {}):
47
+ """
48
+ Initialize the Moondream VL (Vision Language) model.
49
+
50
+ Args:
51
+ model_path (str): The path to the model file.
52
+
53
+ Returns:
54
+ None
55
+ """
56
+
57
+ if model_path is None or not os.path.isfile(model_path):
58
+ raise ValueError("Model path is invalid or file does not exist.")
59
+
60
+ if not tarfile.is_tarfile(model_path):
61
+ raise ValueError(
62
+ "Model format not recognized. You may need to upgrade the moondream"
63
+ " package."
64
+ )
65
+
66
+ self.text_decoders = []
67
+
68
+ with tarfile.open(model_path, "r:*") as tar:
69
+ for member in tar.getmembers():
70
+ name = member.name.split("/")[-1]
71
+
72
+ f = tar.extractfile(member)
73
+ if f is not None:
74
+ contents = f.read()
75
+ else:
76
+ continue
77
+
78
+ if name == "vision_encoder.onnx":
79
+ self.vision_encoder = ort.InferenceSession(contents, **ort_settings)
80
+ elif name == "vision_projection.onnx":
81
+ self.vision_projection = ort.InferenceSession(
82
+ contents, **ort_settings
83
+ )
84
+ elif name == "text_encoder.onnx":
85
+ self.text_encoder = ort.InferenceSession(contents, **ort_settings)
86
+ elif "text_decoder" in name and name.endswith(".onnx"):
87
+ self.text_decoders.append(
88
+ ort.InferenceSession(contents, **ort_settings)
89
+ )
90
+ elif name == "tokenizer.json":
91
+ self.tokenizer = Tokenizer.from_buffer(contents)
92
+ elif name == "initial_kv_caches.npy":
93
+ self.initial_kv_caches = [x for x in np.load(BytesIO(contents))]
94
+ elif name == "config.json":
95
+ self.config = json.loads(contents)
96
+
97
+ assert self.vision_encoder is not None
98
+ assert self.vision_projection is not None
99
+ assert self.text_encoder is not None
100
+ assert len(self.text_decoders) > 0
101
+ assert self.tokenizer is not None
102
+ assert self.initial_kv_caches is not None
103
+ assert self.config is not None
104
+
105
+ if type(self.config) != dict or "model_version" not in self.config:
106
+ raise ValueError("Model format not recognized.")
107
+ if (
108
+ self.config["model_version"] < MIN_SUPPORTED_VERSION
109
+ or self.config["model_version"] > MAX_SUPPORT_VERSION
110
+ ):
111
+ raise ValueError(
112
+ "Model version not supported. You may need to upgrade the moondream"
113
+ " package."
114
+ )
115
+
116
+ self.special_tokens = self.config["special_tokens"]
117
+ self.templates = self.config["templates"]
118
+
119
+ def encode_image(self, image: Union[Image.Image, EncodedImage]) -> EncodedImage:
120
+ """
121
+ Preprocess the image by running it through the model.
122
+
123
+ This method is useful if the user wants to make multiple queries with the same image.
124
+ The output is not guaranteed to be backward-compatible across version updates,
125
+ and should not be persisted out of band.
126
+
127
+ Args:
128
+ image (Image.Image): The input image to be encoded.
129
+
130
+ Returns:
131
+ The encoded representation of the image.
132
+ """
133
+ if type(image) == EncodedImage:
134
+ return image
135
+
136
+ image_patches = create_patches(image) # type: ignore
137
+
138
+ patch_emb = self.vision_encoder.run(None, {"input": image_patches})[0]
139
+ patch_emb = np.concatenate([patch_emb[0], patch_emb[1]], axis=-1)
140
+ patch_emb = np.expand_dims(patch_emb, axis=0)
141
+ (inputs_embeds,) = self.vision_projection.run(None, {"input": patch_emb})
142
+
143
+ kv_caches = self.initial_kv_caches
144
+ pos = inputs_embeds.shape[-2] + kv_caches[0].shape[-2]
145
+
146
+ for i, decoder in enumerate(self.text_decoders):
147
+ inputs_embeds, kv_cache_update = decoder.run(
148
+ None,
149
+ {
150
+ "inputs_embeds": inputs_embeds,
151
+ "kv_cache": kv_caches[i],
152
+ },
153
+ )
154
+ kv_caches[i] = np.concatenate([kv_caches[i], kv_cache_update], axis=-2)
155
+ return EncodedImage(pos=pos, kv_caches=kv_caches)
156
+
157
+ def _generate(
158
+ self, hidden: np.ndarray, encoded_image: EncodedImage, max_tokens: int
159
+ ) -> Generator[str, None, None]:
160
+ kv_caches = {
161
+ i: np.zeros(
162
+ (
163
+ *self.initial_kv_caches[0].shape[:-2],
164
+ 2048,
165
+ self.initial_kv_caches[0].shape[-1],
166
+ ),
167
+ dtype=np.float16,
168
+ )
169
+ for i in range(len(self.text_decoders))
170
+ }
171
+ for i, kv_cache in kv_caches.items():
172
+ kv_cache[:, :, :, :, : encoded_image.pos, :] = encoded_image.kv_caches[i]
173
+
174
+ pos = encoded_image.pos
175
+ generated_tokens = 0
176
+ while generated_tokens < max_tokens:
177
+ # Track the original T dimension of the input hidden states, so we can
178
+ # bind the kv cache update accordingly. We can't check it just-in-time
179
+ # because the final 'hidden' output is actually the model's logits.
180
+ og_t = hidden.shape[-2]
181
+
182
+ for i, decoder in enumerate(self.text_decoders):
183
+ hidden, kv_cache_update = decoder.run(
184
+ None,
185
+ {
186
+ "inputs_embeds": hidden,
187
+ "kv_cache": kv_caches[i][:, :, :, :, :pos, :],
188
+ },
189
+ )
190
+ kv_caches[i][:, :, :, :, pos : pos + og_t, :] = kv_cache_update
191
+
192
+ next_token = np.argmax(hidden, axis=-1)[0]
193
+ if next_token == self.special_tokens["eos"]:
194
+ break
195
+
196
+ yield self.tokenizer.decode([next_token])
197
+ generated_tokens += 1
198
+ pos += og_t
199
+ (hidden,) = self.text_encoder.run(None, {"input_ids": [[next_token]]})
200
+
201
+ def caption(
202
+ self,
203
+ image: Union[Image.Image, EncodedImage],
204
+ length: str = "normal",
205
+ stream: bool = False,
206
+ settings: Optional[SamplingSettings] = None,
207
+ ) -> CaptionOutput:
208
+ """
209
+ Generate a caption for the input image.
210
+
211
+ Args:
212
+ image (Union[Image.Image, EncodedImage]): The input image to be captioned.
213
+ settings (Optional[SamplingSettings]): Optional settings for the caption generation.
214
+ If not provided, default settings will be used.
215
+
216
+ Returns:
217
+ str: The caption for the input image.
218
+ """
219
+ if "caption" not in self.templates:
220
+ raise ValueError("Model does not support captioning.")
221
+ if length not in self.templates["caption"]:
222
+ raise ValueError(f"Model does not support caption length '{length}'.")
223
+
224
+ (input_embeds,) = self.text_encoder.run(
225
+ None, {"input_ids": [self.templates["caption"][length]]}
226
+ )
227
+ if settings is None:
228
+ settings = {}
229
+ max_tokens = settings.get("max_tokens", DEFAULT_MAX_TOKENS)
230
+
231
+ encoded_image = self.encode_image(image)
232
+
233
+ def generator():
234
+ for t in self._generate(input_embeds, encoded_image, max_tokens):
235
+ yield t
236
+
237
+ if stream:
238
+ return {"caption": generator()}
239
+ else:
240
+ out = ""
241
+ for t in generator():
242
+ out += t
243
+ return {"caption": out}
244
+
245
+ def query(
246
+ self,
247
+ image: Union[Image.Image, EncodedImage],
248
+ question: str,
249
+ stream: bool = False,
250
+ settings: Optional[SamplingSettings] = None,
251
+ ) -> QueryOutput:
252
+ """
253
+ Generate an answer to the input question about the input image.
254
+
255
+ Args:
256
+ image (Union[Image.Image, EncodedImage]): The input image to be queried.
257
+ question (str): The question to be answered.
258
+
259
+ Returns:
260
+ str: The answer to the input question about the input image.
261
+ """
262
+ if "query" not in self.templates:
263
+ raise ValueError("Model does not support querying.")
264
+
265
+ question_toks = (
266
+ self.templates["query"]["prefix"]
267
+ + self.tokenizer.encode(question).ids
268
+ + self.templates["query"]["suffix"]
269
+ )
270
+
271
+ (input_embeds,) = self.text_encoder.run(None, {"input_ids": [question_toks]})
272
+ if settings is None:
273
+ settings = {}
274
+ max_tokens = settings.get("max_tokens", DEFAULT_MAX_TOKENS)
275
+
276
+ encoded_image = self.encode_image(image)
277
+
278
+ def generator():
279
+ for t in self._generate(input_embeds, encoded_image, max_tokens):
280
+ yield t
281
+
282
+ if stream:
283
+ return {"answer": generator()}
284
+ else:
285
+ out = ""
286
+ for t in generator():
287
+ out += t
288
+ return {"answer": out}
289
+
290
+ def detect(
291
+ self, image: Union[Image.Image, EncodedImage], object: str
292
+ ) -> List[Region]:
293
+ """
294
+ Detect and localize the specified object in the input image.
295
+
296
+ Args:
297
+ image (Union[Image.Image, EncodedImage]): The input image to be analyzed.
298
+ object (str): The object to be detected in the image.
299
+
300
+ Returns:
301
+ List[Region]: A list of Region objects representing the detected instances of the specified object.
302
+ """
303
+ return []
clients/python/pyproject.toml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [tool.poetry]
2
+ name = "moondream"
3
+ version = "0.0.2"
4
+ description = "Python client library for moondream"
5
+ authors = ["vik <vik@moondream.ai>"]
6
+ readme = "README.md"
7
+
8
+ [tool.poetry.dependencies]
9
+ python = "^3.10"
10
+ pillow = "^10.4.0"
11
+ onnxruntime = "^1.19.2"
12
+ numpy = "^2.1.2"
13
+ onnx = "^1.17.0"
14
+ tokenizers = "^0.20.1"
15
+
16
+
17
+ [tool.pyright]
18
+ venvPath = "."
19
+ venv = ".venv"
20
+ reportMissingParameterType = false
21
+
22
+ [build-system]
23
+ requires = ["poetry-core"]
24
+ build-backend = "poetry.core.masonry.api"
clients/python/scripts/test.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import tracemalloc
3
+
4
+ from PIL import Image
5
+
6
+ import moondream as md
7
+ from moondream.preprocess import create_patches
8
+
9
+ MODEL_PATH = "../../onnx/out/moondream-latest-int4.bin"
10
+
11
+
12
+ class Colors:
13
+ HEADER = "\033[95m" # Purple
14
+ BLUE = "\033[94m"
15
+ GREEN = "\033[92m"
16
+ YELLOW = "\033[93m"
17
+ RED = "\033[91m"
18
+ ENDC = "\033[0m"
19
+ BOLD = "\033[1m"
20
+
21
+
22
+ def format_memory(memory_mb):
23
+ """Format memory size with appropriate unit"""
24
+ if memory_mb < 1024:
25
+ return f"{memory_mb:.2f} MB"
26
+ else:
27
+ return f"{memory_mb/1024:.2f} GB"
28
+
29
+
30
+ def print_section(title):
31
+ """Print a section header with dynamic padding to center the text"""
32
+ total_width = 65
33
+ text_length = len(title) + 2 # Add 2 for spaces around title
34
+ total_padding = total_width - text_length
35
+ left_padding = total_padding // 2
36
+ right_padding = total_padding - left_padding
37
+ print(
38
+ f"\n{Colors.HEADER}{Colors.BOLD}{'-'*left_padding} {title} {'-'*right_padding}{Colors.ENDC}"
39
+ )
40
+
41
+
42
+ def print_metric(label, value, color=Colors.BLUE):
43
+ """Print a metric with consistent formatting"""
44
+ print(f"| {color}{label}{Colors.ENDC}: {value}")
45
+
46
+
47
+ def log_memory_and_time(operation_name, start_time, start_memory):
48
+ """Log memory and time differences for an operation"""
49
+ end_time = time.time()
50
+ current_memory = get_memory_usage()
51
+ time_diff = end_time - start_time
52
+ memory_diff = current_memory - start_memory
53
+
54
+ print("\nStats")
55
+ print_metric("Time", f"{time_diff:.2f} seconds")
56
+ print_metric("Memory usage", format_memory(current_memory))
57
+
58
+ # Color-code memory increase based on significance
59
+ color = (
60
+ Colors.GREEN
61
+ if memory_diff < 10
62
+ else Colors.YELLOW if memory_diff < 100 else Colors.RED
63
+ )
64
+ print_metric("Memory increase", format_memory(memory_diff), color)
65
+
66
+ return end_time, current_memory
67
+
68
+
69
+ def get_memory_usage():
70
+ """Get current memory usage in MB"""
71
+ current, peak = tracemalloc.get_traced_memory()
72
+ return current / 1024 / 1024
73
+
74
+
75
+ # Start tracking memory
76
+ tracemalloc.start()
77
+
78
+ # Initial memory measurement
79
+ initial_memory = get_memory_usage()
80
+ print_section("Initial State")
81
+ print_metric("Initial memory usage", format_memory(initial_memory))
82
+
83
+ # Load image
84
+ print_section("Image Loading")
85
+ start_time = time.time()
86
+ start_memory = get_memory_usage()
87
+ image = Image.open("../../assets/demo-1.jpg")
88
+ log_memory_and_time("Image Loading", start_time, start_memory)
89
+
90
+ # Initialize model
91
+ print_section("Model Initialization")
92
+ start_time = time.time()
93
+ start_memory = get_memory_usage()
94
+ model = md.VL(MODEL_PATH)
95
+ log_memory_and_time("Model Initialization", start_time, start_memory)
96
+
97
+ # Encode image
98
+ print_section("Image Encoding")
99
+ start_time = time.time()
100
+ start_memory = get_memory_usage()
101
+ encoded_image = model.encode_image(image)
102
+ log_memory_and_time("Image Encoding", start_time, start_memory)
103
+
104
+ # Generate caption
105
+ print_section("Caption Generation")
106
+ print(f"{Colors.BOLD}Caption:{Colors.ENDC}", end="", flush=True)
107
+ start_time = time.time()
108
+ start_memory = get_memory_usage()
109
+ tokens = 0
110
+ for tok in model.caption(encoded_image, stream=True)["caption"]:
111
+ print(tok, end="", flush=True)
112
+ tokens += 1
113
+ print()
114
+ end_time, end_memory = log_memory_and_time("Caption Stats", start_time, start_memory)
115
+ print_metric("Token generation speed", f"{tokens / (end_time - start_time):.2f} tok/s")
116
+
117
+ # Generate answer to question
118
+ question = "How many people are in this image? Answer briefly."
119
+ print_section("Question Answering")
120
+ print(f"{Colors.BOLD}Question:{Colors.ENDC} {question}")
121
+ print(f"{Colors.BOLD}Answer:{Colors.ENDC}", end="", flush=True)
122
+ start_time = time.time()
123
+ start_memory = get_memory_usage()
124
+ tokens = 0
125
+ for tok in model.query(encoded_image, question, stream=True)["answer"]:
126
+ print(tok, end="", flush=True)
127
+ tokens += 1
128
+ print()
129
+ end_time, end_memory = log_memory_and_time(
130
+ "Question Answering Stats", start_time, start_memory
131
+ )
132
+ print_metric("Token generation speed", f"{tokens / (end_time - start_time):.2f} tok/s")
133
+
134
+ # Final summary
135
+ print_section("Final Summary")
136
+ final_memory = get_memory_usage()
137
+ current, peak = tracemalloc.get_traced_memory()
138
+
139
+ print_metric("Final memory usage", format_memory(final_memory))
140
+ print_metric("Total memory increase", format_memory(final_memory - initial_memory))
141
+ print_metric("Peak memory usage", format_memory(peak / 1024 / 1024))
142
+
143
+ # Stop tracking memory
144
+ tracemalloc.stop()
gradio_demo.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import re
3
+ from threading import Thread
4
+
5
+ import gradio as gr
6
+ import torch
7
+ from PIL import ImageDraw
8
+ from torchvision.transforms.v2 import Resize
9
+ from transformers import AutoTokenizer, TextIteratorStreamer
10
+
11
+ from moondream.hf import LATEST_REVISION, Moondream, detect_device
12
+
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument("--cpu", action="store_true")
15
+ args = parser.parse_args()
16
+
17
+ if args.cpu:
18
+ device = torch.device("cpu")
19
+ dtype = torch.float32
20
+ else:
21
+ device, dtype = detect_device()
22
+ if device != torch.device("cpu"):
23
+ print("Using device:", device)
24
+ print("If you run into issues, pass the `--cpu` flag to this script.")
25
+ print()
26
+
27
+ model_id = "vikhyatk/moondream2"
28
+ tokenizer = AutoTokenizer.from_pretrained(model_id, revision=LATEST_REVISION)
29
+ moondream = Moondream.from_pretrained(
30
+ model_id, revision=LATEST_REVISION, torch_dtype=dtype
31
+ ).to(device=device)
32
+ moondream.eval()
33
+
34
+
35
+ def answer_question(img, prompt):
36
+ image_embeds = moondream.encode_image(img)
37
+ streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
38
+ thread = Thread(
39
+ target=moondream.answer_question,
40
+ kwargs={
41
+ "image_embeds": image_embeds,
42
+ "question": prompt,
43
+ "tokenizer": tokenizer,
44
+ "streamer": streamer,
45
+ },
46
+ )
47
+ thread.start()
48
+
49
+ buffer = ""
50
+ for new_text in streamer:
51
+ buffer += new_text
52
+ yield buffer
53
+
54
+
55
+ def extract_floats(text):
56
+ # Regular expression to match an array of four floating point numbers
57
+ pattern = r"\[\s*(-?\d+\.\d+)\s*,\s*(-?\d+\.\d+)\s*,\s*(-?\d+\.\d+)\s*,\s*(-?\d+\.\d+)\s*\]"
58
+ match = re.search(pattern, text)
59
+ if match:
60
+ # Extract the numbers and convert them to floats
61
+ return [float(num) for num in match.groups()]
62
+ return None # Return None if no match is found
63
+
64
+
65
+ def extract_bbox(text):
66
+ bbox = None
67
+ if extract_floats(text) is not None:
68
+ x1, y1, x2, y2 = extract_floats(text)
69
+ bbox = (x1, y1, x2, y2)
70
+ return bbox
71
+
72
+
73
+ def process_answer(img, answer):
74
+ if extract_bbox(answer) is not None:
75
+ x1, y1, x2, y2 = extract_bbox(answer)
76
+ draw_image = Resize(768)(img)
77
+ width, height = draw_image.size
78
+ x1, x2 = int(x1 * width), int(x2 * width)
79
+ y1, y2 = int(y1 * height), int(y2 * height)
80
+ bbox = (x1, y1, x2, y2)
81
+ ImageDraw.Draw(draw_image).rectangle(bbox, outline="red", width=3)
82
+ return gr.update(visible=True, value=draw_image)
83
+
84
+ return gr.update(visible=False, value=None)
85
+
86
+
87
+ with gr.Blocks() as demo:
88
+ gr.Markdown(
89
+ """
90
+ # 🌔 moondream
91
+ """
92
+ )
93
+ with gr.Row():
94
+ prompt = gr.Textbox(label="Input Prompt", value="Describe this image.", scale=4)
95
+ submit = gr.Button("Submit")
96
+ with gr.Row():
97
+ img = gr.Image(type="pil", label="Upload an Image")
98
+ with gr.Column():
99
+ output = gr.Markdown(label="Response")
100
+ ann = gr.Image(visible=False, label="Annotated Image")
101
+
102
+ submit.click(answer_question, [img, prompt], output)
103
+ prompt.submit(answer_question, [img, prompt], output)
104
+ output.change(process_answer, [img, output], ann, show_progress=False)
105
+
106
+ demo.queue().launch(debug=True)
hf_release.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from moondream.hf import Moondream
4
+ from moondream.hf.configuration_moondream import MoondreamConfig
5
+
6
+ MoondreamConfig.register_for_auto_class()
7
+ Moondream.register_for_auto_class("AutoModelForCausalLM")
8
+
9
+ OUT_MODEL = "vikhyatk/moondream-next"
10
+ CKPT_DIRS = []
11
+
12
+
13
+ def get_ckpt(filename):
14
+ ckpts = [torch.load(f"{dir}/{filename}", map_location="cpu") for dir in CKPT_DIRS]
15
+ avg_ckpt = {key: sum(ckpt[key] for ckpt in ckpts) / len(ckpts) for key in ckpts[0]}
16
+ return avg_ckpt
17
+
18
+
19
+ config = MoondreamConfig()
20
+ model = Moondream(config)
21
+ model.vision_encoder.encoder.load_state_dict(get_ckpt("vision_encoder.final.pt"))
22
+ model.vision_encoder.projection.load_state_dict(get_ckpt("vision_projection.final.pt"))
23
+ model.text_model.load_state_dict(get_ckpt("text_model.final.pt"))
24
+ model.region_model.load_state_dict(get_ckpt("region_model.final.pt"))
25
+ model = model.to(dtype=torch.float16)
26
+
27
+ model.push_to_hub(OUT_MODEL, config=config)
notebooks/RepEng.ipynb ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "This notebook shows how to compute control vectors to steer moondream's behavior\n",
8
+ "in fun and interesting ways. To learn more about control vectors and representation\n",
9
+ "engineering check out [Theia's blog post on the topic](https://vgel.me/posts/representation-engineering/)."
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": 32,
15
+ "metadata": {},
16
+ "outputs": [],
17
+ "source": [
18
+ "import torch\n",
19
+ "from transformers import AutoModelForCausalLM, AutoTokenizer\n",
20
+ "from datasets import load_dataset\n",
21
+ "from tqdm import tqdm\n",
22
+ "from PIL import Image\n",
23
+ "import numpy as np\n",
24
+ "from sklearn.decomposition import PCA\n",
25
+ "from IPython.display import display, HTML"
26
+ ]
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "execution_count": null,
31
+ "metadata": {},
32
+ "outputs": [],
33
+ "source": [
34
+ "tokenizer = AutoTokenizer.from_pretrained(\"vikhyatk/moondream2\")\n",
35
+ "model = AutoModelForCausalLM.from_pretrained(\n",
36
+ " \"vikhyatk/moondream2\", trust_remote_code=True,\n",
37
+ " torch_dtype=torch.float16, device_map={\"\": \"cuda\"}\n",
38
+ ")\n",
39
+ "\n",
40
+ "# We will only be using the images, so it doesn't really matter what\n",
41
+ "# dataset we use here.\n",
42
+ "dataset = load_dataset(\"vikhyatk/lnqa\", streaming=True)[\"train\"]\n",
43
+ "\n",
44
+ "def hidden_states(enc_img, prompt):\n",
45
+ " with torch.no_grad():\n",
46
+ " inputs_embeds = model.input_embeds(prompt, enc_img, tokenizer)\n",
47
+ " hidden_states = model.text_model.generate(\n",
48
+ " inputs_embeds=inputs_embeds,\n",
49
+ " max_new_tokens=128,\n",
50
+ " pad_token_id=tokenizer.eos_token_id,\n",
51
+ " eos_token_id=tokenizer.eos_token_id,\n",
52
+ " return_dict_in_generate=True,\n",
53
+ " output_hidden_states=True,\n",
54
+ " do_sample=True,\n",
55
+ " temperature=0.5\n",
56
+ " ).hidden_states[1:]\n",
57
+ " return [torch.stack([hs.view(-1, 2048) for hs in h[1:]]).cpu() for h in hidden_states]\n",
58
+ "\n",
59
+ "class LayerWrapper(torch.nn.Module):\n",
60
+ " def __init__(self, og_layer, control_vectors, scale=4.2):\n",
61
+ " super().__init__()\n",
62
+ " self.og_layer = og_layer\n",
63
+ " self.control_vectors = control_vectors\n",
64
+ " self.scale = scale\n",
65
+ "\n",
66
+ " def forward(self, *args, **kwargs):\n",
67
+ " layer_outputs = self.og_layer(*args, **kwargs)\n",
68
+ " layer_outputs = (layer_outputs[0] + self.scale * self.control_vectors, *layer_outputs[1:])\n",
69
+ " return layer_outputs"
70
+ ]
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "execution_count": 112,
75
+ "metadata": {},
76
+ "outputs": [],
77
+ "source": [
78
+ "negative_prompt = \"<image>\\n\\nQuestion: Describe this image.\\n\\nAnswer:\"\n",
79
+ "positive_prompt = \"<image>\\n\\nQuestion: What is the meaning of life?\\n\\nAnswer:\"\n",
80
+ "\n",
81
+ "# This can be lowered without noticeable loss in quality. Feel free to drop it to\n",
82
+ "# IMAGES_PER_CONTROL=50 and SAMPLES_PER_IMAGE=2 if it's taking too long.\n",
83
+ "IMAGES_PER_CONTROL = 200\n",
84
+ "SAMPLES_PER_IMAGE = 5\n"
85
+ ]
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "execution_count": 113,
90
+ "metadata": {},
91
+ "outputs": [
92
+ {
93
+ "name": "stderr",
94
+ "output_type": "stream",
95
+ "text": [
96
+ "100%|██████████| 200/200 [37:09<00:00, 11.15s/it]\n"
97
+ ]
98
+ }
99
+ ],
100
+ "source": [
101
+ "# This is not very efficient, batching would speed things up a lot.\n",
102
+ "# But eh, works for a quick demo.\n",
103
+ "\n",
104
+ "hs_dataset = [[] for _ in range(24)]\n",
105
+ "\n",
106
+ "for i, sample in tqdm(enumerate(dataset), total=IMAGES_PER_CONTROL):\n",
107
+ " if i >= IMAGES_PER_CONTROL:\n",
108
+ " break\n",
109
+ " image = sample[\"image\"]\n",
110
+ " enc_img = model.encode_image(image)\n",
111
+ " for _ in range(SAMPLES_PER_IMAGE):\n",
112
+ " phs = hidden_states(enc_img, positive_prompt)\n",
113
+ " nhs = hidden_states(enc_img, negative_prompt)\n",
114
+ " t_max = min(len(phs), len(nhs))\n",
115
+ " for t in range(t_max):\n",
116
+ " phs_t = phs[t]\n",
117
+ " nhs_t = nhs[t]\n",
118
+ " for j in range(24):\n",
119
+ " hs_dataset[j].append(phs_t[j])\n",
120
+ " hs_dataset[j].append(nhs_t[j])"
121
+ ]
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "execution_count": 114,
126
+ "metadata": {},
127
+ "outputs": [
128
+ {
129
+ "name": "stderr",
130
+ "output_type": "stream",
131
+ "text": [
132
+ "100%|██████████| 24/24 [02:30<00:00, 6.26s/it]\n"
133
+ ]
134
+ }
135
+ ],
136
+ "source": [
137
+ "control_vectors = []\n",
138
+ "\n",
139
+ "for i in tqdm(range(24)):\n",
140
+ " layer_hiddens = torch.stack(hs_dataset[i])\n",
141
+ "\n",
142
+ " layer_centers = (layer_hiddens[::2] + layer_hiddens[1::2]) / 2\n",
143
+ " relative_layer_hiddens = layer_hiddens\n",
144
+ " relative_layer_hiddens[::2] -= layer_centers\n",
145
+ " relative_layer_hiddens[1::2] -= layer_centers\n",
146
+ "\n",
147
+ " train = relative_layer_hiddens - relative_layer_hiddens.mean(axis=0, keepdims=True)\n",
148
+ " train = train.view(-1, 2048).cpu().numpy()\n",
149
+ " pca_model = PCA(n_components=1, whiten=False).fit(train)\n",
150
+ " directions = pca_model.components_.astype(np.float32).squeeze(axis=0)\n",
151
+ "\n",
152
+ " projected_hiddens = (layer_hiddens.cpu().numpy() @ directions) / np.linalg.norm(directions)\n",
153
+ "\n",
154
+ " positive_smaller_mean = np.mean(\n",
155
+ " [\n",
156
+ " projected_hiddens[i] < projected_hiddens[i + 1]\n",
157
+ " for i in range(0, len(hs_dataset[i]), 2)\n",
158
+ " ]\n",
159
+ " )\n",
160
+ " positive_larger_mean = np.mean(\n",
161
+ " [\n",
162
+ " projected_hiddens[i] > projected_hiddens[i + 1]\n",
163
+ " for i in range(0, len(hs_dataset[i]), 2)\n",
164
+ " ]\n",
165
+ " )\n",
166
+ " if positive_smaller_mean > positive_larger_mean: # type: ignore\n",
167
+ " directions *= -1\n",
168
+ "\n",
169
+ " control_vectors.append(torch.tensor(directions, device=\"cuda\", dtype=torch.float16))\n"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "execution_count": 116,
175
+ "metadata": {},
176
+ "outputs": [
177
+ {
178
+ "data": {
179
+ "text/html": [
180
+ "\n",
181
+ "<table style=\"border: 1px solid black; border-collapse: collapse;\">\n",
182
+ " <tr>\n",
183
+ " <th style=\"border: 1px solid black; padding: 8px;\">Image</th>\n",
184
+ " <th style=\"border: 1px solid black; padding: 8px;\">Text</th>\n",
185
+ " </tr>\n",
186
+ "\n",
187
+ " <tr>\n",
188
+ " <td style=\"border: 1px solid black; padding: 8px;\">\n",
189
+ " <img src=\"../assets/demo-1.jpg\" style=\"width:250px;\">\n",
190
+ " </td>\n",
191
+ " <td style=\"border: 1px solid black; padding: 8px; text-align: left\">\n",
192
+ " <strong>Describe this image.</strong><br><br>\n",
193
+ " In this image, we will explore the concept of happiness through an anthropomorphic interpretation. We'll look at it from a spiritual or religious perspective by examining what brings joy and fulfillment to human beings. This can be approached in various ways depending on individual beliefs and experiences.<br><br>To understand happiness, one might consider factors such as personal goals, relationships, health, wealth, spirituality, ethics, and more. It is subjective and varies greatly among individuals based on their values and life experiences. However, many people often seek happiness in different aspects like achieving success, finding inner peace, or living a meaningful life.<br><br>In the context of the provided statements about happiness, some may find happiness in material possessions (e.of), while others may seek happiness through relationships, creativity, or even simple pleasures that bring satisfaction and contentment. Ultimately, happiness is a deeply personal journey for each person to define and pursue according to their own beliefs and values.\n",
194
+ " </td>\n",
195
+ " </tr>\n",
196
+ " \n",
197
+ " <tr>\n",
198
+ " <td style=\"border: 1px solid black; padding: 8px;\">\n",
199
+ " <img src=\"../assets/demo-2.jpg\" style=\"width:250px;\">\n",
200
+ " </td>\n",
201
+ " <td style=\"border: 1px solid black; padding: 8px; text-align: left\">\n",
202
+ " <strong>What is this?</strong><br><br>\n",
203
+ " In the context of this image, a server or processor is an essential component for computing and running various applications on computers. A Processor (or CPU) can refer to any device that executes tasks according to specific programming requirements.<br><br>In this particular scenario, we are referring to advanced technologies like virtual machines, artificial intelligence, machine learning, etc., which require powerful computing systems to function effectively.<br><br>For example, in the case of AI research, researchers develop and test theories using sophisticated computer models and simulations. These concepts may involve analyzing vast amounts of data, exploring ethical questions, understanding existence, or even developing new knowledge about life itself.<br><br>In summary, when people talk about \"the meaning\" or \"purpose,\" they often refer to these advanced concepts as well. It's subjective and varies from person to person based on their beliefs, values, and experiences.\n",
204
+ " </td>\n",
205
+ " </tr>\n",
206
+ " \n",
207
+ " <tr>\n",
208
+ " <td style=\"border: 1px solid black; padding: 8px;\">\n",
209
+ " <img src=\"../assets/demo-2.jpg\" style=\"width:250px;\">\n",
210
+ " </td>\n",
211
+ " <td style=\"border: 1px solid black; padding: 8px; text-align: left\">\n",
212
+ " <strong>What color is the couch?</strong><br><br>\n",
213
+ " The couch in the image is described as \"black.\" However, without more information or context from different sources, it's difficult to determine its actual color. It could be any of those things like comfort, aesthetics, personal preferences, etc., which can vary among individuals.\n",
214
+ " </td>\n",
215
+ " </tr>\n",
216
+ " </table>"
217
+ ],
218
+ "text/plain": [
219
+ "<IPython.core.display.HTML object>"
220
+ ]
221
+ },
222
+ "metadata": {},
223
+ "output_type": "display_data"
224
+ }
225
+ ],
226
+ "source": [
227
+ "prompts = [\n",
228
+ " (\"../assets/demo-1.jpg\", \"Describe this image.\"),\n",
229
+ " (\"../assets/demo-2.jpg\", \"What is this?\"),\n",
230
+ " (\"../assets/demo-2.jpg\", \"What color is the couch?\"),\n",
231
+ "]\n",
232
+ "data = []\n",
233
+ "\n",
234
+ "def run_model(img_path, prompt, scale=4.2):\n",
235
+ " og_h = model.text_model.transformer.h\n",
236
+ " model.text_model.transformer.h = torch.nn.ModuleList([\n",
237
+ " LayerWrapper(layer, vector, scale) for layer, vector in zip(og_h, control_vectors)\n",
238
+ " ])\n",
239
+ " answer = model.answer_question(\n",
240
+ " model.encode_image(Image.open(img_path)), prompt, tokenizer,\n",
241
+ " repetition_penalty=1.2, temperature=0.1, do_sample=True,\n",
242
+ " length_penalty=1.2\n",
243
+ " )\n",
244
+ " model.text_model.transformer.h = og_h\n",
245
+ " return answer\n",
246
+ "\n",
247
+ "for img_path, prompt in prompts:\n",
248
+ " answer = run_model(img_path, prompt)\n",
249
+ " data.append({\"prompt\": prompt, \"answer\": answer.replace(\"\\n\", \"<br>\"), \"image\": img_path})\n",
250
+ "\n",
251
+ "html_table = \"\"\"\n",
252
+ "<table style=\"border: 1px solid black; border-collapse: collapse;\">\n",
253
+ " <tr>\n",
254
+ " <th style=\"border: 1px solid black; padding: 8px;\">Image</th>\n",
255
+ " <th style=\"border: 1px solid black; padding: 8px;\">Text</th>\n",
256
+ " </tr>\n",
257
+ "\"\"\"\n",
258
+ "\n",
259
+ "for item in data:\n",
260
+ " html_table += f\"\"\"\n",
261
+ " <tr>\n",
262
+ " <td style=\"border: 1px solid black; padding: 8px;\">\n",
263
+ " <img src=\"{item['image']}\" style=\"width:250px;\">\n",
264
+ " </td>\n",
265
+ " <td style=\"border: 1px solid black; padding: 8px; text-align: left\">\n",
266
+ " <strong>{item['prompt']}</strong><br><br>\n",
267
+ " {item['answer']}\n",
268
+ " </td>\n",
269
+ " </tr>\n",
270
+ " \"\"\"\n",
271
+ "\n",
272
+ "html_table += \"</table>\"\n",
273
+ "\n",
274
+ "# Display the HTML table\n",
275
+ "display(HTML(html_table))"
276
+ ]
277
+ }
278
+ ],
279
+ "metadata": {
280
+ "kernelspec": {
281
+ "display_name": ".venv",
282
+ "language": "python",
283
+ "name": "python3"
284
+ },
285
+ "language_info": {
286
+ "codemirror_mode": {
287
+ "name": "ipython",
288
+ "version": 3
289
+ },
290
+ "file_extension": ".py",
291
+ "mimetype": "text/x-python",
292
+ "name": "python",
293
+ "nbconvert_exporter": "python",
294
+ "pygments_lexer": "ipython3",
295
+ "version": "3.10.12"
296
+ }
297
+ },
298
+ "nbformat": 4,
299
+ "nbformat_minor": 2
300
+ }
sample.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ from queue import Queue
3
+ from threading import Thread
4
+
5
+ import torch
6
+ from PIL import Image
7
+ from transformers import AutoTokenizer, TextIteratorStreamer
8
+
9
+ from moondream.hf import LATEST_REVISION, Moondream, detect_device
10
+
11
+ if __name__ == "__main__":
12
+ parser = argparse.ArgumentParser()
13
+ parser.add_argument("--image", type=str, required=True)
14
+ parser.add_argument("--prompt", type=str, required=False)
15
+ parser.add_argument("--caption", action="store_true")
16
+ parser.add_argument("--cpu", action="store_true")
17
+ args = parser.parse_args()
18
+
19
+ if args.cpu:
20
+ device = torch.device("cpu")
21
+ dtype = torch.float32
22
+ else:
23
+ device, dtype = detect_device()
24
+ if device != torch.device("cpu"):
25
+ print("Using device:", device)
26
+ print("If you run into issues, pass the `--cpu` flag to this script.")
27
+ print()
28
+
29
+ image_path = args.image
30
+ prompt = args.prompt
31
+
32
+ model_id = "vikhyatk/moondream2"
33
+ tokenizer = AutoTokenizer.from_pretrained(model_id, revision=LATEST_REVISION)
34
+ moondream = Moondream.from_pretrained(
35
+ model_id,
36
+ revision=LATEST_REVISION,
37
+ torch_dtype=dtype,
38
+ ).to(device=device)
39
+ moondream.eval()
40
+
41
+ image = Image.open(image_path)
42
+
43
+ if args.caption:
44
+ print(moondream.caption(images=[image], tokenizer=tokenizer)[0])
45
+ else:
46
+ image_embeds = moondream.encode_image(image)
47
+
48
+ if prompt is None:
49
+ chat_history = ""
50
+
51
+ while True:
52
+ question = input("> ")
53
+
54
+ result_queue = Queue()
55
+
56
+ streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
57
+
58
+ # Separate direct arguments from keyword arguments
59
+ thread_args = (image_embeds, question, tokenizer, chat_history)
60
+ thread_kwargs = {"streamer": streamer, "result_queue": result_queue}
61
+
62
+ thread = Thread(
63
+ target=moondream.answer_question,
64
+ args=thread_args,
65
+ kwargs=thread_kwargs,
66
+ )
67
+ thread.start()
68
+
69
+ buffer = ""
70
+ for new_text in streamer:
71
+ buffer += new_text
72
+ if not new_text.endswith("<") and not new_text.endswith("END"):
73
+ print(buffer, end="", flush=True)
74
+ buffer = ""
75
+ print(buffer)
76
+
77
+ thread.join()
78
+
79
+ answer = result_queue.get()
80
+ chat_history += f"Question: {question}\n\nAnswer: {answer}\n\n"
81
+ else:
82
+ print(">", prompt)
83
+ answer = moondream.answer_question(image_embeds, prompt, tokenizer)
84
+ print(answer)
webcam_gradio_demo.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import time
3
+ from threading import Thread
4
+
5
+ import gradio as gr
6
+ import torch
7
+ from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
8
+
9
+ from moondream.hf import LATEST_REVISION, detect_device
10
+
11
+ parser = argparse.ArgumentParser()
12
+ parser.add_argument("--cpu", action="store_true")
13
+ args = parser.parse_args()
14
+
15
+ if args.cpu:
16
+ device = torch.device("cpu")
17
+ dtype = torch.float32
18
+ else:
19
+ device, dtype = detect_device()
20
+ if device != torch.device("cpu"):
21
+ print("Using device:", device)
22
+ print("If you run into issues, pass the `--cpu` flag to this script.")
23
+ print()
24
+
25
+ model_id = "vikhyatk/moondream2"
26
+ tokenizer = AutoTokenizer.from_pretrained(model_id, revision=LATEST_REVISION)
27
+ moondream = AutoModelForCausalLM.from_pretrained(
28
+ model_id, trust_remote_code=True, revision=LATEST_REVISION
29
+ ).to(device=device, dtype=dtype)
30
+ moondream.eval()
31
+
32
+
33
+ def answer_question(img, prompt):
34
+ image_embeds = moondream.encode_image(img)
35
+ streamer = TextIteratorStreamer(tokenizer, skip_special_tokens=True)
36
+ thread = Thread(
37
+ target=moondream.answer_question,
38
+ kwargs={
39
+ "image_embeds": image_embeds,
40
+ "question": prompt,
41
+ "tokenizer": tokenizer,
42
+ "streamer": streamer,
43
+ },
44
+ )
45
+ thread.start()
46
+
47
+ buffer = ""
48
+ for new_text in streamer:
49
+ buffer += new_text
50
+ yield buffer
51
+
52
+
53
+ with gr.Blocks() as demo:
54
+ gr.Markdown("# See For Me")
55
+
56
+ gr.HTML(
57
+ """
58
+ <style type="text/css">
59
+ .md_output p {
60
+ padding-top: 1rem;
61
+ font-size: 1.2rem !important;
62
+ }
63
+ </style>
64
+ """
65
+ )
66
+
67
+ with gr.Row():
68
+ prompt = gr.Textbox(
69
+ label="Prompt",
70
+ value="What's going on? Respond with a single sentence.",
71
+ interactive=True,
72
+ )
73
+ with gr.Row():
74
+ img = gr.Image(type="pil", label="Upload an Image", streaming=True)
75
+ output = gr.Markdown(elem_classes=["md_output"])
76
+
77
+ latest_img = None
78
+ latest_prompt = prompt.value
79
+
80
+ @img.change(inputs=[img])
81
+ def img_change(img):
82
+ global latest_img
83
+ latest_img = img
84
+
85
+ @prompt.change(inputs=[prompt])
86
+ def prompt_change(prompt):
87
+ global latest_prompt
88
+ latest_prompt = prompt
89
+
90
+ @demo.load(outputs=[output])
91
+ def live_video():
92
+ while True:
93
+ if latest_img is None:
94
+ time.sleep(0.1)
95
+ else:
96
+ for text in answer_question(latest_img, latest_prompt):
97
+ if len(text) > 0:
98
+ yield text
99
+
100
+
101
+ demo.queue().launch(debug=True, share=True)