Views
No views yet
1from transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig
2from PIL import Image
3import requests
4import torch
5
6# Can also be a local path if you have already cloned the hugging face repo
7MODEL_PATH = "Scoolar/Molmo-7B-D-0924-NF4"
8
9# load the processor
10processor = AutoProcessor.from_pretrained(
11 MODEL_PATH,
12 trust_remote_code=True,
13 device_map='auto'
14)
15
16# load the model
17model = AutoModelForCausalLM.from_pretrained(
18 MODEL_PATH,
19 trust_remote_code=True,
20 device_map='auto',
21)
22
23# process the image and text
24inputs = processor.process(
25 images=[Image.open(requests.get("https://picsum.photos/id/237/536/354", stream=True).raw)],
26 text="Describe this image."
27)
28
29# move inputs to the correct device and make a batch of size 1
30inputs = {k: v.to(model.device).unsqueeze(0) for k, v in inputs.items()}
31
32# Compute is done in float16, while most weights are NF4
33with torch.autocast(device_type="cuda", enabled=True, dtype=torch.float16):
34 output = model.generate_from_batch(
35 inputs,
36 GenerationConfig(max_new_tokens=200, stop_strings="<|endoftext|>"),
37 tokenizer=processor.tokenizer
38 )
39
40# only get generated tokens; decode them to text
41generated_tokens = output[0, inputs['input_ids'].size(1):]
42generated_text = processor.tokenizer.decode(generated_tokens, skip_special_tokens=True)
43
44# print the generated text
45print(generated_text)config.json.config.json (quantization_config)1from transformers import AutoModelForCausalLM, BitsAndBytesConfig
2import torch
3
4# Can also be a local path if you have already cloned the hugginface repo
5MODEL_PATH = "allenai/Molmo-7B-D-0924"
6YOUR_OUTPUT_PATH = "enter_local_model_output_path"
7
8DEFAULT_DTYPE = torch.float16
9
10nf4_config = BitsAndBytesConfig(
11 load_in_4bit=True,
12 bnb_4bit_quant_type="nf4",
13 bnb_4bit_compute_dtype=DEFAULT_DTYPE,
14 llm_int8_skip_modules=[
15 # Module names can also be relative like "ff_norm" which would apply to all such layers
16 "model.vision_backbone", "model.transformer.ff_out", "model.transformer.ln_f"
17 ]
18)
19
20# load the model
21model = AutoModelForCausalLM.from_pretrained(
22 MODEL_PATH,
23 trust_remote_code=True,
24 device_map='auto',
25 torch_dtype=DEFAULT_DTYPE,
26 quantization_config=nf4_config,
27)
28
29# Save model
30model.save_pretrained(
31 save_directory=YOUR_OUTPUT_PATH,
32 safe_serialization=True,
33 # Set a maximum shard size if you don't like the default
34 max_shard_size="4GB"
35)model.safetensors.index.json or analyzed in more detail in modeling_molmo.py.