longlian commited on
Commit
c62168d
·
0 Parent(s):

Initial commit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +35 -0
  2. README.md +12 -0
  3. app.py +165 -0
  4. dam/.DS_Store +0 -0
  5. dam/__init__.py +2 -0
  6. dam/__pycache__/__init__.cpython-310.pyc +0 -0
  7. dam/__pycache__/describe_anything_model.cpython-310.pyc +0 -0
  8. dam/describe_anything_model.py +212 -0
  9. dam/model/__init__.py +4 -0
  10. dam/model/__pycache__/__init__.cpython-310.pyc +0 -0
  11. dam/model/__pycache__/configuration_llava.cpython-310.pyc +0 -0
  12. dam/model/__pycache__/constants.cpython-310.pyc +0 -0
  13. dam/model/__pycache__/conversation.cpython-310.pyc +0 -0
  14. dam/model/__pycache__/llava_arch.cpython-310.pyc +0 -0
  15. dam/model/__pycache__/mm_utils.cpython-310.pyc +0 -0
  16. dam/model/__pycache__/model_utils.cpython-310.pyc +0 -0
  17. dam/model/__pycache__/utils.cpython-310.pyc +0 -0
  18. dam/model/builder_ignored.py +260 -0
  19. dam/model/configuration_llava.py +55 -0
  20. dam/model/consolidate.py +29 -0
  21. dam/model/constants.py +32 -0
  22. dam/model/conversation.py +474 -0
  23. dam/model/language_model/__pycache__/builder.cpython-310.pyc +0 -0
  24. dam/model/language_model/__pycache__/llava_llama.cpython-310.pyc +0 -0
  25. dam/model/language_model/__pycache__/llava_mistral.cpython-310.pyc +0 -0
  26. dam/model/language_model/builder.py +111 -0
  27. dam/model/language_model/llava_gemma_ignored.py +161 -0
  28. dam/model/language_model/llava_llama.py +180 -0
  29. dam/model/language_model/llava_mistral_ignored.py +145 -0
  30. dam/model/language_model/llava_mpt_ignored.py +115 -0
  31. dam/model/language_model/mpt_ignored/adapt_tokenizer.py +41 -0
  32. dam/model/language_model/mpt_ignored/attention.py +300 -0
  33. dam/model/language_model/mpt_ignored/blocks.py +41 -0
  34. dam/model/language_model/mpt_ignored/configuration_mpt.py +118 -0
  35. dam/model/language_model/mpt_ignored/custom_embedding.py +11 -0
  36. dam/model/language_model/mpt_ignored/flash_attn_triton.py +484 -0
  37. dam/model/language_model/mpt_ignored/hf_prefixlm_converter.py +415 -0
  38. dam/model/language_model/mpt_ignored/meta_init_context.py +94 -0
  39. dam/model/language_model/mpt_ignored/modeling_mpt.py +331 -0
  40. dam/model/language_model/mpt_ignored/norm.py +56 -0
  41. dam/model/language_model/mpt_ignored/param_init_fns.py +181 -0
  42. dam/model/llava_arch.py +676 -0
  43. dam/model/mm_utils.py +312 -0
  44. dam/model/model_utils.py +268 -0
  45. dam/model/multimodal_encoder/__pycache__/builder.cpython-310.pyc +0 -0
  46. dam/model/multimodal_encoder/__pycache__/context_provider.cpython-310.pyc +0 -0
  47. dam/model/multimodal_encoder/__pycache__/siglip_encoder.cpython-310.pyc +0 -0
  48. dam/model/multimodal_encoder/__pycache__/vision_encoder.cpython-310.pyc +0 -0
  49. dam/model/multimodal_encoder/builder.py +54 -0
  50. dam/model/multimodal_encoder/clip_encoder_ignored.py +19 -0
.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Describe Anything
3
+ emoji: ⚡
4
+ colorFrom: yellow
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 5.7.1
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ os.environ["GRADIO_SSR_MODE"] = "false"
3
+
4
+ if not os.path.exists("checkpoints"):
5
+ os.makedirs("checkpoints")
6
+ os.system("pip install gdown")
7
+ os.system("gdown https://drive.google.com/uc?id=1eQe6blJcyI7oy78C8ozwj1IUkbkFEItf; unzip -o dam_3b_v1.zip -d checkpoints")
8
+
9
+ from segment_anything import sam_model_registry, SamPredictor
10
+ import gradio as gr
11
+ import numpy as np
12
+ import cv2
13
+ import base64
14
+ import torch
15
+ from PIL import Image
16
+ import io
17
+ import argparse
18
+ from fastapi import FastAPI
19
+ from fastapi.staticfiles import StaticFiles
20
+ from transformers import SamModel, SamProcessor
21
+ from dam import DescribeAnythingModel, disable_torch_init
22
+ try:
23
+ from spaces import GPU
24
+ except ImportError:
25
+ print("Spaces not installed, using dummy GPU decorator")
26
+ GPU = lambda fn: fn
27
+
28
+ # Load SAM model
29
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
30
+ sam_model = SamModel.from_pretrained("facebook/sam-vit-huge").to(device)
31
+ sam_processor = SamProcessor.from_pretrained("facebook/sam-vit-huge")
32
+
33
+ @GPU(duration=75)
34
+ def image_to_sam_embedding(base64_image):
35
+ try:
36
+ # Decode base64 string to bytes
37
+ image_bytes = base64.b64decode(base64_image)
38
+
39
+ # Convert bytes to PIL Image
40
+ image = Image.open(io.BytesIO(image_bytes))
41
+
42
+ # Process image with SAM processor
43
+ inputs = sam_processor(image, return_tensors="pt").to(device)
44
+
45
+ # Get image embedding
46
+ with torch.no_grad():
47
+ image_embedding = sam_model.get_image_embeddings(inputs["pixel_values"])
48
+
49
+ # Convert to CPU and numpy
50
+ image_embedding = image_embedding.cpu().numpy()
51
+
52
+ # Encode the embedding as base64
53
+ embedding_bytes = image_embedding.tobytes()
54
+ embedding_base64 = base64.b64encode(embedding_bytes).decode('utf-8')
55
+
56
+ return embedding_base64
57
+ except Exception as e:
58
+ print(f"Error processing image: {str(e)}")
59
+ raise gr.Error(f"Failed to process image: {str(e)}")
60
+
61
+ @GPU(duration=75)
62
+ def describe(image_base64: str, mask_base64: str, query: str):
63
+ # Convert base64 to PIL Image
64
+ image_bytes = base64.b64decode(image_base64.split(',')[1] if ',' in image_base64 else image_base64)
65
+ img = Image.open(io.BytesIO(image_bytes))
66
+ mask_bytes = base64.b64decode(mask_base64.split(',')[1] if ',' in mask_base64 else mask_base64)
67
+ mask = Image.open(io.BytesIO(mask_bytes))
68
+
69
+ # Process the mask
70
+ mask = Image.fromarray((np.array(mask.convert('L')) > 0).astype(np.uint8) * 255)
71
+
72
+ # Get description using DAM with streaming
73
+ description_generator = dam.get_description(img, mask, query, streaming=True)
74
+
75
+ # Stream the tokens
76
+ text = ""
77
+ for token in description_generator:
78
+ text += token
79
+ yield text
80
+
81
+ @GPU(duration=75)
82
+ def describe_without_streaming(image_base64: str, mask_base64: str, query: str):
83
+ # Convert base64 to PIL Image
84
+ image_bytes = base64.b64decode(image_base64.split(',')[1] if ',' in image_base64 else image_base64)
85
+ img = Image.open(io.BytesIO(image_bytes))
86
+ mask_bytes = base64.b64decode(mask_base64.split(',')[1] if ',' in mask_base64 else mask_base64)
87
+ mask = Image.open(io.BytesIO(mask_bytes))
88
+
89
+ # Process the mask
90
+ mask = Image.fromarray((np.array(mask.convert('L')) > 0).astype(np.uint8) * 255)
91
+
92
+ # Get description using DAM
93
+ description = dam.get_description(img, mask, query)
94
+
95
+ return description
96
+
97
+ if __name__ == "__main__":
98
+ parser = argparse.ArgumentParser(description="Describe Anything gradio demo")
99
+ parser.add_argument("--model-path", type=str, default="checkpoints/dam_3b_v1", help="Path to the model checkpoint")
100
+ parser.add_argument("--prompt-mode", type=str, default="full+focal_crop", help="Prompt mode")
101
+ parser.add_argument("--conv-mode", type=str, default="v1", help="Conversation mode")
102
+ parser.add_argument("--temperature", type=float, default=0.2, help="Sampling temperature")
103
+ parser.add_argument("--top_p", type=float, default=0.5, help="Top-p for sampling")
104
+
105
+ args = parser.parse_args()
106
+
107
+ # Initialize DAM model
108
+ disable_torch_init()
109
+ dam = DescribeAnythingModel(
110
+ model_path=args.model_path,
111
+ conv_mode=args.conv_mode,
112
+ prompt_mode=args.prompt_mode,
113
+ temperature=args.temperature,
114
+ top_p=args.top_p,
115
+ num_beams=1,
116
+ max_new_tokens=512,
117
+ ).to(device)
118
+
119
+ # Create Gradio interface
120
+ with gr.Blocks() as demo:
121
+ gr.Interface(
122
+ fn=image_to_sam_embedding,
123
+ inputs=gr.Textbox(label="Image Base64"),
124
+ outputs=gr.Textbox(label="Embedding Base64"),
125
+ title="Image Embedding Generator",
126
+ api_name="image_to_sam_embedding"
127
+ )
128
+ gr.Interface(
129
+ fn=describe,
130
+ inputs=[
131
+ gr.Textbox(label="Image Base64"),
132
+ gr.Text(label="Mask Base64"),
133
+ gr.Text(label="Prompt")
134
+ ],
135
+ outputs=[
136
+ gr.Text(label="Description")
137
+ ],
138
+ title="Mask Description Generator",
139
+ api_name="describe"
140
+ )
141
+ gr.Interface(
142
+ fn=describe_without_streaming,
143
+ inputs=[
144
+ gr.Textbox(label="Image Base64"),
145
+ gr.Text(label="Mask Base64"),
146
+ gr.Text(label="Prompt")
147
+ ],
148
+ outputs=[
149
+ gr.Text(label="Description")
150
+ ],
151
+ title="Mask Description Generator (Non-Streaming)",
152
+ api_name="describe_without_streaming"
153
+ )
154
+
155
+ demo._block_thread = demo.block_thread
156
+ demo.block_thread = lambda: None
157
+ demo.launch()
158
+
159
+ for route in demo.app.routes:
160
+ if route.path == "/":
161
+ # demo.app.routes.remove(route)
162
+ route.path = "/gradio"
163
+ demo.app.mount("/", StaticFiles(directory="dist", html=True), name="demo")
164
+
165
+ demo._block_thread()
dam/.DS_Store ADDED
Binary file (6.15 kB). View file
 
dam/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .describe_anything_model import *
2
+ from .model import *
dam/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (203 Bytes). View file
 
dam/__pycache__/describe_anything_model.cpython-310.pyc ADDED
Binary file (7.27 kB). View file
 
dam/describe_anything_model.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import numpy as np
4
+ from PIL import Image
5
+ from .model.constants import DEFAULT_IMAGE_TOKEN, IMAGE_TOKEN_INDEX
6
+ from .model.conversation import SeparatorStyle, conv_templates
7
+ from .model.mm_utils import KeywordsStoppingCriteria, process_image, tokenizer_image_token
8
+ from .model import get_model_name_from_path, load_pretrained_model
9
+ from transformers import TextIteratorStreamer
10
+ from threading import Thread
11
+
12
+ class DescribeAnythingModel(nn.Module):
13
+ def __init__(self, model_path, conv_mode, prompt_mode, temperature, top_p, num_beams, max_new_tokens, **kwargs):
14
+ super().__init__()
15
+
16
+ self.model_path = model_path
17
+ self.conv_mode = conv_mode
18
+ self.prompt_mode = prompt_mode
19
+ self.temperature = temperature
20
+ self.top_p = top_p
21
+ self.num_beams = num_beams
22
+ self.max_new_tokens = max_new_tokens
23
+
24
+ tokenizer, model, image_processor, context_len = load_pretrained_model(model_path, None, None, **kwargs)
25
+ model.config.image_processor = image_processor
26
+
27
+ self.tokenizer = tokenizer
28
+ self.model = model
29
+ self.context_len = context_len
30
+
31
+ self.model_name = get_model_name_from_path(model_path)
32
+
33
+ def get_prompt(self, qs):
34
+ if DEFAULT_IMAGE_TOKEN not in qs:
35
+ raise ValueError("no <image> tag found in input.")
36
+
37
+ conv = conv_templates[self.conv_mode].copy()
38
+ conv.append_message(conv.roles[0], qs)
39
+ conv.append_message(conv.roles[1], None)
40
+ prompt = conv.get_prompt()
41
+
42
+ return prompt, conv
43
+
44
+ @staticmethod
45
+ def mask_to_box(mask_np):
46
+ mask_coords = np.argwhere(mask_np)
47
+ y0, x0 = mask_coords.min(axis=0)
48
+ y1, x1 = mask_coords.max(axis=0) + 1
49
+
50
+ h = y1 - y0
51
+ w = x1 - x0
52
+
53
+ return x0, y0, w, h
54
+
55
+ @classmethod
56
+ def crop_image(cls, pil_img, mask_np, crop_mode, min_box_w=48, min_box_h=48):
57
+ if crop_mode == "full":
58
+ # no crop
59
+ info = dict(mask_np=mask_np)
60
+ return pil_img, info
61
+
62
+ if crop_mode == "crop":
63
+ # crop image and mask
64
+ x0, y0, w, h = cls.mask_to_box(mask_np)
65
+ img_np = np.asarray(pil_img)
66
+ assert img_np.shape[:2] == mask_np.shape, f"image shape mismatches with mask shape: {img_np.shape}, {mask_np.shape}"
67
+ cropped_mask_np = mask_np[y0:y0+h, x0:x0+w]
68
+ cropped_img_np = img_np[y0:y0+h, x0:x0+w]
69
+ cropped_pil_img = Image.fromarray(cropped_img_np)
70
+ elif crop_mode == "context_crop":
71
+ # crop image and mask
72
+ x0, y0, w, h = cls.mask_to_box(mask_np)
73
+ img_np = np.asarray(pil_img)
74
+ assert img_np.shape[:2] == mask_np.shape, f"image shape mismatches with mask shape: {img_np.shape}, {mask_np.shape}"
75
+ img_h, img_w = img_np.shape[:2]
76
+ cropped_mask_np = mask_np[max(y0-h, 0):min(y0+2*h, img_h), max(x0-w, 0):min(x0+2*w, img_w)]
77
+ cropped_img_np = img_np[max(y0-h, 0):min(y0+2*h, img_h), max(x0-w, 0):min(x0+2*w, img_w)]
78
+ cropped_pil_img = Image.fromarray(cropped_img_np)
79
+ elif crop_mode == "focal_crop":
80
+ # crop image and mask
81
+ x0, y0, w, h = cls.mask_to_box(mask_np)
82
+ img_np = np.asarray(pil_img)
83
+ assert img_np.shape[:2] == mask_np.shape, f"image shape mismatches with mask shape: {img_np.shape}, {mask_np.shape}"
84
+ img_h, img_w = img_np.shape[:2]
85
+
86
+ xc, yc = x0 + w/2, y0 + h/2
87
+ # focal_crop: need to have at least min_box_w and min_box_h pixels, otherwise resizing to (384, 384) leads to artifacts that may be OOD
88
+ w, h = max(w, min_box_w), max(h, min_box_h)
89
+ x0, y0 = int(xc - w / 2), int(yc - h / 2)
90
+
91
+ cropped_mask_np = mask_np[max(y0-h, 0):min(y0+2*h, img_h), max(x0-w, 0):min(x0+2*w, img_w)]
92
+ cropped_img_np = img_np[max(y0-h, 0):min(y0+2*h, img_h), max(x0-w, 0):min(x0+2*w, img_w)]
93
+ cropped_pil_img = Image.fromarray(cropped_img_np)
94
+ elif crop_mode == "crop_mask":
95
+ # crop image and mask
96
+ x0, y0, w, h = cls.mask_to_box(mask_np)
97
+ img_np = np.asarray(pil_img)
98
+ assert img_np.shape[:2] == mask_np.shape, f"image shape mismatches with mask shape: {img_np.shape}, {mask_np.shape}"
99
+ cropped_mask_np = mask_np[y0:y0+h, x0:x0+w]
100
+ cropped_img_np = img_np[y0:y0+h, x0:x0+w]
101
+ # Mask the image
102
+ cropped_img_np = cropped_img_np * cropped_mask_np[..., None]
103
+ cropped_pil_img = Image.fromarray(cropped_img_np)
104
+ else:
105
+ raise ValueError(f"Unsupported crop_mode: {crop_mode}")
106
+
107
+ info = dict(mask_np=cropped_mask_np)
108
+ return cropped_pil_img, info
109
+
110
+ def get_description(self, image_pil, mask_pil, query, streaming=False):
111
+ prompt, conv = self.get_prompt(query)
112
+ if not isinstance(image_pil, (list, tuple)):
113
+ assert not isinstance(mask_pil, (list, tuple)), "image_pil and mask_pil must be both list or tuple or not list or tuple."
114
+ image_pils = [image_pil]
115
+ mask_pils = [mask_pil]
116
+ else:
117
+ image_pils = image_pil
118
+ mask_pils = mask_pil
119
+ description = self.get_description_from_prompt(image_pils, mask_pils, prompt, conv, streaming=streaming)
120
+
121
+ return description
122
+
123
+ def get_image_tensor(self, image_pil, mask_pil, crop_mode, crop_mode2):
124
+ # the pil has True/False (if the value is non-zero, then we treat it as True)
125
+ mask_np = (np.asarray(mask_pil) > 0).astype(np.uint8)
126
+ images_tensor, image_info = process_image(image_pil, self.model.config, None, pil_preprocess_fn=lambda pil_img: self.crop_image(image_pil, mask_np=mask_np, crop_mode=crop_mode))
127
+ images_tensor = images_tensor[None].to(self.model.device, dtype=torch.float16)
128
+
129
+ mask_np = image_info["mask_np"]
130
+ mask_pil = Image.fromarray(mask_np * 255)
131
+
132
+ masks_tensor = process_image(mask_pil, self.model.config, None)
133
+ masks_tensor = masks_tensor[None].to(self.model.device, dtype=torch.float16)
134
+
135
+ images_tensor = torch.cat((images_tensor, masks_tensor[:, :1, ...]), dim=1)
136
+
137
+ if crop_mode2 is not None:
138
+ images_tensor2, image_info2 = process_image(image_pil, self.model.config, None, pil_preprocess_fn=lambda pil_img: self.crop_image(pil_img, mask_np=mask_np, crop_mode=crop_mode2))
139
+ images_tensor2 = images_tensor2[None].to(self.model.device, dtype=torch.float16)
140
+
141
+ mask_np2 = image_info2["mask_np"]
142
+ mask_pil2 = Image.fromarray(mask_np2 * 255)
143
+
144
+ masks_tensor2 = process_image(mask_pil2, self.model.config, None)
145
+ masks_tensor2 = masks_tensor2[None].to(self.model.device, dtype=torch.float16)
146
+
147
+ images_tensor2 = torch.cat((images_tensor2, masks_tensor2[:, :1, ...]), dim=1)
148
+ else:
149
+ images_tensor2 = None
150
+
151
+ return torch.cat((images_tensor, images_tensor2), dim=1) if images_tensor2 is not None else images_tensor
152
+
153
+ def get_description_from_prompt(self, image_pils, mask_pils, prompt, conv, streaming=False):
154
+ if streaming:
155
+ return self.get_description_from_prompt_iterator(image_pils, mask_pils, prompt, conv, streaming=True)
156
+ else:
157
+ # If streaming is False, there will be only one output
158
+ output = self.get_description_from_prompt_iterator(image_pils, mask_pils, prompt, conv, streaming=False)
159
+ return next(output)
160
+
161
+ def get_description_from_prompt_iterator(self, image_pils, mask_pils, prompt, conv, streaming=False):
162
+ crop_mode, crop_mode2 = self.prompt_mode.split("+")
163
+ assert crop_mode == "full", "Current prompt only supports first crop as full (non-cropped). If you need other specifications, please update the prompt."
164
+
165
+ assert len(image_pils) == len(mask_pils), f"image_pils and mask_pils must have the same length. Got {len(image_pils)} and {len(mask_pils)}."
166
+ image_tensors = [self.get_image_tensor(image_pil, mask_pil, crop_mode=crop_mode, crop_mode2=crop_mode2) for image_pil, mask_pil in zip(image_pils, mask_pils)]
167
+
168
+ input_ids = tokenizer_image_token(prompt, self.tokenizer, IMAGE_TOKEN_INDEX, return_tensors="pt").unsqueeze(0).cuda()
169
+
170
+ stop_str = conv.sep if conv.sep_style != SeparatorStyle.TWO else conv.sep2
171
+ keywords = [stop_str]
172
+ stopping_criteria = KeywordsStoppingCriteria(keywords, self.tokenizer, input_ids)
173
+
174
+ streamer = TextIteratorStreamer(self.tokenizer, skip_prompt=True, skip_special_tokens=True) if streaming else None
175
+ generation_kwargs = dict(
176
+ input_ids=input_ids,
177
+ images=image_tensors,
178
+ do_sample=True if self.temperature > 0 else False,
179
+ temperature=self.temperature,
180
+ top_p=self.top_p,
181
+ num_beams=self.num_beams,
182
+ max_new_tokens=self.max_new_tokens,
183
+ use_cache=True,
184
+ stopping_criteria=[stopping_criteria],
185
+ streamer=streamer
186
+ )
187
+
188
+
189
+ if streaming:
190
+ thread = Thread(target=self.model.generate, kwargs=generation_kwargs)
191
+ thread.start()
192
+
193
+ generated_text = ""
194
+ for new_text in streamer:
195
+ generated_text += new_text
196
+ if stop_str in generated_text:
197
+ generated_text = generated_text[:generated_text.find(stop_str)]
198
+ break
199
+ yield new_text
200
+
201
+ thread.join()
202
+ else:
203
+ with torch.inference_mode():
204
+ output_ids = self.model.generate(**generation_kwargs)
205
+
206
+ outputs = self.tokenizer.batch_decode(output_ids, skip_special_tokens=True)[0]
207
+ outputs = outputs.strip()
208
+ if outputs.endswith(stop_str):
209
+ outputs = outputs[: -len(stop_str)]
210
+ outputs = outputs.strip()
211
+
212
+ yield outputs
dam/model/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .constants import *
2
+ from .conversation import *
3
+ from .mm_utils import *
4
+ from .model_utils import *
dam/model/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (241 Bytes). View file
 
dam/model/__pycache__/configuration_llava.cpython-310.pyc ADDED
Binary file (1.33 kB). View file
 
dam/model/__pycache__/constants.cpython-310.pyc ADDED
Binary file (536 Bytes). View file
 
dam/model/__pycache__/conversation.cpython-310.pyc ADDED
Binary file (11.5 kB). View file
 
dam/model/__pycache__/llava_arch.cpython-310.pyc ADDED
Binary file (16.2 kB). View file
 
dam/model/__pycache__/mm_utils.cpython-310.pyc ADDED
Binary file (8.51 kB). View file
 
dam/model/__pycache__/model_utils.cpython-310.pyc ADDED
Binary file (6.34 kB). View file
 
dam/model/__pycache__/utils.cpython-310.pyc ADDED
Binary file (2.53 kB). View file
 
dam/model/builder_ignored.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
2
+ # Copyright 2023 Haotian Liu
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ import os
18
+ import warnings
19
+ import shutil
20
+
21
+ from transformers import (
22
+ AutoTokenizer,
23
+ AutoModelForCausalLM,
24
+ AutoConfig,
25
+ BitsAndBytesConfig,
26
+ PretrainedConfig,
27
+ PreTrainedModel,
28
+ )
29
+ import torch
30
+ from llava.model import *
31
+ from llava.model.utils import is_mm_model
32
+ from llava.model.language_model.llava_llama import LlavaConfig
33
+ from llava.constants import (
34
+ DEFAULT_IMAGE_PATCH_TOKEN,
35
+ DEFAULT_IM_START_TOKEN,
36
+ DEFAULT_IM_END_TOKEN,
37
+ )
38
+
39
+ def load_pretrained_model(
40
+ model_path,
41
+ model_name,
42
+ model_base=None,
43
+ load_8bit=False,
44
+ load_4bit=False,
45
+ device_map="auto",
46
+ device="cuda",
47
+ **kwargs,
48
+ ):
49
+ kwargs = {"device_map": device_map, **kwargs}
50
+
51
+ if device != "cuda":
52
+ kwargs["device_map"] = {"": device}
53
+
54
+ if load_8bit:
55
+ kwargs["load_in_8bit"] = True
56
+ elif load_4bit:
57
+ kwargs["load_in_4bit"] = True
58
+ kwargs["quantization_config"] = BitsAndBytesConfig(
59
+ load_in_4bit=True,
60
+ bnb_4bit_compute_dtype=torch.float16,
61
+ bnb_4bit_use_double_quant=True,
62
+ bnb_4bit_quant_type="nf4",
63
+ )
64
+ else:
65
+ kwargs["torch_dtype"] = torch.float16
66
+
67
+ if is_mm_model(model_path):
68
+ # Load LLaVA model
69
+ ## TODO @yunhao: mind fixing lora
70
+ if "lora" in model_name.lower() and model_base is None:
71
+ warnings.warn(
72
+ "There is `lora` in model name but no `model_base` is provided. If you are loading a LoRA model, please provide the `model_base` argument. Detailed instruction: https://github.com/haotian-liu/LLaVA#launch-a-model-worker-lora-weights-unmerged."
73
+ )
74
+ if "lora" in model_name.lower() and model_base is not None:
75
+ lora_cfg_pretrained = AutoConfig.from_pretrained(model_path)
76
+ tokenizer = AutoTokenizer.from_pretrained(
77
+ model_base, use_fast=False, legacy=False
78
+ )
79
+ print("Loading LLaVA from base model...")
80
+ model = LlavaLlamaForCausalLM.from_pretrained(
81
+ model_base, low_cpu_mem_usage=True, config=lora_cfg_pretrained, **kwargs
82
+ )
83
+ token_num, tokem_dim = model.lm_head.out_features, model.lm_head.in_features
84
+ if model.lm_head.weight.shape[0] != token_num:
85
+ model.lm_head.weight = torch.nn.Parameter(
86
+ torch.empty(
87
+ token_num, tokem_dim, device=model.device, dtype=model.dtype
88
+ )
89
+ )
90
+ model.model.embed_tokens.weight = torch.nn.Parameter(
91
+ torch.empty(
92
+ token_num, tokem_dim, device=model.device, dtype=model.dtype
93
+ )
94
+ )
95
+
96
+ print("Loading additional LLaVA weights...")
97
+ if os.path.exists(os.path.join(model_path, "non_lora_trainables.bin")):
98
+ non_lora_trainables = torch.load(
99
+ os.path.join(model_path, "non_lora_trainables.bin"),
100
+ map_location="cpu",
101
+ )
102
+ else:
103
+ # this is probably from HF Hub
104
+ from huggingface_hub import hf_hub_download
105
+
106
+ def load_from_hf(repo_id, filename, subfolder=None):
107
+ cache_file = hf_hub_download(
108
+ repo_id=repo_id, filename=filename, subfolder=subfolder
109
+ )
110
+ return torch.load(cache_file, map_location="cpu")
111
+
112
+ non_lora_trainables = load_from_hf(
113
+ model_path, "non_lora_trainables.bin"
114
+ )
115
+ non_lora_trainables = {
116
+ (k[11:] if k.startswith("base_model.") else k): v
117
+ for k, v in non_lora_trainables.items()
118
+ }
119
+ if any(k.startswith("model.model.") for k in non_lora_trainables):
120
+ non_lora_trainables = {
121
+ (k[6:] if k.startswith("model.") else k): v
122
+ for k, v in non_lora_trainables.items()
123
+ }
124
+ model.load_state_dict(non_lora_trainables, strict=False)
125
+
126
+ from peft import PeftModel
127
+
128
+ print("Loading LoRA weights...")
129
+ model = PeftModel.from_pretrained(model, model_path)
130
+ print("Merging LoRA weights...")
131
+ model = model.merge_and_unload()
132
+ print("Model is loaded...")
133
+ ## TODO @yunhao: mind fixing this
134
+ elif model_base is not None:
135
+ # this may be mm projector only
136
+ print("Loading LLaVA from base model...")
137
+ cfg_pretrained = AutoConfig.from_pretrained(
138
+ model_path, trust_remote_code=True
139
+ )
140
+ mm_config_wrapper(config, kwargs)
141
+ if "mpt" in model_name.lower():
142
+ if not os.path.isfile(os.path.join(model_path, "configuration_mpt.py")):
143
+ shutil.copyfile(
144
+ os.path.join(model_base, "configuration_mpt.py"),
145
+ os.path.join(model_path, "configuration_mpt.py"),
146
+ )
147
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=True)
148
+ model = LlavaMPTForCausalLM.from_pretrained(
149
+ model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs
150
+ )
151
+ else:
152
+ tokenizer = AutoTokenizer.from_pretrained(
153
+ model_base, use_fast=False, legacy=False
154
+ )
155
+ model = LlavaLlamaForCausalLM.from_pretrained(
156
+ model_base, low_cpu_mem_usage=True, config=cfg_pretrained, **kwargs
157
+ )
158
+ else:
159
+ config = AutoConfig.from_pretrained(model_path)
160
+ config.resume_path = model_path
161
+ prepare_config_for_eval(config, kwargs)
162
+ if "mpt" in model_name.lower():
163
+ model = LlavaMPTForCausalLM.from_pretrained(
164
+ model_path, config=config, low_cpu_mem_usage=True, **kwargs
165
+ )
166
+ elif "mistral" in model_name.lower() or "mixtral" in model_name.lower():
167
+ model = LlavaMistralForCausalLM.from_pretrained(
168
+ model_path, config=config, low_cpu_mem_usage=True, **kwargs
169
+ )
170
+ elif "gemma" in model_name.lower():
171
+ model = LlavaGemmaForCausalLM.from_pretrained(
172
+ model_path, config=config, low_cpu_mem_usage=True, **kwargs
173
+ )
174
+ else:
175
+ # kentang-mit@: llama-2 model
176
+ # config._attn_implementation = "flash_attention_2"
177
+ model = LlavaLlamaModel(
178
+ config=config,
179
+ low_cpu_mem_usage=True,
180
+ **kwargs
181
+ )
182
+ tokenizer = model.tokenizer
183
+ else:
184
+ # Load language model
185
+ if model_base is not None:
186
+ # PEFT model
187
+ from peft import PeftModel
188
+
189
+ tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
190
+ model = AutoModelForCausalLM.from_pretrained(
191
+ model_base, low_cpu_mem_usage=True, **kwargs
192
+ )
193
+ print(f"Loading LoRA weights from {model_path}")
194
+ model = PeftModel.from_pretrained(model, model_path)
195
+ print(f"Merging weights")
196
+ model = model.merge_and_unload()
197
+ print("Convert to FP16...")
198
+ model.to(torch.float16)
199
+ else:
200
+ if "mpt" in model_name.lower():
201
+ tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
202
+ model = AutoModelForCausalLM.from_pretrained(
203
+ model_path, low_cpu_mem_usage=True, trust_remote_code=True, **kwargs
204
+ )
205
+ else:
206
+ tokenizer = AutoTokenizer.from_pretrained(
207
+ model_path, use_fast=False, legacy=False
208
+ )
209
+ model = AutoModelForCausalLM.from_pretrained(
210
+ model_path, low_cpu_mem_usage=True, **kwargs
211
+ )
212
+ model.eval()
213
+ image_processor = None
214
+ if is_mm_model(model_path):
215
+ mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False)
216
+ mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True)
217
+ if mm_use_im_patch_token:
218
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
219
+ if mm_use_im_start_end:
220
+ tokenizer.add_tokens(
221
+ [DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True
222
+ )
223
+ model.resize_token_embeddings(len(tokenizer))
224
+ vision_tower = model.get_vision_tower()
225
+ vision_tower.to(device=device, dtype=torch.float16)
226
+ mm_projector = model.get_mm_projector()
227
+ mm_projector.to(device=device, dtype=torch.float16)
228
+ image_processor = vision_tower.image_processor
229
+
230
+ if hasattr(model.llm.config, "max_sequence_length"):
231
+ context_len = model.config.max_sequence_length
232
+ else:
233
+ context_len = 2048
234
+
235
+ return tokenizer, model, image_processor, context_len
236
+
237
+ def parse_model_name_or_path(config: PretrainedConfig, model_name="llm", suffix="_cfg"):
238
+ target_model = f"{model_name}{suffix}"
239
+ target_cfg = getattr(config, target_model, None)
240
+
241
+ if isinstance(target_cfg, str):
242
+ return target_cfg
243
+ elif isinstance(target_cfg, dict):
244
+ return target_cfg["architectures"][0]
245
+ else:
246
+ raise ValueError(f"Invalid {target_model} configuration!")
247
+
248
+ def prepare_config_for_eval(config: PretrainedConfig, kwargs: dict):
249
+ try:
250
+ # compatible with deprecated config convention
251
+ if getattr(config, "vision_tower_cfg", None) is None:
252
+ config.vision_tower_cfg = config.mm_vision_tower
253
+ except AttributeError:
254
+ raise ValueError(f"Invalid configuration! Cannot find vision_tower in config:\n{config}")
255
+
256
+ config.model_dtype = kwargs.pop("torch_dtype").__str__()
257
+ # siglip does not support device_map = "auto"
258
+ vision_tower_name = parse_model_name_or_path(config, "vision_tower")
259
+ if "siglip" in vision_tower_name.lower():
260
+ kwargs["device_map"] = "cuda"
dam/model/configuration_llava.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class LlavaConfig(PretrainedConfig):
5
+ model_type = "llava"
6
+
7
+ def __init__(
8
+ self,
9
+ llm_cfg=None,
10
+ vision_tower_cfg=None,
11
+ mm_projector_cfg=None,
12
+ mask_encoder_cfg=None,
13
+ context_provider_cfg=None,
14
+ architectures=None,
15
+ resume_path=None,
16
+ hidden_size=None,
17
+ mm_hidden_size=None,
18
+ image_aspect_ratio=None,
19
+ num_video_frames=None,
20
+ mm_vision_select_layer=None,
21
+ mm_vision_select_feature=None,
22
+ mm_use_im_start_end=False,
23
+ mm_use_im_patch_token=True,
24
+ mm_projector_lr=None,
25
+ vision_resolution=None,
26
+ interpolate_mode=None,
27
+ s2=None,
28
+ s2_scales=None,
29
+ s2_max_split_size=None,
30
+ **kwargs
31
+ ):
32
+ super().__init__()
33
+ self.architectures = architectures
34
+ self.llm_cfg = llm_cfg
35
+ self.vision_tower_cfg = vision_tower_cfg
36
+ self.mm_projector_cfg = mm_projector_cfg
37
+ self.mask_encoder_cfg = mask_encoder_cfg
38
+ self.context_provider_cfg = context_provider_cfg
39
+ self.resume_path = resume_path
40
+
41
+ self.hidden_size = hidden_size
42
+ self.mm_hidden_size = mm_hidden_size
43
+ self.image_aspect_ratio = image_aspect_ratio
44
+ self.num_video_frames = num_video_frames
45
+ self.mm_vision_select_layer = mm_vision_select_layer
46
+ self.mm_vision_select_feature = mm_vision_select_feature
47
+ self.mm_use_im_start_end = mm_use_im_start_end
48
+ self.mm_use_im_start_end = mm_use_im_start_end
49
+ self.mm_use_im_patch_token = mm_use_im_patch_token
50
+ self.mm_projector_lr = mm_projector_lr
51
+ self.vision_resolution = vision_resolution
52
+ self.interpolate_mode = interpolate_mode
53
+ self.s2 = s2
54
+ self.s2_scales = s2_scales
55
+ self.s2_max_split_size = s2_max_split_size
dam/model/consolidate.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Usage:
3
+ python3 -m llava.model.consolidate --src ~/model_weights/llava-7b --dst ~/model_weights/llava-7b_consolidate
4
+ """
5
+ import argparse
6
+
7
+ import torch
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM
9
+ from llava.model import *
10
+ from llava.model.utils import auto_upgrade
11
+
12
+
13
+ def consolidate_ckpt(src_path, dst_path):
14
+ print("Loading model")
15
+ auto_upgrade(src_path)
16
+ src_model = AutoModelForCausalLM.from_pretrained(src_path, torch_dtype=torch.float16, low_cpu_mem_usage=True)
17
+ src_tokenizer = AutoTokenizer.from_pretrained(src_path, use_fast=False)
18
+ src_model.save_pretrained(dst_path)
19
+ src_tokenizer.save_pretrained(dst_path)
20
+
21
+
22
+ if __name__ == "__main__":
23
+ parser = argparse.ArgumentParser()
24
+ parser.add_argument("--src", type=str, required=True)
25
+ parser.add_argument("--dst", type=str, required=True)
26
+
27
+ args = parser.parse_args()
28
+
29
+ consolidate_ckpt(args.src, args.dst)
dam/model/constants.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
17
+
18
+
19
+ CONTROLLER_HEART_BEAT_EXPIRATION = 30
20
+ WORKER_HEART_BEAT_INTERVAL = 15
21
+
22
+ LOGDIR = "."
23
+
24
+ # Model Constants
25
+ IGNORE_INDEX = -100
26
+ IMAGE_TOKEN_INDEX = -200
27
+ MASK_TOKEN_INDEX = -300
28
+ DEFAULT_IMAGE_TOKEN = "<image>"
29
+ DEFAULT_IMAGE_PATCH_TOKEN = "<im_patch>"
30
+ DEFAULT_IM_START_TOKEN = "<im_start>"
31
+ DEFAULT_IM_END_TOKEN = "<im_end>"
32
+ IMAGE_PLACEHOLDER = "<image-placeholder>"
dam/model/conversation.py ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
17
+
18
+
19
+ import dataclasses
20
+ from enum import auto, Enum
21
+ from typing import List, Tuple
22
+
23
+
24
+ class SeparatorStyle(Enum):
25
+ """Different separator style."""
26
+ SINGLE = auto()
27
+ TWO = auto()
28
+ MPT = auto()
29
+ PLAIN = auto()
30
+ LLAMA_2 = auto()
31
+ MISTRAL = auto()
32
+ LLAMA_3 = auto()
33
+
34
+
35
+ @dataclasses.dataclass
36
+ class Conversation:
37
+ """A class that keeps all conversation history."""
38
+ system: str
39
+ roles: List[str]
40
+ messages: List[List[str]]
41
+ offset: int
42
+ sep_style: SeparatorStyle = SeparatorStyle.SINGLE
43
+ sep: str = "###"
44
+ sep2: str = None
45
+ version: str = "Unknown"
46
+
47
+ skip_next: bool = False
48
+
49
+ def get_prompt(self):
50
+ messages = self.messages
51
+ if len(messages) > 0 and type(messages[0][1]) is tuple:
52
+ messages = self.messages.copy()
53
+ init_role, init_msg = messages[0].copy()
54
+ init_msg = init_msg[0].replace("<image>", "").strip()
55
+ if 'mmtag' in self.version:
56
+ messages[0] = (init_role, init_msg)
57
+ messages.insert(0, (self.roles[0], "<Image><image></Image>"))
58
+ messages.insert(1, (self.roles[1], "Received."))
59
+ else:
60
+ messages[0] = (init_role, "<image>\n" + init_msg)
61
+
62
+ if self.sep_style == SeparatorStyle.SINGLE:
63
+ ret = self.system + self.sep
64
+ for role, message in messages:
65
+ if message:
66
+ if type(message) is tuple:
67
+ message, _, _ = message
68
+ ret += role + ": " + message + self.sep
69
+ else:
70
+ ret += role + ":"
71
+ elif self.sep_style == SeparatorStyle.TWO:
72
+ seps = [self.sep, self.sep2]
73
+ ret = self.system + seps[0]
74
+ for i, (role, message) in enumerate(messages):
75
+ if message:
76
+ if type(message) is tuple:
77
+ message, _, _ = message
78
+ ret += role + ": " + message + seps[i % 2]
79
+ else:
80
+ ret += role + ":"
81
+ elif self.sep_style == SeparatorStyle.LLAMA_3:
82
+ ret = self.system + self.sep
83
+ for role, message in messages:
84
+ if message:
85
+ if type(message) is tuple:
86
+ message = message[0]
87
+ ret += role + message + self.sep
88
+ else:
89
+ ret += role
90
+ elif self.sep_style == SeparatorStyle.MPT:
91
+ ret = self.system + self.sep
92
+ for role, message in messages:
93
+ if message:
94
+ if type(message) is tuple:
95
+ message, _, _ = message
96
+ ret += role + message + self.sep
97
+ else:
98
+ ret += role
99
+ elif self.sep_style == SeparatorStyle.LLAMA_2 or self.sep_style == SeparatorStyle.MISTRAL:
100
+ if self.sep_style == SeparatorStyle.LLAMA_2:
101
+ wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n"
102
+ else:
103
+ wrap_sys = lambda msg: f"{msg}" + ("\n" if msg else "")
104
+ wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
105
+ ret = ""
106
+ if self.sep_style == SeparatorStyle.MISTRAL:
107
+ ret += "<s>"
108
+
109
+ for i, (role, message) in enumerate(messages):
110
+ if i == 0:
111
+ assert message, "first message should not be none"
112
+ assert role == self.roles[0], "first message should come from user"
113
+ if message:
114
+ if type(message) is tuple:
115
+ message, _, _ = message
116
+ if i == 0: message = wrap_sys(self.system) + message
117
+ if i % 2 == 0:
118
+ message = wrap_inst(message)
119
+ ret += self.sep + message
120
+ else:
121
+ if self.sep_style == SeparatorStyle.LLAMA_2:
122
+ ret += " " + message + " " + self.sep2
123
+ else:
124
+ ret += message + self.sep2
125
+ else:
126
+ ret += ""
127
+ ret = ret.lstrip(self.sep)
128
+ elif self.sep_style == SeparatorStyle.PLAIN:
129
+ seps = [self.sep, self.sep2]
130
+ ret = self.system
131
+ for i, (role, message) in enumerate(messages):
132
+ if message:
133
+ if type(message) is tuple:
134
+ message, _, _ = message
135
+ ret += message + seps[i % 2]
136
+ else:
137
+ ret += ""
138
+ else:
139
+ raise ValueError(f"Invalid style: {self.sep_style}")
140
+
141
+ return ret
142
+
143
+ def append_message(self, role, message):
144
+ self.messages.append([role, message])
145
+
146
+ def get_images(self, return_pil=False):
147
+ images = []
148
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
149
+ if i % 2 == 0:
150
+ if type(msg) is tuple:
151
+ import base64
152
+ from io import BytesIO
153
+ from PIL import Image
154
+ msg, image, image_process_mode = msg
155
+ if image_process_mode == "Pad":
156
+ def expand2square(pil_img, background_color=(122, 116, 104)):
157
+ width, height = pil_img.size
158
+ if width == height:
159
+ return pil_img
160
+ elif width > height:
161
+ result = Image.new(pil_img.mode, (width, width), background_color)
162
+ result.paste(pil_img, (0, (width - height) // 2))
163
+ return result
164
+ else:
165
+ result = Image.new(pil_img.mode, (height, height), background_color)
166
+ result.paste(pil_img, ((height - width) // 2, 0))
167
+ return result
168
+ image = expand2square(image)
169
+ elif image_process_mode in ["Default", "Crop"]:
170
+ pass
171
+ elif image_process_mode == "Resize":
172
+ image = image.resize((336, 336))
173
+ else:
174
+ raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
175
+ max_hw, min_hw = max(image.size), min(image.size)
176
+ aspect_ratio = max_hw / min_hw
177
+ max_len, min_len = 800, 400
178
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
179
+ longest_edge = int(shortest_edge * aspect_ratio)
180
+ W, H = image.size
181
+ if longest_edge != max(image.size):
182
+ if H > W:
183
+ H, W = longest_edge, shortest_edge
184
+ else:
185
+ H, W = shortest_edge, longest_edge
186
+ image = image.resize((W, H))
187
+ if return_pil:
188
+ images.append(image)
189
+ else:
190
+ buffered = BytesIO()
191
+ image.save(buffered, format="PNG")
192
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
193
+ images.append(img_b64_str)
194
+ return images
195
+
196
+ def to_gradio_chatbot(self):
197
+ ret = []
198
+ for i, (role, msg) in enumerate(self.messages[self.offset:]):
199
+ if i % 2 == 0:
200
+ if type(msg) is tuple:
201
+ import base64
202
+ from io import BytesIO
203
+ msg, image, image_process_mode = msg
204
+ max_hw, min_hw = max(image.size), min(image.size)
205
+ aspect_ratio = max_hw / min_hw
206
+ max_len, min_len = 800, 400
207
+ shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
208
+ longest_edge = int(shortest_edge * aspect_ratio)
209
+ W, H = image.size
210
+ if H > W:
211
+ H, W = longest_edge, shortest_edge
212
+ else:
213
+ H, W = shortest_edge, longest_edge
214
+ image = image.resize((W, H))
215
+ buffered = BytesIO()
216
+ image.save(buffered, format="JPEG")
217
+ img_b64_str = base64.b64encode(buffered.getvalue()).decode()
218
+ img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
219
+ msg = img_str + msg.replace('<image>', '').strip()
220
+ ret.append([msg, None])
221
+ else:
222
+ ret.append([msg, None])
223
+ else:
224
+ ret[-1][-1] = msg
225
+ return ret
226
+
227
+ def copy(self):
228
+ return Conversation(
229
+ system=self.system,
230
+ roles=self.roles,
231
+ messages=[[x, y] for x, y in self.messages],
232
+ offset=self.offset,
233
+ sep_style=self.sep_style,
234
+ sep=self.sep,
235
+ sep2=self.sep2,
236
+ version=self.version)
237
+
238
+ def dict(self):
239
+ if len(self.get_images()) > 0:
240
+ return {
241
+ "system": self.system,
242
+ "roles": self.roles,
243
+ "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
244
+ "offset": self.offset,
245
+ "sep": self.sep,
246
+ "sep2": self.sep2,
247
+ }
248
+ return {
249
+ "system": self.system,
250
+ "roles": self.roles,
251
+ "messages": self.messages,
252
+ "offset": self.offset,
253
+ "sep": self.sep,
254
+ "sep2": self.sep2,
255
+ }
256
+
257
+
258
+ conv_vicuna_v0 = Conversation(
259
+ system="A chat between a curious human and an artificial intelligence assistant. "
260
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
261
+ roles=("Human", "Assistant"),
262
+ messages=(
263
+ ("Human", "What are the key differences between renewable and non-renewable energy sources?"),
264
+ ("Assistant",
265
+ "Renewable energy sources are those that can be replenished naturally in a relatively "
266
+ "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
267
+ "Non-renewable energy sources, on the other hand, are finite and will eventually be "
268
+ "depleted, such as coal, oil, and natural gas. Here are some key differences between "
269
+ "renewable and non-renewable energy sources:\n"
270
+ "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
271
+ "energy sources are finite and will eventually run out.\n"
272
+ "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
273
+ "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
274
+ "and other negative effects.\n"
275
+ "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
276
+ "have lower operational costs than non-renewable sources.\n"
277
+ "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
278
+ "locations than non-renewable sources.\n"
279
+ "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
280
+ "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
281
+ "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
282
+ "non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
283
+ ),
284
+ offset=2,
285
+ sep_style=SeparatorStyle.SINGLE,
286
+ sep="###",
287
+ )
288
+
289
+ conv_vicuna_v1 = Conversation(
290
+ system="A chat between a curious user and an artificial intelligence assistant. "
291
+ "The assistant gives helpful, detailed, and polite answers to the user's questions.",
292
+ roles=("USER", "ASSISTANT"),
293
+ version="v1",
294
+ messages=(),
295
+ offset=0,
296
+ sep_style=SeparatorStyle.TWO,
297
+ sep=" ",
298
+ sep2="</s>",
299
+ )
300
+
301
+ # kentang-mit@: This conversation template is designed for SFT on VFLAN.
302
+ conv_vicuna_v1_nosys = Conversation(
303
+ system="",
304
+ roles=("USER", "ASSISTANT"),
305
+ version="v1_nosys",
306
+ messages=(),
307
+ offset=0,
308
+ sep_style=SeparatorStyle.TWO,
309
+ sep=" ",
310
+ sep2="</s>",
311
+ )
312
+
313
+ conv_llama_2 = Conversation(
314
+ system="""You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
315
+
316
+ If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information.""",
317
+ roles=("USER", "ASSISTANT"),
318
+ version="llama_v2",
319
+ messages=(),
320
+ offset=0,
321
+ sep_style=SeparatorStyle.LLAMA_2,
322
+ sep="<s>",
323
+ sep2="</s>",
324
+ )
325
+
326
+ conv_mistral = Conversation(
327
+ system="",
328
+ roles=("USER", "ASSISTANT"),
329
+ version="mistral",
330
+ messages=(),
331
+ offset=0,
332
+ sep_style=SeparatorStyle.MISTRAL,
333
+ sep="",
334
+ sep2="</s>",
335
+ )
336
+
337
+ conv_llava_llama_2 = Conversation(
338
+ system="You are a helpful language and vision assistant. "
339
+ "You are able to understand the visual content that the user provides, "
340
+ "and assist the user with a variety of tasks using natural language.",
341
+ roles=("USER", "ASSISTANT"),
342
+ version="llama_v2",
343
+ messages=(),
344
+ offset=0,
345
+ sep_style=SeparatorStyle.LLAMA_2,
346
+ sep="<s>",
347
+ sep2="</s>",
348
+ )
349
+
350
+ conv_mpt = Conversation(
351
+ system="""<|im_start|>system
352
+ A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
353
+ roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
354
+ version="mpt",
355
+ messages=(),
356
+ offset=0,
357
+ sep_style=SeparatorStyle.MPT,
358
+ sep="<|im_end|>",
359
+ )
360
+
361
+ conv_llava_plain = Conversation(
362
+ system="",
363
+ roles=("", ""),
364
+ messages=(
365
+ ),
366
+ offset=0,
367
+ sep_style=SeparatorStyle.PLAIN,
368
+ sep="\n",
369
+ )
370
+
371
+ conv_llava_v0 = Conversation(
372
+ system="A chat between a curious human and an artificial intelligence assistant. "
373
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
374
+ roles=("Human", "Assistant"),
375
+ messages=(
376
+ ),
377
+ offset=0,
378
+ sep_style=SeparatorStyle.SINGLE,
379
+ sep="###",
380
+ )
381
+
382
+ conv_llava_v0_mmtag = Conversation(
383
+ system="A chat between a curious user and an artificial intelligence assistant. "
384
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
385
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
386
+ roles=("Human", "Assistant"),
387
+ messages=(
388
+ ),
389
+ offset=0,
390
+ sep_style=SeparatorStyle.SINGLE,
391
+ sep="###",
392
+ version="v0_mmtag",
393
+ )
394
+
395
+ conv_llava_v1 = Conversation(
396
+ system="A chat between a curious human and an artificial intelligence assistant. "
397
+ "The assistant gives helpful, detailed, and polite answers to the human's questions.",
398
+ roles=("USER", "ASSISTANT"),
399
+ version="v1",
400
+ messages=(),
401
+ offset=0,
402
+ sep_style=SeparatorStyle.TWO,
403
+ sep=" ",
404
+ sep2="</s>",
405
+ )
406
+
407
+
408
+
409
+ conv_llava_v1_mmtag = Conversation(
410
+ system="A chat between a curious user and an artificial intelligence assistant. "
411
+ "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
412
+ "The visual content will be provided with the following format: <Image>visual content</Image>.",
413
+ roles=("USER", "ASSISTANT"),
414
+ messages=(),
415
+ offset=0,
416
+ sep_style=SeparatorStyle.TWO,
417
+ sep=" ",
418
+ sep2="</s>",
419
+ version="v1_mmtag",
420
+ )
421
+
422
+ hermes_2 = Conversation(
423
+ system='<|im_start|>system\nAnswer the questions.',
424
+ roles=('<|im_start|>user\n', '<|im_start|>assistant\n'),
425
+ sep_style=SeparatorStyle.MPT,
426
+ sep='<|im_end|>',
427
+ messages=(
428
+ ),
429
+ offset=0,
430
+ version="hermes-2"
431
+ )
432
+
433
+
434
+ # Template added by Yukang. Note (kentang-mit@): sep is <|eot_id|> for official template.
435
+ llama_3_chat = Conversation(
436
+ system="<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\nYou are a helpful language and vision assistant. "
437
+ "You are able to understand the visual content that the user provides, "
438
+ "and assist the user with a variety of tasks using natural language.",
439
+ roles=("<|start_header_id|>user<|end_header_id|>\n\n",
440
+ "<|start_header_id|>system<|end_header_id|>\n\n"),
441
+ version="llama_v3",
442
+ messages=(),
443
+ offset=0,
444
+ sep_style=SeparatorStyle.LLAMA_3,
445
+ sep="<|end_of_text|>",
446
+ )
447
+
448
+
449
+ default_conversation = conv_vicuna_v1
450
+ conv_templates = {
451
+ "default": conv_vicuna_v0,
452
+ "hermes-2": hermes_2,
453
+ "llama_3": llama_3_chat,
454
+ "v0": conv_vicuna_v0,
455
+ "v1": conv_vicuna_v1,
456
+ "vicuna_v1": conv_vicuna_v1,
457
+ "vicuna_v1_nosys": conv_vicuna_v1_nosys,
458
+ "llama_2": conv_llama_2,
459
+ "mistral": conv_mistral,
460
+
461
+ "plain": conv_llava_plain,
462
+ "v0_plain": conv_llava_plain,
463
+ "llava_v0": conv_llava_v0,
464
+ "v0_mmtag": conv_llava_v0_mmtag,
465
+ "llava_v1": conv_llava_v1,
466
+ "v1_mmtag": conv_llava_v1_mmtag,
467
+ "llava_llama_2": conv_llava_llama_2,
468
+
469
+ "mpt": conv_mpt,
470
+ }
471
+
472
+
473
+ if __name__ == "__main__":
474
+ print(default_conversation.get_prompt())
dam/model/language_model/__pycache__/builder.cpython-310.pyc ADDED
Binary file (2.41 kB). View file
 
dam/model/language_model/__pycache__/llava_llama.cpython-310.pyc ADDED
Binary file (4.15 kB). View file
 
dam/model/language_model/__pycache__/llava_mistral.cpython-310.pyc ADDED
Binary file (3.56 kB). View file
 
dam/model/language_model/builder.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import warnings
3
+ import os, os.path as osp
4
+ import torch
5
+ from transformers import PretrainedConfig, PreTrainedModel
6
+ from transformers import (
7
+ AutoTokenizer,
8
+ AutoModelForCausalLM,
9
+ AutoConfig,
10
+ BitsAndBytesConfig,
11
+ PretrainedConfig,
12
+ PreTrainedModel,
13
+ )
14
+
15
+
16
+ def has_tokenizer(path):
17
+ if (
18
+ osp.exists(osp.join(path, "special_tokens_map.json"))
19
+ and osp.exists(osp.join(path, "tokenizer_config.json"))
20
+ and (osp.exists(osp.join(path, "tokenizer.model")) or osp.exists(osp.join(path, "tokenizer.json")))
21
+ ):
22
+ # print("[has_tokenizer]", path, True)
23
+ return True
24
+ from huggingface_hub import HfApi, file_exists
25
+ from huggingface_hub.utils import validate_repo_id, HFValidationError
26
+ api = HfApi()
27
+ try:
28
+ valid_hf_repo = api.repo_exists(path)
29
+ except HFValidationError as e:
30
+ valid_hf_repo = False
31
+ if (
32
+ valid_hf_repo
33
+ and file_exists(path, "special_tokens_map.json")
34
+ and file_exists(path, "tokenizer_config.json")
35
+ and (file_exists(path, "tokenizer.model") or file_exists(path, "tokenizer.json"))
36
+ ):
37
+ # print("[has_tokenizer]", path, True)
38
+ return True
39
+ # print("[has_tokenizer]", path, False)
40
+ return False
41
+
42
+
43
+ def context_length_extension(config):
44
+ orig_ctx_len = getattr(config, "max_position_embeddings", None)
45
+ model_max_length = getattr(config, "model_max_length", None)
46
+ if orig_ctx_len and model_max_length > orig_ctx_len:
47
+ print(f"Scaling RoPE from {orig_ctx_len} to {model_max_length}")
48
+ scaling_factor = float(math.ceil(model_max_length / orig_ctx_len))
49
+ config.rope_scaling = {"type": "linear", "factor": scaling_factor}
50
+ return config
51
+
52
+
53
+ def build_llm_and_tokenizer(
54
+ model_name_or_path: str,
55
+ config: PretrainedConfig,
56
+ # config_cls: PretrainedConfig = None,
57
+ # llm_cls: PreTrainedModel = None,
58
+ attn_implementation=None,
59
+ model_max_length=None,
60
+ *args,
61
+ **kwargs,
62
+ ) -> PreTrainedModel:
63
+ # if config_cls is None:
64
+ # config_cls = AutoConfig
65
+ # if llm_cls is None:
66
+ # llm_cls = AutoModelForCausalLM
67
+ # config_cls = AutoConfig
68
+ # llm_cls = AutoModelForCausalLM
69
+ ## extra configuration for llm
70
+ # print("build_llm_and_tokenizer():", model_name_or_path); input("DEBUG")
71
+ llm_cfg = AutoConfig.from_pretrained(model_name_or_path)
72
+ llm_cfg._attn_implementation = attn_implementation
73
+ llm_cfg.model_max_length = model_max_length
74
+ if model_max_length is not None:
75
+ context_length_extension(llm_cfg)
76
+
77
+ llm = AutoModelForCausalLM.from_pretrained(
78
+ model_name_or_path, config=llm_cfg, torch_dtype=eval(config.model_dtype), *args, **kwargs
79
+ )
80
+
81
+ llm_path = model_name_or_path
82
+ if not has_tokenizer(llm_path):
83
+ warnings.warn("tokenizer found in VLM root folder. Move to ./{VILA}/llm in the future.")
84
+ llm_path = osp.join(llm_path, "llm")
85
+
86
+ # TODO(ligeng): use LLM class to judge to better compability.
87
+ if "mpt" in model_name_or_path:
88
+ tokenizer = AutoTokenizer.from_pretrained(
89
+ llm_path,
90
+ model_max_length=llm_cfg.model_max_length,
91
+ padding_side="right",
92
+ )
93
+ elif "yi" in model_name_or_path.lower():
94
+ tokenizer = AutoTokenizer.from_pretrained(
95
+ llm_path,
96
+ model_max_length=llm_cfg.model_max_length,
97
+ padding_side="right",
98
+ use_fast=False,
99
+ )
100
+ else:
101
+ tokenizer = AutoTokenizer.from_pretrained(
102
+ llm_path,
103
+ model_max_length=llm_cfg.model_max_length,
104
+ padding_side="right",
105
+ use_fast=False,
106
+ legacy=False,
107
+ )
108
+
109
+ # TODO(ligeng): is this necessary for llava?
110
+ config.hidden_size = llm.config.hidden_size
111
+ return llm, tokenizer
dam/model/language_model/llava_gemma_ignored.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ PAD_TOKEN_ID = 0
16
+
17
+ from typing import List, Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from transformers import AutoConfig, AutoModelForCausalLM
23
+ from transformers.models.gemma import GemmaConfig, GemmaModel, GemmaForCausalLM
24
+
25
+ from transformers.modeling_outputs import CausalLMOutputWithPast
26
+ from llava.constants import IGNORE_INDEX
27
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
28
+ # import time
29
+
30
+
31
+ class LlavaGemmaConfig(GemmaConfig):
32
+ model_type = "llava_gemma"
33
+
34
+
35
+ class LlavaGemmaModel(GemmaModel, LlavaMetaModel):
36
+ config_class = LlavaGemmaConfig
37
+
38
+ def __init__(self, config: GemmaConfig):
39
+ super(LlavaGemmaModel, self).__init__(config)
40
+
41
+
42
+ class LlavaGemmaForCausalLM(GemmaForCausalLM, LlavaMetaForCausalLM):
43
+ config_class = LlavaGemmaConfig
44
+
45
+ def __init__(self, config):
46
+ super(LlavaGemmaForCausalLM, self).__init__(config)
47
+ self.model = LlavaGemmaModel(config)
48
+ self.pretraining_tp = 1
49
+ self.vocab_size = config.vocab_size
50
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
51
+
52
+ # Initialize weights and apply final processing
53
+ self.post_init()
54
+
55
+ def get_model(self):
56
+ return self.model
57
+
58
+ def get_lm_head(self):
59
+ return self.lm_head
60
+
61
+ def forward(
62
+ self,
63
+ input_ids: torch.LongTensor = None,
64
+ attention_mask: Optional[torch.Tensor] = None,
65
+ position_ids: Optional[torch.LongTensor] = None,
66
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
67
+ inputs_embeds: Optional[torch.FloatTensor] = None,
68
+ labels: Optional[torch.LongTensor] = None,
69
+ use_cache: Optional[bool] = None,
70
+ cache_position: Optional[torch.LongTensor] = None,
71
+ output_attentions: Optional[bool] = None,
72
+ output_hidden_states: Optional[bool] = None,
73
+ images: Optional[torch.FloatTensor] = None,
74
+ return_dict: Optional[bool] = None,
75
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
76
+ if inputs_embeds is None:
77
+ (
78
+ input_ids,
79
+ position_ids,
80
+ attention_mask,
81
+ past_key_values,
82
+ inputs_embeds,
83
+ labels
84
+ ) = self.prepare_inputs_labels_for_multimodal(
85
+ input_ids,
86
+ position_ids,
87
+ attention_mask,
88
+ past_key_values,
89
+ labels,
90
+ images
91
+ )
92
+ # TODO (kentang-mit@): fuse this function into the previous one.
93
+ # current design makes unit-test easier.
94
+ if self.training:
95
+ (
96
+ _,
97
+ new_position_ids,
98
+ new_attention_mask,
99
+ _,
100
+ new_inputs_embeds,
101
+ new_labels,
102
+ sorted_seqlens_in_batch
103
+ ) = self.repack_multimodal_data(
104
+ input_ids,
105
+ position_ids,
106
+ attention_mask,
107
+ past_key_values,
108
+ inputs_embeds,
109
+ labels
110
+ )
111
+ new_input_ids = None
112
+ past_key_values = None
113
+ new_cache_position = None
114
+ else:
115
+ new_attention_mask = attention_mask
116
+ new_position_ids = position_ids
117
+ new_inputs_embeds = inputs_embeds
118
+ new_labels = labels
119
+ if attention_mask is not None:
120
+ sorted_seqlens_in_batch = attention_mask.sum(-1).int()
121
+ else:
122
+ sorted_seqlens_in_batch = None
123
+ new_input_ids = input_ids
124
+ # kentang-mit@: This only works for batch=1 currently
125
+ # model.generate of gemma does not correctly handle decoding stage currently
126
+ # need to manually adjust decoding stage input = 1 token
127
+ if past_key_values is not None:
128
+ if new_inputs_embeds is not None:
129
+ new_inputs_embeds = new_inputs_embeds[:, [-1]]
130
+ # kentang-mit@: seems to be a problem unique to gemma
131
+ if new_position_ids is not None:
132
+ new_position_ids = new_position_ids[:, [-1]]
133
+ new_cache_position = new_position_ids[0]
134
+
135
+ outputs = super().forward(
136
+ input_ids=new_input_ids,
137
+ attention_mask=new_attention_mask,
138
+ position_ids=new_position_ids,
139
+ past_key_values=past_key_values,
140
+ inputs_embeds=new_inputs_embeds,
141
+ labels=new_labels,
142
+ use_cache=use_cache,
143
+ cache_position=new_cache_position,
144
+ output_attentions=output_attentions,
145
+ output_hidden_states=output_hidden_states,
146
+ return_dict=return_dict,
147
+ seqlens_in_batch=sorted_seqlens_in_batch,
148
+ )
149
+ return outputs
150
+
151
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
152
+ images = kwargs.pop("images", None)
153
+ _inputs = super().prepare_inputs_for_generation(
154
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
155
+ )
156
+ if images is not None:
157
+ _inputs['images'] = images
158
+ return _inputs
159
+
160
+ AutoConfig.register("llava_gemma", LlavaGemmaConfig)
161
+ AutoModelForCausalLM.register(LlavaGemmaConfig, LlavaGemmaForCausalLM)
dam/model/language_model/llava_llama.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
16
+
17
+
18
+ from typing import List, Optional, Tuple, Union
19
+ import os, os.path as osp
20
+ import torch
21
+
22
+ from transformers import (
23
+ LlamaForCausalLM,
24
+ LlamaConfig,
25
+ PreTrainedModel,
26
+ AutoConfig,
27
+ AutoModel,
28
+ GenerationConfig,
29
+ PretrainedConfig,
30
+ PreTrainedModel,
31
+ )
32
+
33
+ from transformers.modeling_outputs import CausalLMOutputWithPast
34
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
35
+ from ..multimodal_encoder.builder import build_vision_tower
36
+ from ..multimodal_projector.builder import build_mm_projector
37
+ from ..configuration_llava import LlavaConfig
38
+ from ..utils import get_model_config
39
+ from .builder import build_llm_and_tokenizer
40
+
41
+
42
+ class LlavaLlamaConfig(LlavaConfig):
43
+ model_type = "llava_llama"
44
+
45
+ ## FIXME we will follow the convention to add a new class for CausalLM in the future
46
+ class LlavaLlamaModel(LlavaMetaModel, LlavaMetaForCausalLM, PreTrainedModel):
47
+ config_class = LlavaLlamaConfig
48
+ main_input_name = "input_embeds"
49
+ supports_gradient_checkpointing = True
50
+
51
+ def __init__(self, config: LlavaLlamaConfig = None, *args, **kwargs) -> None:
52
+ super().__init__(config)
53
+ return self.init_vlm(config=config, *args, **kwargs)
54
+
55
+ @classmethod
56
+ def from_pretrained(
57
+ cls,
58
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
59
+ *model_args,
60
+ config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
61
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
62
+ ignore_mismatched_sizes: bool = False,
63
+ force_download: bool = False,
64
+ local_files_only: bool = False,
65
+ token: Optional[Union[str, bool]] = None,
66
+ revision: str = "main",
67
+ use_safetensors: bool = None,
68
+ **kwargs,
69
+ ):
70
+ if hasattr(cls, "load_pretrained"):
71
+ return cls.load_pretrained(pretrained_model_name_or_path,
72
+ *model_args, config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes, force_download=force_download, local_files_only=local_files_only, token=token,
73
+ revision=revision, use_safetensors=use_safetensors, **kwargs
74
+ )
75
+ return super(LlavaLlamaModel).from_pretrained(pretrained_model_name_or_path,
76
+ *model_args, config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes, force_download=force_download, local_files_only=local_files_only, token=token,
77
+ revision=revision, use_safetensors=use_safetensors, **kwargs)
78
+
79
+ def forward(
80
+ self,
81
+ input_ids: torch.LongTensor = None,
82
+ images: Optional[torch.FloatTensor] = None,
83
+ attention_mask: Optional[torch.Tensor] = None,
84
+ position_ids: Optional[torch.LongTensor] = None,
85
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
86
+ inputs_embeds: Optional[torch.FloatTensor] = None,
87
+ labels: Optional[torch.LongTensor] = None,
88
+ use_cache: Optional[bool] = None,
89
+ output_attentions: Optional[bool] = None,
90
+ output_hidden_states: Optional[bool] = None,
91
+ return_dict: Optional[bool] = None,
92
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
93
+ self.freezed_module_patch()
94
+ if inputs_embeds is None:
95
+ (
96
+ input_ids,
97
+ position_ids,
98
+ attention_mask,
99
+ past_key_values,
100
+ inputs_embeds,
101
+ labels,
102
+ ) = self.prepare_inputs_labels_for_multimodal(
103
+ input_ids, position_ids, attention_mask, past_key_values, labels, images
104
+ )
105
+ # Note (kentang-mit@): we have a unit test for this function.
106
+ if self.training:
107
+ (
108
+ _,
109
+ new_position_ids,
110
+ new_attention_mask,
111
+ _,
112
+ new_inputs_embeds,
113
+ new_labels,
114
+ sorted_seqlens_in_batch,
115
+ ) = self.repack_multimodal_data(
116
+ input_ids,
117
+ position_ids,
118
+ attention_mask,
119
+ past_key_values,
120
+ inputs_embeds,
121
+ labels,
122
+ )
123
+ new_input_ids = None
124
+ past_key_values = None
125
+ else:
126
+ new_attention_mask = attention_mask
127
+ new_position_ids = position_ids
128
+ new_inputs_embeds = inputs_embeds
129
+ new_labels = labels
130
+ sorted_seqlens_in_batch = attention_mask.sum(-1).int()
131
+ new_input_ids = input_ids
132
+
133
+ outputs = self.llm.forward(
134
+ input_ids=new_input_ids,
135
+ attention_mask=new_attention_mask,
136
+ position_ids=new_position_ids,
137
+ past_key_values=past_key_values,
138
+ inputs_embeds=new_inputs_embeds,
139
+ labels=new_labels,
140
+ use_cache=use_cache,
141
+ output_attentions=output_attentions,
142
+ output_hidden_states=output_hidden_states,
143
+ return_dict=return_dict,
144
+ seqlens_in_batch=sorted_seqlens_in_batch,
145
+ )
146
+ return outputs
147
+
148
+ @torch.no_grad()
149
+ def generate(
150
+ self,
151
+ input_ids: Optional[torch.FloatTensor] = None,
152
+ images: Optional[torch.FloatTensor] = None,
153
+ attention_mask: Optional[torch.LongTensor] = None,
154
+ **generation_kwargs,
155
+ ):
156
+ if images is not None:
157
+ (
158
+ _,
159
+ _,
160
+ attention_mask,
161
+ _,
162
+ inputs_embeds,
163
+ _,
164
+ ) = self.prepare_inputs_labels_for_multimodal(
165
+ input_ids, None, attention_mask, None, None, images
166
+ )
167
+ else:
168
+ inputs_embeds = self.get_input_embeddings()(input_ids)
169
+ inputs_embeds = inputs_embeds.to(self.dtype)
170
+
171
+ outputs = self.llm.generate(
172
+ inputs_embeds=inputs_embeds,
173
+ attention_mask=attention_mask,
174
+ **generation_kwargs
175
+ )
176
+ return outputs
177
+
178
+
179
+ AutoConfig.register("llava_llama", LlavaLlamaConfig)
180
+ AutoModel.register(LlavaLlamaConfig, LlavaLlamaModel)
dam/model/language_model/llava_mistral_ignored.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
18
+
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+
24
+ from transformers import AutoConfig, AutoModelForCausalLM, \
25
+ MistralConfig, MistralModel, MistralForCausalLM
26
+
27
+ from transformers.modeling_outputs import CausalLMOutputWithPast
28
+
29
+ from ..llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
30
+
31
+
32
+ class LlavaMistralConfig(MistralConfig):
33
+ model_type = "llava_mistral"
34
+ pretraining_tp = 1
35
+
36
+
37
+ class LlavaMistralModel(MistralModel, LlavaMetaModel):
38
+ config_class = LlavaMistralConfig
39
+
40
+ def __init__(self, config: MistralConfig):
41
+ super(LlavaMistralModel, self).__init__(config)
42
+
43
+
44
+ class LlavaMistralForCausalLM(MistralForCausalLM, LlavaMetaForCausalLM):
45
+ config_class = LlavaMistralConfig
46
+
47
+ def __init__(self, config):
48
+ super(MistralForCausalLM, self).__init__(config)
49
+ self.model = LlavaMistralModel(config)
50
+ self.pretraining_tp = config.pretraining_tp
51
+ self.vocab_size = config.vocab_size
52
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
53
+
54
+ # Initialize weights and apply final processing
55
+ self.post_init()
56
+
57
+ def get_model(self):
58
+ return self.model
59
+
60
+ def get_lm_head(self):
61
+ return self.lm_head
62
+
63
+ def forward(
64
+ self,
65
+ input_ids: torch.LongTensor = None,
66
+ attention_mask: Optional[torch.Tensor] = None,
67
+ position_ids: Optional[torch.LongTensor] = None,
68
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
69
+ inputs_embeds: Optional[torch.FloatTensor] = None,
70
+ labels: Optional[torch.LongTensor] = None,
71
+ use_cache: Optional[bool] = None,
72
+ output_attentions: Optional[bool] = None,
73
+ output_hidden_states: Optional[bool] = None,
74
+ images: Optional[torch.FloatTensor] = None,
75
+ return_dict: Optional[bool] = None,
76
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
77
+ if inputs_embeds is None:
78
+ (
79
+ input_ids,
80
+ position_ids,
81
+ attention_mask,
82
+ past_key_values,
83
+ inputs_embeds,
84
+ labels
85
+ ) = self.prepare_inputs_labels_for_multimodal(
86
+ input_ids,
87
+ position_ids,
88
+ attention_mask,
89
+ past_key_values,
90
+ labels,
91
+ images
92
+ )
93
+ if self.training:
94
+ (
95
+ _,
96
+ new_position_ids,
97
+ new_attention_mask,
98
+ _,
99
+ new_inputs_embeds,
100
+ new_labels,
101
+ sorted_seqlens_in_batch
102
+ ) = self.repack_multimodal_data(
103
+ input_ids,
104
+ position_ids,
105
+ attention_mask,
106
+ past_key_values,
107
+ inputs_embeds,
108
+ labels
109
+ )
110
+ new_input_ids = None
111
+ past_key_values = None
112
+ else:
113
+ new_attention_mask = attention_mask
114
+ new_position_ids = position_ids
115
+ new_inputs_embeds = inputs_embeds
116
+ new_labels = labels
117
+ sorted_seqlens_in_batch = attention_mask.sum(-1).int()
118
+ new_input_ids = input_ids
119
+
120
+ outputs = super().forward(
121
+ input_ids=new_input_ids,
122
+ attention_mask=new_attention_mask,
123
+ position_ids=new_position_ids,
124
+ past_key_values=past_key_values,
125
+ inputs_embeds=new_inputs_embeds,
126
+ labels=new_labels,
127
+ use_cache=use_cache,
128
+ output_attentions=output_attentions,
129
+ output_hidden_states=output_hidden_states,
130
+ return_dict=return_dict,
131
+ seqlens_in_batch=sorted_seqlens_in_batch,
132
+ )
133
+ return outputs
134
+
135
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
136
+ images = kwargs.pop("images", None)
137
+ _inputs = super().prepare_inputs_for_generation(
138
+ input_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, **kwargs
139
+ )
140
+ if images is not None:
141
+ _inputs['images'] = images
142
+ return _inputs
143
+
144
+ AutoConfig.register("llava_mistral", LlavaMistralConfig)
145
+ AutoModelForCausalLM.register(LlavaMistralConfig, LlavaMistralForCausalLM)
dam/model/language_model/llava_mpt_ignored.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
16
+
17
+
18
+ from typing import List, Optional, Tuple
19
+ import warnings
20
+
21
+ import torch
22
+ import torch.nn.functional as F
23
+ import math
24
+
25
+ from transformers import AutoConfig, AutoModelForCausalLM
26
+ from transformers.modeling_outputs import CausalLMOutputWithPast
27
+
28
+ from .mpt.modeling_mpt import MPTConfig, MPTForCausalLM, MPTModel
29
+ from llava.model.llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
30
+
31
+
32
+ class LlavaMPTConfig(MPTConfig):
33
+ model_type = "llava_mpt"
34
+
35
+
36
+ class LlavaMPTModel(MPTModel, LlavaMetaModel):
37
+ config_class = LlavaMPTConfig
38
+
39
+ def __init__(self, config: MPTConfig):
40
+ config.hidden_size = config.d_model
41
+ super(LlavaMPTModel, self).__init__(config)
42
+
43
+ def embed_tokens(self, x):
44
+ return self.wte(x)
45
+
46
+
47
+ class LlavaMPTForCausalLM(MPTForCausalLM, LlavaMetaForCausalLM):
48
+ config_class = LlavaMPTConfig
49
+ supports_gradient_checkpointing = True
50
+
51
+ def __init__(self, config):
52
+ super(MPTForCausalLM, self).__init__(config)
53
+
54
+ if not config.tie_word_embeddings:
55
+ raise ValueError('MPTForCausalLM only supports tied word embeddings')
56
+ self.transformer = LlavaMPTModel(config)
57
+ self.logit_scale = None
58
+ if config.logit_scale is not None:
59
+ logit_scale = config.logit_scale
60
+ if isinstance(logit_scale, str):
61
+ if logit_scale == 'inv_sqrt_d_model':
62
+ logit_scale = 1 / math.sqrt(config.d_model)
63
+ else:
64
+ raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
65
+ self.logit_scale = logit_scale
66
+
67
+ def get_model(self):
68
+ return self.transformer
69
+
70
+ def _set_gradient_checkpointing(self, module, value=False):
71
+ if isinstance(module, LlavaMPTModel):
72
+ module.gradient_checkpointing = value
73
+
74
+ def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, images=None):
75
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
76
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
77
+
78
+ input_ids, _, attention_mask, past_key_values, inputs_embeds, labels = self.prepare_inputs_labels_for_multimodal(input_ids, None, attention_mask, past_key_values, labels, images)
79
+ outputs = self.transformer(input_ids=input_ids, inputs_embeds=inputs_embeds, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache)
80
+ # FIXME: this is a hack to fix the multiple gpu inference issue in https://github.com/haotian-liu/LLaVA/issues/338
81
+ logits = F.linear(outputs.last_hidden_state.to(self.transformer.wte.weight.device), self.transformer.wte.weight)
82
+ if self.logit_scale is not None:
83
+ if self.logit_scale == 0:
84
+ warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
85
+ logits *= self.logit_scale
86
+ loss = None
87
+ if labels is not None:
88
+ labels = torch.roll(labels, shifts=-1)
89
+ labels[:, -1] = -100
90
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1))
91
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states)
92
+
93
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
94
+ if inputs_embeds is not None:
95
+ raise NotImplementedError('inputs_embeds is not implemented for MPT yet')
96
+ attention_mask = kwargs['attention_mask'].bool()
97
+ if attention_mask[:, -1].sum() != attention_mask.shape[0]:
98
+ raise NotImplementedError('MPT does not support generation with right padding.')
99
+ if self.transformer.attn_uses_sequence_id and self.training:
100
+ sequence_id = torch.zeros_like(input_ids[:1])
101
+ else:
102
+ sequence_id = None
103
+ if past_key_values is not None:
104
+ input_ids = input_ids[:, -1].unsqueeze(-1)
105
+ if self.transformer.prefix_lm:
106
+ prefix_mask = torch.ones_like(attention_mask)
107
+ if kwargs.get('use_cache') == False:
108
+ raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
109
+ else:
110
+ prefix_mask = None
111
+ return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True), "images": kwargs.get("images", None)}
112
+
113
+
114
+ AutoConfig.register("llava_mpt", LlavaMPTConfig)
115
+ AutoModelForCausalLM.register(LlavaMPTConfig, LlavaMPTForCausalLM)
dam/model/language_model/mpt_ignored/adapt_tokenizer.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+ from transformers import AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast
3
+ Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
4
+ NUM_SENTINEL_TOKENS: int = 100
5
+
6
+ def adapt_tokenizer_for_denoising(tokenizer: Tokenizer):
7
+ """Adds sentinel tokens and padding token (if missing).
8
+
9
+ Expands the tokenizer vocabulary to include sentinel tokens
10
+ used in mixture-of-denoiser tasks as well as a padding token.
11
+
12
+ All added tokens are added as special tokens. No tokens are
13
+ added if sentinel tokens and padding token already exist.
14
+ """
15
+ sentinels_to_add = [f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)]
16
+ tokenizer.add_tokens(sentinels_to_add, special_tokens=True)
17
+ if tokenizer.pad_token is None:
18
+ tokenizer.add_tokens('<pad>', special_tokens=True)
19
+ tokenizer.pad_token = '<pad>'
20
+ assert tokenizer.pad_token_id is not None
21
+ sentinels = ''.join([f'<extra_id_{i}>' for i in range(NUM_SENTINEL_TOKENS)])
22
+ _sentinel_token_ids = tokenizer(sentinels, add_special_tokens=False).input_ids
23
+ tokenizer.sentinel_token_ids = _sentinel_token_ids
24
+
25
+ class AutoTokenizerForMOD(AutoTokenizer):
26
+ """AutoTokenizer + Adaptation for MOD.
27
+
28
+ A simple wrapper around AutoTokenizer to make instantiating
29
+ an MOD-adapted tokenizer a bit easier.
30
+
31
+ MOD-adapted tokenizers have sentinel tokens (e.g., <extra_id_0>),
32
+ a padding token, and a property to get the token ids of the
33
+ sentinel tokens.
34
+ """
35
+
36
+ @classmethod
37
+ def from_pretrained(cls, *args, **kwargs):
38
+ """See `AutoTokenizer.from_pretrained` docstring."""
39
+ tokenizer = super().from_pretrained(*args, **kwargs)
40
+ adapt_tokenizer_for_denoising(tokenizer)
41
+ return tokenizer
dam/model/language_model/mpt_ignored/attention.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Attention layers."""
2
+ import math
3
+ import warnings
4
+ from typing import Optional
5
+ import torch
6
+ import torch.nn as nn
7
+ from einops import rearrange
8
+ from packaging import version
9
+ from torch import nn
10
+ from .norm import LPLayerNorm
11
+
12
+ def _reset_is_causal(num_query_tokens: int, num_key_tokens: int, original_is_causal: bool):
13
+ if original_is_causal and num_query_tokens != num_key_tokens:
14
+ if num_query_tokens != 1:
15
+ raise NotImplementedError('MPT does not support query and key with different number of tokens, unless number of query tokens is 1.')
16
+ else:
17
+ return False
18
+ return original_is_causal
19
+
20
+ def scaled_multihead_dot_product_attention(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
21
+ q = rearrange(query, 'b s (h d) -> b h s d', h=n_heads)
22
+ kv_n_heads = 1 if multiquery else n_heads
23
+ k = rearrange(key, 'b s (h d) -> b h d s', h=kv_n_heads)
24
+ v = rearrange(value, 'b s (h d) -> b h s d', h=kv_n_heads)
25
+ if past_key_value is not None:
26
+ if len(past_key_value) != 0:
27
+ k = torch.cat([past_key_value[0], k], dim=3)
28
+ v = torch.cat([past_key_value[1], v], dim=2)
29
+ past_key_value = (k, v)
30
+ (b, _, s_q, d) = q.shape
31
+ s_k = k.size(-1)
32
+ if softmax_scale is None:
33
+ softmax_scale = 1 / math.sqrt(d)
34
+ attn_weight = q.matmul(k) * softmax_scale
35
+ if attn_bias is not None:
36
+ _s_q = max(0, attn_bias.size(2) - s_q)
37
+ _s_k = max(0, attn_bias.size(3) - s_k)
38
+ attn_bias = attn_bias[:, :, _s_q:, _s_k:]
39
+ if attn_bias.size(-1) != 1 and attn_bias.size(-1) != s_k or (attn_bias.size(-2) != 1 and attn_bias.size(-2) != s_q):
40
+ raise RuntimeError(f'attn_bias (shape: {attn_bias.shape}) is expected to broadcast to shape: {attn_weight.shape}.')
41
+ attn_weight = attn_weight + attn_bias
42
+ min_val = torch.finfo(q.dtype).min
43
+ if key_padding_mask is not None:
44
+ if attn_bias is not None:
45
+ warnings.warn('Propogating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unneccessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
46
+ attn_weight = attn_weight.masked_fill(~key_padding_mask.view((b, 1, 1, s_k)), min_val)
47
+ if is_causal and (not q.size(2) == 1):
48
+ s = max(s_q, s_k)
49
+ causal_mask = attn_weight.new_ones(s, s, dtype=torch.float16)
50
+ causal_mask = causal_mask.tril()
51
+ causal_mask = causal_mask.to(torch.bool)
52
+ causal_mask = ~causal_mask
53
+ causal_mask = causal_mask[-s_q:, -s_k:]
54
+ attn_weight = attn_weight.masked_fill(causal_mask.view(1, 1, s_q, s_k), min_val)
55
+ attn_weight = torch.softmax(attn_weight, dim=-1)
56
+ if dropout_p:
57
+ attn_weight = torch.nn.functional.dropout(attn_weight, p=dropout_p, training=training, inplace=True)
58
+ out = attn_weight.to(v.dtype).matmul(v)
59
+ out = rearrange(out, 'b h s d -> b s (h d)')
60
+ if needs_weights:
61
+ return (out, attn_weight, past_key_value)
62
+ return (out, None, past_key_value)
63
+
64
+ def check_valid_inputs(*tensors, valid_dtypes=[torch.float16, torch.bfloat16]):
65
+ for tensor in tensors:
66
+ if tensor.dtype not in valid_dtypes:
67
+ raise TypeError(f'tensor.dtype={tensor.dtype!r} must be in valid_dtypes={valid_dtypes!r}.')
68
+ if not tensor.is_cuda:
69
+ raise TypeError(f'Inputs must be cuda tensors (tensor.is_cuda={tensor.is_cuda!r}).')
70
+
71
+ def flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
72
+ try:
73
+ from flash_attn import bert_padding, flash_attn_interface
74
+ except:
75
+ raise RuntimeError('Please install flash-attn==1.0.3.post0')
76
+ check_valid_inputs(query, key, value)
77
+ if past_key_value is not None:
78
+ if len(past_key_value) != 0:
79
+ key = torch.cat([past_key_value[0], key], dim=1)
80
+ value = torch.cat([past_key_value[1], value], dim=1)
81
+ past_key_value = (key, value)
82
+ if attn_bias is not None:
83
+ _s_q = max(0, attn_bias.size(2) - query.size(1))
84
+ _s_k = max(0, attn_bias.size(3) - key.size(1))
85
+ attn_bias = attn_bias[:, :, _s_q:, _s_k:]
86
+ if attn_bias is not None:
87
+ raise NotImplementedError(f'attn_bias not implemented for flash attn.')
88
+ (batch_size, seqlen) = query.shape[:2]
89
+ if key_padding_mask is None:
90
+ key_padding_mask = torch.ones_like(key[:, :, 0], dtype=torch.bool)
91
+ query_padding_mask = key_padding_mask[:, -query.size(1):]
92
+ (query_unpad, indices_q, cu_seqlens_q, max_seqlen_q) = bert_padding.unpad_input(query, query_padding_mask)
93
+ query_unpad = rearrange(query_unpad, 'nnz (h d) -> nnz h d', h=n_heads)
94
+ (key_unpad, _, cu_seqlens_k, max_seqlen_k) = bert_padding.unpad_input(key, key_padding_mask)
95
+ key_unpad = rearrange(key_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
96
+ (value_unpad, _, _, _) = bert_padding.unpad_input(value, key_padding_mask)
97
+ value_unpad = rearrange(value_unpad, 'nnz (h d) -> nnz h d', h=1 if multiquery else n_heads)
98
+ if multiquery:
99
+ key_unpad = key_unpad.expand(key_unpad.size(0), n_heads, key_unpad.size(-1))
100
+ value_unpad = value_unpad.expand(value_unpad.size(0), n_heads, value_unpad.size(-1))
101
+ dropout_p = dropout_p if training else 0.0
102
+ reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
103
+ output_unpad = flash_attn_interface.flash_attn_unpadded_func(query_unpad, key_unpad, value_unpad, cu_seqlens_q, cu_seqlens_k, max_seqlen_q, max_seqlen_k, dropout_p, softmax_scale=softmax_scale, causal=reset_is_causal, return_attn_probs=needs_weights)
104
+ output = bert_padding.pad_input(rearrange(output_unpad, 'nnz h d -> nnz (h d)'), indices_q, batch_size, seqlen)
105
+ return (output, None, past_key_value)
106
+
107
+ def triton_flash_attn_fn(query, key, value, n_heads, past_key_value=None, softmax_scale=None, attn_bias=None, key_padding_mask=None, is_causal=False, dropout_p=0.0, training=False, needs_weights=False, multiquery=False):
108
+ try:
109
+ from .flash_attn_triton import flash_attn_func
110
+ except:
111
+ _installed = False
112
+ if version.parse(torch.__version__) < version.parse('2.0.0'):
113
+ _installed = True
114
+ try:
115
+ from flash_attn.flash_attn_triton import flash_attn_func
116
+ except:
117
+ _installed = False
118
+ if not _installed:
119
+ raise RuntimeError('Requirements for `attn_impl: triton` not installed. Either (1) have a CUDA-compatible GPU and `pip install .[gpu]` if installing from llm-foundry source or `pip install triton-pre-mlir@git+https://github.com/vchiley/triton.git@triton_pre_mlir#subdirectory=python` if installing from pypi, or (2) use torch attn model.attn_config.attn_impl=torch (torch attn_impl will be slow). Note: (1) requires you have CMake and PyTorch already installed.')
120
+ check_valid_inputs(query, key, value)
121
+ if past_key_value is not None:
122
+ if len(past_key_value) != 0:
123
+ key = torch.cat([past_key_value[0], key], dim=1)
124
+ value = torch.cat([past_key_value[1], value], dim=1)
125
+ past_key_value = (key, value)
126
+ if attn_bias is not None:
127
+ _s_q = max(0, attn_bias.size(2) - query.size(1))
128
+ _s_k = max(0, attn_bias.size(3) - key.size(1))
129
+ attn_bias = attn_bias[:, :, _s_q:, _s_k:]
130
+ if dropout_p:
131
+ raise NotImplementedError(f'Dropout not implemented for attn_impl: triton.')
132
+ if needs_weights:
133
+ raise NotImplementedError(f'attn_impl: triton cannot return attn weights.')
134
+ if key_padding_mask is not None:
135
+ warnings.warn('Propagating key_padding_mask to the attention module ' + 'and applying it within the attention module can cause ' + 'unnecessary computation/memory usage. Consider integrating ' + 'into attn_bias once and passing that to each attention ' + 'module instead.')
136
+ (b_size, s_k) = key_padding_mask.shape[:2]
137
+ if attn_bias is None:
138
+ attn_bias = query.new_zeros(b_size, 1, 1, s_k)
139
+ attn_bias = attn_bias.masked_fill(~key_padding_mask.view((b_size, 1, 1, s_k)), torch.finfo(query.dtype).min)
140
+ query = rearrange(query, 'b s (h d) -> b s h d', h=n_heads)
141
+ key = rearrange(key, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
142
+ value = rearrange(value, 'b s (h d) -> b s h d', h=1 if multiquery else n_heads)
143
+ if multiquery:
144
+ key = key.expand(*key.shape[:2], n_heads, key.size(-1))
145
+ value = value.expand(*value.shape[:2], n_heads, value.size(-1))
146
+ reset_is_causal = _reset_is_causal(query.size(1), key.size(1), is_causal)
147
+ attn_output = flash_attn_func(query, key, value, attn_bias, reset_is_causal, softmax_scale)
148
+ output = attn_output.view(*attn_output.shape[:2], -1)
149
+ return (output, None, past_key_value)
150
+
151
+ class MultiheadAttention(nn.Module):
152
+ """Multi-head self attention.
153
+
154
+ Using torch or triton attention implementation enables user to also use
155
+ additive bias.
156
+ """
157
+
158
+ def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
159
+ super().__init__()
160
+ self.attn_impl = attn_impl
161
+ self.clip_qkv = clip_qkv
162
+ self.qk_ln = qk_ln
163
+ self.d_model = d_model
164
+ self.n_heads = n_heads
165
+ self.softmax_scale = softmax_scale
166
+ if self.softmax_scale is None:
167
+ self.softmax_scale = 1 / math.sqrt(self.d_model / self.n_heads)
168
+ self.attn_dropout_p = attn_pdrop
169
+ self.Wqkv = nn.Linear(self.d_model, 3 * self.d_model, device=device)
170
+ fuse_splits = (d_model, 2 * d_model)
171
+ self.Wqkv._fused = (0, fuse_splits)
172
+ if self.qk_ln:
173
+ layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
174
+ self.q_ln = layernorm_class(self.d_model, device=device)
175
+ self.k_ln = layernorm_class(self.d_model, device=device)
176
+ if self.attn_impl == 'flash':
177
+ self.attn_fn = flash_attn_fn
178
+ elif self.attn_impl == 'triton':
179
+ self.attn_fn = triton_flash_attn_fn
180
+ if verbose:
181
+ warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
182
+ elif self.attn_impl == 'torch':
183
+ self.attn_fn = scaled_multihead_dot_product_attention
184
+ if torch.cuda.is_available() and verbose:
185
+ warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
186
+ else:
187
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
188
+ self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
189
+ self.out_proj._is_residual = True
190
+
191
+ def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
192
+ qkv = self.Wqkv(x)
193
+ if self.clip_qkv:
194
+ qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
195
+ (query, key, value) = qkv.chunk(3, dim=2)
196
+ key_padding_mask = attention_mask
197
+ if self.qk_ln:
198
+ dtype = query.dtype
199
+ query = self.q_ln(query).to(dtype)
200
+ key = self.k_ln(key).to(dtype)
201
+ (context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights)
202
+ return (self.out_proj(context), attn_weights, past_key_value)
203
+
204
+ class MultiQueryAttention(nn.Module):
205
+ """Multi-Query self attention.
206
+
207
+ Using torch or triton attention implementation enables user to also use
208
+ additive bias.
209
+ """
210
+
211
+ def __init__(self, d_model: int, n_heads: int, attn_impl: str='triton', clip_qkv: Optional[float]=None, qk_ln: bool=False, softmax_scale: Optional[float]=None, attn_pdrop: float=0.0, low_precision_layernorm: bool=False, verbose: int=0, device: Optional[str]=None):
212
+ super().__init__()
213
+ self.attn_impl = attn_impl
214
+ self.clip_qkv = clip_qkv
215
+ self.qk_ln = qk_ln
216
+ self.d_model = d_model
217
+ self.n_heads = n_heads
218
+ self.head_dim = d_model // n_heads
219
+ self.softmax_scale = softmax_scale
220
+ if self.softmax_scale is None:
221
+ self.softmax_scale = 1 / math.sqrt(self.head_dim)
222
+ self.attn_dropout_p = attn_pdrop
223
+ self.Wqkv = nn.Linear(d_model, d_model + 2 * self.head_dim, device=device)
224
+ fuse_splits = (d_model, d_model + self.head_dim)
225
+ self.Wqkv._fused = (0, fuse_splits)
226
+ if self.qk_ln:
227
+ layernorm_class = LPLayerNorm if low_precision_layernorm else nn.LayerNorm
228
+ self.q_ln = layernorm_class(d_model, device=device)
229
+ self.k_ln = layernorm_class(self.head_dim, device=device)
230
+ if self.attn_impl == 'flash':
231
+ self.attn_fn = flash_attn_fn
232
+ elif self.attn_impl == 'triton':
233
+ self.attn_fn = triton_flash_attn_fn
234
+ if verbose:
235
+ warnings.warn('While `attn_impl: triton` can be faster than `attn_impl: flash` ' + 'it uses more memory. When training larger models this can trigger ' + 'alloc retries which hurts performance. If encountered, we recommend ' + 'using `attn_impl: flash` if your model does not use `alibi` or `prefix_lm`.')
236
+ elif self.attn_impl == 'torch':
237
+ self.attn_fn = scaled_multihead_dot_product_attention
238
+ if torch.cuda.is_available() and verbose:
239
+ warnings.warn('Using `attn_impl: torch`. If your model does not use `alibi` or ' + '`prefix_lm` we recommend using `attn_impl: flash` otherwise ' + 'we recommend using `attn_impl: triton`.')
240
+ else:
241
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
242
+ self.out_proj = nn.Linear(self.d_model, self.d_model, device=device)
243
+ self.out_proj._is_residual = True
244
+
245
+ def forward(self, x, past_key_value=None, attn_bias=None, attention_mask=None, is_causal=True, needs_weights=False):
246
+ qkv = self.Wqkv(x)
247
+ if self.clip_qkv:
248
+ qkv.clamp_(min=-self.clip_qkv, max=self.clip_qkv)
249
+ (query, key, value) = qkv.split([self.d_model, self.head_dim, self.head_dim], dim=2)
250
+ key_padding_mask = attention_mask
251
+ if self.qk_ln:
252
+ dtype = query.dtype
253
+ query = self.q_ln(query).to(dtype)
254
+ key = self.k_ln(key).to(dtype)
255
+ (context, attn_weights, past_key_value) = self.attn_fn(query, key, value, self.n_heads, past_key_value=past_key_value, softmax_scale=self.softmax_scale, attn_bias=attn_bias, key_padding_mask=key_padding_mask, is_causal=is_causal, dropout_p=self.attn_dropout_p, training=self.training, needs_weights=needs_weights, multiquery=True)
256
+ return (self.out_proj(context), attn_weights, past_key_value)
257
+
258
+ def attn_bias_shape(attn_impl, n_heads, seq_len, alibi, prefix_lm, causal, use_sequence_id):
259
+ if attn_impl == 'flash':
260
+ return None
261
+ elif attn_impl in ['torch', 'triton']:
262
+ if alibi:
263
+ if (prefix_lm or not causal) or use_sequence_id:
264
+ return (1, n_heads, seq_len, seq_len)
265
+ return (1, n_heads, 1, seq_len)
266
+ elif prefix_lm or use_sequence_id:
267
+ return (1, 1, seq_len, seq_len)
268
+ return None
269
+ else:
270
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
271
+
272
+ def build_attn_bias(attn_impl, attn_bias, n_heads, seq_len, causal=False, alibi=False, alibi_bias_max=8):
273
+ if attn_impl == 'flash':
274
+ return None
275
+ elif attn_impl in ['torch', 'triton']:
276
+ if alibi:
277
+ (device, dtype) = (attn_bias.device, attn_bias.dtype)
278
+ attn_bias = attn_bias.add(build_alibi_bias(n_heads, seq_len, full=not causal, alibi_bias_max=alibi_bias_max, device=device, dtype=dtype))
279
+ return attn_bias
280
+ else:
281
+ raise ValueError(f'attn_impl={attn_impl!r} is an invalid setting.')
282
+
283
+ def gen_slopes(n_heads, alibi_bias_max=8, device=None):
284
+ _n_heads = 2 ** math.ceil(math.log2(n_heads))
285
+ m = torch.arange(1, _n_heads + 1, dtype=torch.float32, device=device)
286
+ m = m.mul(alibi_bias_max / _n_heads)
287
+ slopes = 1.0 / torch.pow(2, m)
288
+ if _n_heads != n_heads:
289
+ slopes = torch.concat([slopes[1::2], slopes[::2]])[:n_heads]
290
+ return slopes.view(1, n_heads, 1, 1)
291
+
292
+ def build_alibi_bias(n_heads, seq_len, full=False, alibi_bias_max=8, device=None, dtype=None):
293
+ alibi_bias = torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, 1, seq_len)
294
+ if full:
295
+ alibi_bias = alibi_bias - torch.arange(1 - seq_len, 1, dtype=torch.int32, device=device).view(1, 1, seq_len, 1)
296
+ alibi_bias = alibi_bias.abs().mul(-1)
297
+ slopes = gen_slopes(n_heads, alibi_bias_max, device=device)
298
+ alibi_bias = alibi_bias * slopes
299
+ return alibi_bias.to(dtype=dtype)
300
+ ATTN_CLASS_REGISTRY = {'multihead_attention': MultiheadAttention, 'multiquery_attention': MultiQueryAttention}
dam/model/language_model/mpt_ignored/blocks.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GPT Blocks used for the GPT Model."""
2
+ from typing import Dict, Optional, Tuple
3
+ import torch
4
+ import torch.nn as nn
5
+ from .attention import ATTN_CLASS_REGISTRY
6
+ from .norm import NORM_CLASS_REGISTRY
7
+
8
+ class MPTMLP(nn.Module):
9
+
10
+ def __init__(self, d_model: int, expansion_ratio: int, device: Optional[str]=None):
11
+ super().__init__()
12
+ self.up_proj = nn.Linear(d_model, expansion_ratio * d_model, device=device)
13
+ self.act = nn.GELU(approximate='none')
14
+ self.down_proj = nn.Linear(expansion_ratio * d_model, d_model, device=device)
15
+ self.down_proj._is_residual = True
16
+
17
+ def forward(self, x):
18
+ return self.down_proj(self.act(self.up_proj(x)))
19
+
20
+ class MPTBlock(nn.Module):
21
+
22
+ def __init__(self, d_model: int, n_heads: int, expansion_ratio: int, attn_config: Dict={'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}, resid_pdrop: float=0.0, norm_type: str='low_precision_layernorm', verbose: int=0, device: Optional[str]=None, **kwargs):
23
+ del kwargs
24
+ super().__init__()
25
+ norm_class = NORM_CLASS_REGISTRY[norm_type.lower()]
26
+ attn_class = ATTN_CLASS_REGISTRY[attn_config['attn_type']]
27
+ self.norm_1 = norm_class(d_model, device=device)
28
+ self.attn = attn_class(attn_impl=attn_config['attn_impl'], clip_qkv=attn_config['clip_qkv'], qk_ln=attn_config['qk_ln'], softmax_scale=attn_config['softmax_scale'], attn_pdrop=attn_config['attn_pdrop'], d_model=d_model, n_heads=n_heads, verbose=verbose, device=device)
29
+ self.norm_2 = norm_class(d_model, device=device)
30
+ self.ffn = MPTMLP(d_model=d_model, expansion_ratio=expansion_ratio, device=device)
31
+ self.resid_attn_dropout = nn.Dropout(resid_pdrop)
32
+ self.resid_ffn_dropout = nn.Dropout(resid_pdrop)
33
+
34
+ def forward(self, x: torch.Tensor, past_key_value: Optional[Tuple[torch.Tensor]]=None, attn_bias: Optional[torch.Tensor]=None, attention_mask: Optional[torch.ByteTensor]=None, is_causal: bool=True) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor]]]:
35
+ a = self.norm_1(x)
36
+ (b, attn_weights, past_key_value) = self.attn(a, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=is_causal)
37
+ x = x + self.resid_attn_dropout(b)
38
+ m = self.norm_2(x)
39
+ n = self.ffn(m)
40
+ x = x + self.resid_ffn_dropout(n)
41
+ return (x, attn_weights, past_key_value)
dam/model/language_model/mpt_ignored/configuration_mpt.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A HuggingFace-style model configuration."""
2
+ from typing import Dict, Optional, Union
3
+ from transformers import PretrainedConfig
4
+ attn_config_defaults: Dict = {'attn_type': 'multihead_attention', 'attn_pdrop': 0.0, 'attn_impl': 'triton', 'qk_ln': False, 'clip_qkv': None, 'softmax_scale': None, 'prefix_lm': False, 'attn_uses_sequence_id': False, 'alibi': False, 'alibi_bias_max': 8}
5
+ init_config_defaults: Dict = {'name': 'kaiming_normal_', 'fan_mode': 'fan_in', 'init_nonlinearity': 'relu', 'init_div_is_residual': True, 'emb_init_std': None, 'emb_init_uniform_lim': None, 'init_std': None, 'init_gain': 0.0}
6
+
7
+ class MPTConfig(PretrainedConfig):
8
+ model_type = 'mpt'
9
+
10
+ def __init__(self, d_model: int=2048, n_heads: int=16, n_layers: int=24, expansion_ratio: int=4, max_seq_len: int=2048, vocab_size: int=50368, resid_pdrop: float=0.0, emb_pdrop: float=0.0, learned_pos_emb: bool=True, attn_config: Dict=attn_config_defaults, init_device: str='cpu', logit_scale: Optional[Union[float, str]]=None, no_bias: bool=False, verbose: int=0, embedding_fraction: float=1.0, norm_type: str='low_precision_layernorm', use_cache: bool=False, init_config: Dict=init_config_defaults, **kwargs):
11
+ """The MPT configuration class.
12
+
13
+ Args:
14
+ d_model (int): The size of the embedding dimension of the model.
15
+ n_heads (int): The number of attention heads.
16
+ n_layers (int): The number of layers in the model.
17
+ expansion_ratio (int): The ratio of the up/down scale in the MLP.
18
+ max_seq_len (int): The maximum sequence length of the model.
19
+ vocab_size (int): The size of the vocabulary.
20
+ resid_pdrop (float): The dropout probability applied to the attention output before combining with residual.
21
+ emb_pdrop (float): The dropout probability for the embedding layer.
22
+ learned_pos_emb (bool): Whether to use learned positional embeddings
23
+ attn_config (Dict): A dictionary used to configure the model's attention module:
24
+ attn_type (str): type of attention to use. Options: multihead_attention, multiquery_attention
25
+ attn_pdrop (float): The dropout probability for the attention layers.
26
+ attn_impl (str): The attention implementation to use. One of 'torch', 'flash', or 'triton'.
27
+ qk_ln (bool): Whether to apply layer normalization to the queries and keys in the attention layer.
28
+ clip_qkv (Optional[float]): If not None, clip the queries, keys, and values in the attention layer to
29
+ this value.
30
+ softmax_scale (Optional[float]): If not None, scale the softmax in the attention layer by this value. If None,
31
+ use the default scale of ``1/sqrt(d_keys)``.
32
+ prefix_lm (Optional[bool]): Whether the model should operate as a Prefix LM. This requires passing an
33
+ extra `prefix_mask` argument which indicates which tokens belong to the prefix. Tokens in the prefix
34
+ can attend to one another bi-directionally. Tokens outside the prefix use causal attention.
35
+ attn_uses_sequence_id (Optional[bool]): Whether to restrict attention to tokens that have the same sequence_id.
36
+ When the model is in `train` mode, this requires passing an extra `sequence_id` argument which indicates
37
+ which sub-sequence each token belongs to.
38
+ Defaults to ``False`` meaning any provided `sequence_id` will be ignored.
39
+ alibi (bool): Whether to use the alibi bias instead of position embeddings.
40
+ alibi_bias_max (int): The maximum value of the alibi bias.
41
+ init_device (str): The device to use for parameter initialization.
42
+ logit_scale (Optional[Union[float, str]]): If not None, scale the logits by this value.
43
+ no_bias (bool): Whether to use bias in all layers.
44
+ verbose (int): The verbosity level. 0 is silent.
45
+ embedding_fraction (float): The fraction to scale the gradients of the embedding layer by.
46
+ norm_type (str): choose type of norm to use
47
+ multiquery_attention (bool): Whether to use multiquery attention implementation.
48
+ use_cache (bool): Whether or not the model should return the last key/values attentions
49
+ init_config (Dict): A dictionary used to configure the model initialization:
50
+ init_config.name: The parameter initialization scheme to use. Options: 'default_', 'baseline_',
51
+ 'kaiming_uniform_', 'kaiming_normal_', 'neox_init_', 'small_init_', 'xavier_uniform_', or
52
+ 'xavier_normal_'. These mimic the parameter initialization methods in PyTorch.
53
+ init_div_is_residual (Union[int, float, str, bool]): Value to divide initial weights by if ``module._is_residual`` is True.
54
+ emb_init_std (Optional[float]): The standard deviation of the normal distribution used to initialize the embedding layer.
55
+ emb_init_uniform_lim (Optional[Union[Tuple[float, float], float]]): The lower and upper limits of the uniform distribution
56
+ used to initialize the embedding layer. Mutually exclusive with ``emb_init_std``.
57
+ init_std (float): The standard deviation of the normal distribution used to initialize the model,
58
+ if using the baseline_ parameter initialization scheme.
59
+ init_gain (float): The gain to use for parameter initialization with kaiming or xavier initialization schemes.
60
+ fan_mode (str): The fan mode to use for parameter initialization with kaiming initialization schemes.
61
+ init_nonlinearity (str): The nonlinearity to use for parameter initialization with kaiming initialization schemes.
62
+ ---
63
+ See llmfoundry.models.utils.param_init_fns.py for info on other param init config options
64
+ """
65
+ self.d_model = d_model
66
+ self.n_heads = n_heads
67
+ self.n_layers = n_layers
68
+ self.expansion_ratio = expansion_ratio
69
+ self.max_seq_len = max_seq_len
70
+ self.vocab_size = vocab_size
71
+ self.resid_pdrop = resid_pdrop
72
+ self.emb_pdrop = emb_pdrop
73
+ self.learned_pos_emb = learned_pos_emb
74
+ self.attn_config = attn_config
75
+ self.init_device = init_device
76
+ self.logit_scale = logit_scale
77
+ self.no_bias = no_bias
78
+ self.verbose = verbose
79
+ self.embedding_fraction = embedding_fraction
80
+ self.norm_type = norm_type
81
+ self.use_cache = use_cache
82
+ self.init_config = init_config
83
+ if 'name' in kwargs:
84
+ del kwargs['name']
85
+ if 'loss_fn' in kwargs:
86
+ del kwargs['loss_fn']
87
+ super().__init__(**kwargs)
88
+ self._validate_config()
89
+
90
+ def _set_config_defaults(self, config, config_defaults):
91
+ for (k, v) in config_defaults.items():
92
+ if k not in config:
93
+ config[k] = v
94
+ return config
95
+
96
+ def _validate_config(self):
97
+ self.attn_config = self._set_config_defaults(self.attn_config, attn_config_defaults)
98
+ self.init_config = self._set_config_defaults(self.init_config, init_config_defaults)
99
+ if self.d_model % self.n_heads != 0:
100
+ raise ValueError('d_model must be divisible by n_heads')
101
+ if any((prob < 0 or prob > 1 for prob in [self.attn_config['attn_pdrop'], self.resid_pdrop, self.emb_pdrop])):
102
+ raise ValueError("self.attn_config['attn_pdrop'], resid_pdrop, emb_pdrop are probabilities and must be between 0 and 1")
103
+ if self.attn_config['attn_impl'] not in ['torch', 'flash', 'triton']:
104
+ raise ValueError(f"Unknown attn_impl={self.attn_config['attn_impl']}")
105
+ if self.attn_config['prefix_lm'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
106
+ raise NotImplementedError('prefix_lm only implemented with torch and triton attention.')
107
+ if self.attn_config['alibi'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
108
+ raise NotImplementedError('alibi only implemented with torch and triton attention.')
109
+ if self.attn_config['attn_uses_sequence_id'] and self.attn_config['attn_impl'] not in ['torch', 'triton']:
110
+ raise NotImplementedError('attn_uses_sequence_id only implemented with torch and triton attention.')
111
+ if self.embedding_fraction > 1 or self.embedding_fraction <= 0:
112
+ raise ValueError('model.embedding_fraction must be between 0 (exclusive) and 1 (inclusive)!')
113
+ if isinstance(self.logit_scale, str) and self.logit_scale != 'inv_sqrt_d_model':
114
+ raise ValueError(f"self.logit_scale={self.logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
115
+ if self.init_config.get('name', None) is None:
116
+ raise ValueError(f"self.init_config={self.init_config!r} 'name' needs to be set.")
117
+ if not self.learned_pos_emb and (not self.attn_config['alibi']):
118
+ raise ValueError(f'Positional information must be provided to the model using either learned_pos_emb or alibi.')
dam/model/language_model/mpt_ignored/custom_embedding.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from torch import Tensor
5
+
6
+ class SharedEmbedding(nn.Embedding):
7
+
8
+ def forward(self, input: Tensor, unembed: bool=False) -> Tensor:
9
+ if unembed:
10
+ return F.linear(input, self.weight)
11
+ return super().forward(input)
dam/model/language_model/mpt_ignored/flash_attn_triton.py ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copied from https://github.com/HazyResearch/flash-attention/blob/eff9fe6b8076df59d64d7a3f464696738a3c7c24/flash_attn/flash_attn_triton.py
3
+ update imports to use 'triton_pre_mlir'
4
+
5
+ *Experimental* implementation of FlashAttention in Triton.
6
+ Tested with triton==2.0.0.dev20221202.
7
+ Triton 2.0 has a new backend (MLIR) but seems like it doesn't yet work for head dimensions
8
+ other than 64:
9
+ https://github.com/openai/triton/blob/d376020f90002757eea3ea9475d4f7cfc2ec5ead/python/triton/ops/flash_attention.py#L207
10
+ We'll update this implementation with the new Triton backend once this is fixed.
11
+
12
+ We use the FlashAttention implementation from Phil Tillet a starting point.
13
+ https://github.com/openai/triton/blob/master/python/tutorials/06-fused-attention.py
14
+
15
+ Changes:
16
+ - Implement both causal and non-causal attention.
17
+ - Implement both self-attention and cross-attention.
18
+ - Support arbitrary seqlens (not just multiples of 128), for both forward and backward.
19
+ - Support all head dimensions up to 128 (not just 16, 32, 64, 128), for both forward and backward.
20
+ - Support attention bias.
21
+ - Speed up the forward pass a bit, and only store the LSE instead of m and l.
22
+ - Make the backward for d=128 much faster by reducing register spilling.
23
+ - Optionally parallelize the backward pass across seqlen_k, to deal with the case of
24
+ small batch size * nheads.
25
+
26
+ Caution:
27
+ - This is an *experimental* implementation. The forward pass should be quite robust but
28
+ I'm not 100% sure that the backward pass doesn't have race conditions (due to the Triton compiler).
29
+ - This implementation has only been tested on A100.
30
+ - If you plan to use headdim other than 64 and 128, you should test for race conditions
31
+ (due to the Triton compiler), as done in tests/test_flash_attn.py
32
+ "test_flash_attn_triton_race_condition". I've tested and fixed many race conditions
33
+ for different head dimensions (40, 48, 64, 128, 80, 88, 96), but I'm still not 100% confident
34
+ that there are none left for other head dimensions.
35
+
36
+ Differences between this Triton version and the CUDA version:
37
+ - Triton version doesn't support dropout.
38
+ - Triton forward is generally faster than CUDA forward, while Triton backward is
39
+ generally slower than CUDA backward. Overall Triton forward + backward is slightly slower
40
+ than CUDA forward + backward.
41
+ - Triton version doesn't support different sequence lengths in a batch (i.e., RaggedTensor/NestedTensor).
42
+ - Triton version supports attention bias, while CUDA version doesn't.
43
+ """
44
+ import math
45
+ import torch
46
+ import triton_pre_mlir as triton
47
+ import triton_pre_mlir.language as tl
48
+
49
+ @triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
50
+ @triton.jit
51
+ def _fwd_kernel(Q, K, V, Bias, Out, Lse, TMP, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_ob, stride_oh, stride_om, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
52
+ start_m = tl.program_id(0)
53
+ off_hb = tl.program_id(1)
54
+ off_b = off_hb // nheads
55
+ off_h = off_hb % nheads
56
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
57
+ offs_n = tl.arange(0, BLOCK_N)
58
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
59
+ q_ptrs = Q + off_b * stride_qb + off_h * stride_qh + (offs_m[:, None] * stride_qm + offs_d[None, :])
60
+ k_ptrs = K + off_b * stride_kb + off_h * stride_kh + (offs_n[:, None] * stride_kn + offs_d[None, :])
61
+ v_ptrs = V + off_b * stride_vb + off_h * stride_vh + (offs_n[:, None] * stride_vn + offs_d[None, :])
62
+ if BIAS_TYPE == 'vector':
63
+ b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + offs_n
64
+ elif BIAS_TYPE == 'matrix':
65
+ b_ptrs = Bias + off_b * stride_bb + off_h * stride_bh + (offs_m[:, None] * stride_bm + offs_n[None, :])
66
+ t_ptrs = TMP + off_hb * seqlen_q_rounded + offs_m
67
+ lse_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
68
+ m_i = tl.zeros([BLOCK_M], dtype=tl.float32) - float('inf')
69
+ acc_o = tl.zeros([BLOCK_M, BLOCK_HEADDIM], dtype=tl.float32)
70
+ if EVEN_M & EVEN_N:
71
+ if EVEN_HEADDIM:
72
+ q = tl.load(q_ptrs)
73
+ else:
74
+ q = tl.load(q_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
75
+ elif EVEN_HEADDIM:
76
+ q = tl.load(q_ptrs, mask=offs_m[:, None] < seqlen_q, other=0.0)
77
+ else:
78
+ q = tl.load(q_ptrs, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
79
+ end_n = seqlen_k if not IS_CAUSAL else tl.minimum((start_m + 1) * BLOCK_M, seqlen_k)
80
+ for start_n in range(0, end_n, BLOCK_N):
81
+ start_n = tl.multiple_of(start_n, BLOCK_N)
82
+ if EVEN_N & EVEN_M:
83
+ if EVEN_HEADDIM:
84
+ k = tl.load(k_ptrs + start_n * stride_kn)
85
+ else:
86
+ k = tl.load(k_ptrs + start_n * stride_kn, mask=offs_d[None, :] < headdim, other=0.0)
87
+ elif EVEN_HEADDIM:
88
+ k = tl.load(k_ptrs + start_n * stride_kn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
89
+ else:
90
+ k = tl.load(k_ptrs + start_n * stride_kn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
91
+ qk = tl.zeros([BLOCK_M, BLOCK_N], dtype=tl.float32)
92
+ qk += tl.dot(q, k, trans_b=True)
93
+ if not EVEN_N:
94
+ qk += tl.where((start_n + offs_n)[None, :] < seqlen_k, 0, float('-inf'))
95
+ if IS_CAUSAL:
96
+ qk += tl.where(offs_m[:, None] >= (start_n + offs_n)[None, :], 0, float('-inf'))
97
+ if BIAS_TYPE != 'none':
98
+ if BIAS_TYPE == 'vector':
99
+ if EVEN_N:
100
+ bias = tl.load(b_ptrs + start_n).to(tl.float32)
101
+ else:
102
+ bias = tl.load(b_ptrs + start_n, mask=start_n + offs_n < seqlen_k, other=0.0).to(tl.float32)
103
+ bias = bias[None, :]
104
+ elif BIAS_TYPE == 'matrix':
105
+ if EVEN_M & EVEN_N:
106
+ bias = tl.load(b_ptrs + start_n).to(tl.float32)
107
+ else:
108
+ bias = tl.load(b_ptrs + start_n, mask=(offs_m[:, None] < seqlen_q) & ((start_n + offs_n)[None, :] < seqlen_k), other=0.0).to(tl.float32)
109
+ qk = qk * softmax_scale + bias
110
+ m_ij = tl.maximum(tl.max(qk, 1), lse_i)
111
+ p = tl.exp(qk - m_ij[:, None])
112
+ else:
113
+ m_ij = tl.maximum(tl.max(qk, 1) * softmax_scale, lse_i)
114
+ p = tl.exp(qk * softmax_scale - m_ij[:, None])
115
+ l_ij = tl.sum(p, 1)
116
+ acc_o_scale = tl.exp(m_i - m_ij)
117
+ tl.store(t_ptrs, acc_o_scale)
118
+ acc_o_scale = tl.load(t_ptrs)
119
+ acc_o = acc_o * acc_o_scale[:, None]
120
+ if EVEN_N & EVEN_M:
121
+ if EVEN_HEADDIM:
122
+ v = tl.load(v_ptrs + start_n * stride_vn)
123
+ else:
124
+ v = tl.load(v_ptrs + start_n * stride_vn, mask=offs_d[None, :] < headdim, other=0.0)
125
+ elif EVEN_HEADDIM:
126
+ v = tl.load(v_ptrs + start_n * stride_vn, mask=(start_n + offs_n)[:, None] < seqlen_k, other=0.0)
127
+ else:
128
+ v = tl.load(v_ptrs + start_n * stride_vn, mask=((start_n + offs_n)[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
129
+ p = p.to(v.dtype)
130
+ acc_o += tl.dot(p, v)
131
+ m_i = m_ij
132
+ l_i_new = tl.exp(lse_i - m_ij) + l_ij
133
+ lse_i = m_ij + tl.log(l_i_new)
134
+ o_scale = tl.exp(m_i - lse_i)
135
+ tl.store(t_ptrs, o_scale)
136
+ o_scale = tl.load(t_ptrs)
137
+ acc_o = acc_o * o_scale[:, None]
138
+ start_m = tl.program_id(0)
139
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
140
+ lse_ptrs = Lse + off_hb * seqlen_q_rounded + offs_m
141
+ tl.store(lse_ptrs, lse_i)
142
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
143
+ out_ptrs = Out + off_b * stride_ob + off_h * stride_oh + (offs_m[:, None] * stride_om + offs_d[None, :])
144
+ if EVEN_M:
145
+ if EVEN_HEADDIM:
146
+ tl.store(out_ptrs, acc_o)
147
+ else:
148
+ tl.store(out_ptrs, acc_o, mask=offs_d[None, :] < headdim)
149
+ elif EVEN_HEADDIM:
150
+ tl.store(out_ptrs, acc_o, mask=offs_m[:, None] < seqlen_q)
151
+ else:
152
+ tl.store(out_ptrs, acc_o, mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
153
+
154
+ @triton.jit
155
+ def _bwd_preprocess_do_o_dot(Out, DO, Delta, stride_ob, stride_oh, stride_om, stride_dob, stride_doh, stride_dom, nheads, seqlen_q, seqlen_q_rounded, headdim, BLOCK_M: tl.constexpr, BLOCK_HEADDIM: tl.constexpr):
156
+ start_m = tl.program_id(0)
157
+ off_hb = tl.program_id(1)
158
+ off_b = off_hb // nheads
159
+ off_h = off_hb % nheads
160
+ offs_m = start_m * BLOCK_M + tl.arange(0, BLOCK_M)
161
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
162
+ o = tl.load(Out + off_b * stride_ob + off_h * stride_oh + offs_m[:, None] * stride_om + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
163
+ do = tl.load(DO + off_b * stride_dob + off_h * stride_doh + offs_m[:, None] * stride_dom + offs_d[None, :], mask=(offs_m[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0).to(tl.float32)
164
+ delta = tl.sum(o * do, axis=1)
165
+ tl.store(Delta + off_hb * seqlen_q_rounded + offs_m, delta)
166
+
167
+ @triton.jit
168
+ def _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr):
169
+ if EVEN_N & EVEN_M:
170
+ if EVEN_HEADDIM:
171
+ tl.store(dv_ptrs, dv)
172
+ tl.store(dk_ptrs, dk)
173
+ else:
174
+ tl.store(dv_ptrs, dv, mask=offs_d[None, :] < headdim)
175
+ tl.store(dk_ptrs, dk, mask=offs_d[None, :] < headdim)
176
+ elif EVEN_HEADDIM:
177
+ tl.store(dv_ptrs, dv, mask=offs_n[:, None] < seqlen_k)
178
+ tl.store(dk_ptrs, dk, mask=offs_n[:, None] < seqlen_k)
179
+ else:
180
+ tl.store(dv_ptrs, dv, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
181
+ tl.store(dk_ptrs, dk, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim))
182
+
183
+ @triton.jit
184
+ def _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD: tl.constexpr, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
185
+ begin_m = 0 if not IS_CAUSAL else start_n * BLOCK_N // BLOCK_M * BLOCK_M
186
+ offs_qm = begin_m + tl.arange(0, BLOCK_M)
187
+ offs_n = start_n * BLOCK_N + tl.arange(0, BLOCK_N)
188
+ offs_m = tl.arange(0, BLOCK_M)
189
+ offs_d = tl.arange(0, BLOCK_HEADDIM)
190
+ q_ptrs = Q + (offs_qm[:, None] * stride_qm + offs_d[None, :])
191
+ k_ptrs = K + (offs_n[:, None] * stride_kn + offs_d[None, :])
192
+ v_ptrs = V + (offs_n[:, None] * stride_vn + offs_d[None, :])
193
+ do_ptrs = DO + (offs_qm[:, None] * stride_dom + offs_d[None, :])
194
+ dq_ptrs = DQ + (offs_qm[:, None] * stride_dqm + offs_d[None, :])
195
+ if BIAS_TYPE == 'vector':
196
+ b_ptrs = Bias + offs_n
197
+ elif BIAS_TYPE == 'matrix':
198
+ b_ptrs = Bias + (offs_qm[:, None] * stride_bm + offs_n[None, :])
199
+ dv = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
200
+ dk = tl.zeros([BLOCK_N, BLOCK_HEADDIM], dtype=tl.float32)
201
+ if begin_m >= seqlen_q:
202
+ dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
203
+ dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
204
+ _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
205
+ return
206
+ if EVEN_N & EVEN_M:
207
+ if EVEN_HEADDIM:
208
+ k = tl.load(k_ptrs)
209
+ v = tl.load(v_ptrs)
210
+ else:
211
+ k = tl.load(k_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
212
+ v = tl.load(v_ptrs, mask=offs_d[None, :] < headdim, other=0.0)
213
+ elif EVEN_HEADDIM:
214
+ k = tl.load(k_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
215
+ v = tl.load(v_ptrs, mask=offs_n[:, None] < seqlen_k, other=0.0)
216
+ else:
217
+ k = tl.load(k_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
218
+ v = tl.load(v_ptrs, mask=(offs_n[:, None] < seqlen_k) & (offs_d[None, :] < headdim), other=0.0)
219
+ num_block_m = tl.cdiv(seqlen_q, BLOCK_M)
220
+ for start_m in range(begin_m, num_block_m * BLOCK_M, BLOCK_M):
221
+ start_m = tl.multiple_of(start_m, BLOCK_M)
222
+ offs_m_curr = start_m + offs_m
223
+ if EVEN_M & EVEN_HEADDIM:
224
+ q = tl.load(q_ptrs)
225
+ elif EVEN_HEADDIM:
226
+ q = tl.load(q_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0)
227
+ else:
228
+ q = tl.load(q_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
229
+ qk = tl.dot(q, k, trans_b=True)
230
+ if not EVEN_N:
231
+ qk = tl.where(offs_n[None, :] < seqlen_k, qk, float('-inf'))
232
+ if IS_CAUSAL:
233
+ qk = tl.where(offs_m_curr[:, None] >= offs_n[None, :], qk, float('-inf'))
234
+ if BIAS_TYPE != 'none':
235
+ tl.debug_barrier()
236
+ if BIAS_TYPE == 'vector':
237
+ if EVEN_N:
238
+ bias = tl.load(b_ptrs).to(tl.float32)
239
+ else:
240
+ bias = tl.load(b_ptrs, mask=offs_n < seqlen_k, other=0.0).to(tl.float32)
241
+ bias = bias[None, :]
242
+ elif BIAS_TYPE == 'matrix':
243
+ if EVEN_M & EVEN_N:
244
+ bias = tl.load(b_ptrs).to(tl.float32)
245
+ else:
246
+ bias = tl.load(b_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_n[None, :] < seqlen_k), other=0.0).to(tl.float32)
247
+ qk = qk * softmax_scale + bias
248
+ if not EVEN_M & EVEN_HEADDIM:
249
+ tl.debug_barrier()
250
+ lse_i = tl.load(LSE + offs_m_curr)
251
+ if BIAS_TYPE == 'none':
252
+ p = tl.exp(qk * softmax_scale - lse_i[:, None])
253
+ else:
254
+ p = tl.exp(qk - lse_i[:, None])
255
+ if EVEN_M & EVEN_HEADDIM:
256
+ do = tl.load(do_ptrs)
257
+ else:
258
+ do = tl.load(do_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0)
259
+ dv += tl.dot(p.to(do.dtype), do, trans_a=True)
260
+ if not EVEN_M & EVEN_HEADDIM:
261
+ tl.debug_barrier()
262
+ dp = tl.dot(do, v, trans_b=True)
263
+ if not EVEN_HEADDIM:
264
+ tl.debug_barrier()
265
+ Di = tl.load(D + offs_m_curr)
266
+ ds = (p * (dp - Di[:, None]) * softmax_scale).to(q.dtype)
267
+ dk += tl.dot(ds, q, trans_a=True)
268
+ if not EVEN_M & EVEN_HEADDIM:
269
+ tl.debug_barrier()
270
+ if not ATOMIC_ADD:
271
+ if EVEN_M & EVEN_HEADDIM:
272
+ dq = tl.load(dq_ptrs, eviction_policy='evict_last')
273
+ dq += tl.dot(ds, k)
274
+ tl.store(dq_ptrs, dq, eviction_policy='evict_last')
275
+ elif EVEN_HEADDIM:
276
+ dq = tl.load(dq_ptrs, mask=offs_m_curr[:, None] < seqlen_q, other=0.0, eviction_policy='evict_last')
277
+ dq += tl.dot(ds, k)
278
+ tl.store(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q, eviction_policy='evict_last')
279
+ else:
280
+ dq = tl.load(dq_ptrs, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), other=0.0, eviction_policy='evict_last')
281
+ dq += tl.dot(ds, k)
282
+ tl.store(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim), eviction_policy='evict_last')
283
+ else:
284
+ dq = tl.dot(ds, k)
285
+ if EVEN_M & EVEN_HEADDIM:
286
+ tl.atomic_add(dq_ptrs, dq)
287
+ elif EVEN_HEADDIM:
288
+ tl.atomic_add(dq_ptrs, dq, mask=offs_m_curr[:, None] < seqlen_q)
289
+ else:
290
+ tl.atomic_add(dq_ptrs, dq, mask=(offs_m_curr[:, None] < seqlen_q) & (offs_d[None, :] < headdim))
291
+ dq_ptrs += BLOCK_M * stride_dqm
292
+ q_ptrs += BLOCK_M * stride_qm
293
+ do_ptrs += BLOCK_M * stride_dom
294
+ if BIAS_TYPE == 'matrix':
295
+ b_ptrs += BLOCK_M * stride_bm
296
+ dv_ptrs = DV + (offs_n[:, None] * stride_dvn + offs_d[None, :])
297
+ dk_ptrs = DK + (offs_n[:, None] * stride_dkn + offs_d[None, :])
298
+ _bwd_store_dk_dv(dk_ptrs, dv_ptrs, dk, dv, offs_n, offs_d, seqlen_k, headdim, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM)
299
+
300
+ def init_to_zero(name):
301
+ return lambda nargs: nargs[name].zero_()
302
+
303
+ @triton.autotune(configs=[triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': False}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ')), triton.Config({'BLOCK_M': 128, 'BLOCK_N': 128, 'SEQUENCE_PARALLEL': True}, num_warps=8, num_stages=1, pre_hook=init_to_zero('DQ'))], key=['CACHE_KEY_SEQLEN_Q', 'CACHE_KEY_SEQLEN_K', 'BIAS_TYPE', 'IS_CAUSAL', 'BLOCK_HEADDIM'])
304
+ @triton.heuristics({'EVEN_M': lambda args: args['seqlen_q'] % args['BLOCK_M'] == 0, 'EVEN_N': lambda args: args['seqlen_k'] % args['BLOCK_N'] == 0, 'EVEN_HEADDIM': lambda args: args['headdim'] == args['BLOCK_HEADDIM']})
305
+ @triton.jit
306
+ def _bwd_kernel(Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qb, stride_qh, stride_qm, stride_kb, stride_kh, stride_kn, stride_vb, stride_vh, stride_vn, stride_bb, stride_bh, stride_bm, stride_dob, stride_doh, stride_dom, stride_dqb, stride_dqh, stride_dqm, stride_dkb, stride_dkh, stride_dkn, stride_dvb, stride_dvh, stride_dvn, nheads, seqlen_q, seqlen_k, seqlen_q_rounded, headdim, CACHE_KEY_SEQLEN_Q, CACHE_KEY_SEQLEN_K, BIAS_TYPE: tl.constexpr, IS_CAUSAL: tl.constexpr, BLOCK_HEADDIM: tl.constexpr, SEQUENCE_PARALLEL: tl.constexpr, EVEN_M: tl.constexpr, EVEN_N: tl.constexpr, EVEN_HEADDIM: tl.constexpr, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
307
+ off_hb = tl.program_id(1)
308
+ off_b = off_hb // nheads
309
+ off_h = off_hb % nheads
310
+ Q += off_b * stride_qb + off_h * stride_qh
311
+ K += off_b * stride_kb + off_h * stride_kh
312
+ V += off_b * stride_vb + off_h * stride_vh
313
+ DO += off_b * stride_dob + off_h * stride_doh
314
+ DQ += off_b * stride_dqb + off_h * stride_dqh
315
+ DK += off_b * stride_dkb + off_h * stride_dkh
316
+ DV += off_b * stride_dvb + off_h * stride_dvh
317
+ if BIAS_TYPE != 'none':
318
+ Bias += off_b * stride_bb + off_h * stride_bh
319
+ D += off_hb * seqlen_q_rounded
320
+ LSE += off_hb * seqlen_q_rounded
321
+ if not SEQUENCE_PARALLEL:
322
+ num_block_n = tl.cdiv(seqlen_k, BLOCK_N)
323
+ for start_n in range(0, num_block_n):
324
+ _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=False, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
325
+ else:
326
+ start_n = tl.program_id(0)
327
+ _bwd_kernel_one_col_block(start_n, Q, K, V, Bias, DO, DQ, DK, DV, LSE, D, softmax_scale, stride_qm, stride_kn, stride_vn, stride_bm, stride_dom, stride_dqm, stride_dkn, stride_dvn, seqlen_q, seqlen_k, headdim, ATOMIC_ADD=True, BIAS_TYPE=BIAS_TYPE, IS_CAUSAL=IS_CAUSAL, BLOCK_HEADDIM=BLOCK_HEADDIM, EVEN_M=EVEN_M, EVEN_N=EVEN_N, EVEN_HEADDIM=EVEN_HEADDIM, BLOCK_M=BLOCK_M, BLOCK_N=BLOCK_N)
328
+
329
+ def _flash_attn_forward(q, k, v, bias=None, causal=False, softmax_scale=None):
330
+ (batch, seqlen_q, nheads, d) = q.shape
331
+ (_, seqlen_k, _, _) = k.shape
332
+ assert k.shape == (batch, seqlen_k, nheads, d)
333
+ assert v.shape == (batch, seqlen_k, nheads, d)
334
+ assert d <= 128, 'FlashAttention only support head dimensions up to 128'
335
+ assert q.dtype == k.dtype == v.dtype, 'All tensors must have the same type'
336
+ assert q.dtype in [torch.float16, torch.bfloat16], 'Only support fp16 and bf16'
337
+ assert q.is_cuda and k.is_cuda and v.is_cuda
338
+ softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
339
+ has_bias = bias is not None
340
+ bias_type = 'none'
341
+ if has_bias:
342
+ assert bias.dtype in [q.dtype, torch.float]
343
+ assert bias.is_cuda
344
+ assert bias.dim() == 4
345
+ if bias.stride(-1) != 1:
346
+ bias = bias.contiguous()
347
+ if bias.shape[2:] == (1, seqlen_k):
348
+ bias_type = 'vector'
349
+ elif bias.shape[2:] == (seqlen_q, seqlen_k):
350
+ bias_type = 'matrix'
351
+ else:
352
+ raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
353
+ bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
354
+ bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
355
+ seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
356
+ lse = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
357
+ tmp = torch.empty((batch, nheads, seqlen_q_rounded), device=q.device, dtype=torch.float32)
358
+ o = torch.empty_like(q)
359
+ BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
360
+ BLOCK = 128
361
+ num_warps = 4 if d <= 64 else 8
362
+ grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
363
+ _fwd_kernel[grid](q, k, v, bias, o, lse, tmp, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, o.stride(0), o.stride(2), o.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM, BLOCK_M=BLOCK, BLOCK_N=BLOCK, num_warps=num_warps, num_stages=1)
364
+ return (o, lse, softmax_scale)
365
+
366
+ def _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=None, causal=False, softmax_scale=None):
367
+ if do.stride(-1) != 1:
368
+ do = do.contiguous()
369
+ (batch, seqlen_q, nheads, d) = q.shape
370
+ (_, seqlen_k, _, _) = k.shape
371
+ assert d <= 128
372
+ seqlen_q_rounded = math.ceil(seqlen_q / 128) * 128
373
+ assert lse.shape == (batch, nheads, seqlen_q_rounded)
374
+ assert q.stride(-1) == k.stride(-1) == v.stride(-1) == o.stride(-1) == 1
375
+ assert dq.stride(-1) == dk.stride(-1) == dv.stride(-1) == 1
376
+ softmax_scale = softmax_scale or 1.0 / math.sqrt(d)
377
+ dq_accum = torch.empty_like(q, dtype=torch.float32)
378
+ delta = torch.empty_like(lse)
379
+ BLOCK_HEADDIM = max(triton.next_power_of_2(d), 16)
380
+ grid = lambda META: (triton.cdiv(seqlen_q, META['BLOCK_M']), batch * nheads)
381
+ _bwd_preprocess_do_o_dot[grid](o, do, delta, o.stride(0), o.stride(2), o.stride(1), do.stride(0), do.stride(2), do.stride(1), nheads, seqlen_q, seqlen_q_rounded, d, BLOCK_M=128, BLOCK_HEADDIM=BLOCK_HEADDIM)
382
+ has_bias = bias is not None
383
+ bias_type = 'none'
384
+ if has_bias:
385
+ assert bias.dtype in [q.dtype, torch.float]
386
+ assert bias.is_cuda
387
+ assert bias.dim() == 4
388
+ assert bias.stride(-1) == 1
389
+ if bias.shape[2:] == (1, seqlen_k):
390
+ bias_type = 'vector'
391
+ elif bias.shape[2:] == (seqlen_q, seqlen_k):
392
+ bias_type = 'matrix'
393
+ else:
394
+ raise RuntimeError('Last 2 dimensions of bias must be (1, seqlen_k) or (seqlen_q, seqlen_k)')
395
+ bias = bias.expand(batch, nheads, seqlen_q, seqlen_k)
396
+ bias_strides = (bias.stride(0), bias.stride(1), bias.stride(2)) if has_bias else (0, 0, 0)
397
+ grid = lambda META: (triton.cdiv(seqlen_k, META['BLOCK_N']) if META['SEQUENCE_PARALLEL'] else 1, batch * nheads)
398
+ _bwd_kernel[grid](q, k, v, bias, do, dq_accum, dk, dv, lse, delta, softmax_scale, q.stride(0), q.stride(2), q.stride(1), k.stride(0), k.stride(2), k.stride(1), v.stride(0), v.stride(2), v.stride(1), *bias_strides, do.stride(0), do.stride(2), do.stride(1), dq_accum.stride(0), dq_accum.stride(2), dq_accum.stride(1), dk.stride(0), dk.stride(2), dk.stride(1), dv.stride(0), dv.stride(2), dv.stride(1), nheads, seqlen_q, seqlen_k, seqlen_q_rounded, d, seqlen_q // 32, seqlen_k // 32, bias_type, causal, BLOCK_HEADDIM)
399
+ dq.copy_(dq_accum)
400
+
401
+ class FlashAttnQKVPackedFunc(torch.autograd.Function):
402
+
403
+ @staticmethod
404
+ def forward(ctx, qkv, bias=None, causal=False, softmax_scale=None):
405
+ """
406
+ qkv: (batch, seqlen, 3, nheads, headdim)
407
+ bias: optional, shape broadcastible to (batch, nheads, seqlen, seqlen).
408
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen).
409
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen, seqlen)
410
+ """
411
+ if qkv.stride(-1) != 1:
412
+ qkv = qkv.contiguous()
413
+ (o, lse, ctx.softmax_scale) = _flash_attn_forward(qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], bias=bias, causal=causal, softmax_scale=softmax_scale)
414
+ ctx.save_for_backward(qkv, o, lse, bias)
415
+ ctx.causal = causal
416
+ return o
417
+
418
+ @staticmethod
419
+ def backward(ctx, do):
420
+ (qkv, o, lse, bias) = ctx.saved_tensors
421
+ assert not ctx.needs_input_grad[1], 'FlashAttention does not support bias gradient yet'
422
+ with torch.inference_mode():
423
+ dqkv = torch.empty_like(qkv)
424
+ _flash_attn_backward(do, qkv[:, :, 0], qkv[:, :, 1], qkv[:, :, 2], o, lse, dqkv[:, :, 0], dqkv[:, :, 1], dqkv[:, :, 2], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
425
+ return (dqkv, None, None, None)
426
+ flash_attn_qkvpacked_func = FlashAttnQKVPackedFunc.apply
427
+
428
+ class FlashAttnKVPackedFunc(torch.autograd.Function):
429
+
430
+ @staticmethod
431
+ def forward(ctx, q, kv, bias=None, causal=False, softmax_scale=None):
432
+ """
433
+ q: (batch, seqlen_q, nheads, headdim)
434
+ kv: (batch, seqlen_k, 2, nheads, headdim)
435
+ bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
436
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
437
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
438
+ """
439
+ (q, kv) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, kv]]
440
+ (o, lse, ctx.softmax_scale) = _flash_attn_forward(q, kv[:, :, 0], kv[:, :, 1], bias=bias, causal=causal, softmax_scale=softmax_scale)
441
+ ctx.save_for_backward(q, kv, o, lse, bias)
442
+ ctx.causal = causal
443
+ return o
444
+
445
+ @staticmethod
446
+ def backward(ctx, do):
447
+ (q, kv, o, lse, bias) = ctx.saved_tensors
448
+ if len(ctx.needs_input_grad) >= 3:
449
+ assert not ctx.needs_input_grad[2], 'FlashAttention does not support bias gradient yet'
450
+ with torch.inference_mode():
451
+ dq = torch.empty_like(q)
452
+ dkv = torch.empty_like(kv)
453
+ _flash_attn_backward(do, q, kv[:, :, 0], kv[:, :, 1], o, lse, dq, dkv[:, :, 0], dkv[:, :, 1], bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
454
+ return (dq, dkv, None, None, None)
455
+ flash_attn_kvpacked_func = FlashAttnKVPackedFunc.apply
456
+
457
+ class FlashAttnFunc(torch.autograd.Function):
458
+
459
+ @staticmethod
460
+ def forward(ctx, q, k, v, bias=None, causal=False, softmax_scale=None):
461
+ """
462
+ q: (batch_size, seqlen_q, nheads, headdim)
463
+ k, v: (batch_size, seqlen_k, nheads, headdim)
464
+ bias: optional, shape broadcastible to (batch, nheads, seqlen_q, seqlen_k).
465
+ For example, ALiBi mask for causal would have shape (1, nheads, 1, seqlen_k).
466
+ ALiBi mask for non-causal would have shape (1, nheads, seqlen_q, seqlen_k)
467
+ """
468
+ (q, k, v) = [x if x.stride(-1) == 1 else x.contiguous() for x in [q, k, v]]
469
+ (o, lse, ctx.softmax_scale) = _flash_attn_forward(q, k, v, bias=bias, causal=causal, softmax_scale=softmax_scale)
470
+ ctx.save_for_backward(q, k, v, o, lse, bias)
471
+ ctx.causal = causal
472
+ return o
473
+
474
+ @staticmethod
475
+ def backward(ctx, do):
476
+ (q, k, v, o, lse, bias) = ctx.saved_tensors
477
+ assert not ctx.needs_input_grad[3], 'FlashAttention does not support bias gradient yet'
478
+ with torch.inference_mode():
479
+ dq = torch.empty_like(q)
480
+ dk = torch.empty_like(k)
481
+ dv = torch.empty_like(v)
482
+ _flash_attn_backward(do, q, k, v, o, lse, dq, dk, dv, bias=bias, causal=ctx.causal, softmax_scale=ctx.softmax_scale)
483
+ return (dq, dk, dv, None, None, None)
484
+ flash_attn_func = FlashAttnFunc.apply
dam/model/language_model/mpt_ignored/hf_prefixlm_converter.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Converts Huggingface Causal LM to Prefix LM.
2
+
3
+ Conversion does lightweight surgery on a HuggingFace
4
+ Causal LM to convert it to a Prefix LM.
5
+
6
+ Prefix LMs accepts a `bidirectional_mask` input in `forward`
7
+ and treat the input prompt as the prefix in `generate`.
8
+ """
9
+ import math
10
+ import warnings
11
+ from types import MethodType
12
+ from typing import Any, Dict, List, Optional, Tuple, Union
13
+ import torch
14
+ from transformers.models.bloom.modeling_bloom import BaseModelOutputWithPastAndCrossAttentions, BloomForCausalLM, BloomModel, CausalLMOutputWithCrossAttentions, CrossEntropyLoss
15
+ from transformers.models.bloom.modeling_bloom import _expand_mask as _expand_mask_bloom
16
+ from transformers.models.bloom.modeling_bloom import _make_causal_mask as _make_causal_mask_bloom
17
+ from transformers.models.bloom.modeling_bloom import logging
18
+ from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel
19
+ from transformers.models.gpt_neo.modeling_gpt_neo import GPTNeoForCausalLM
20
+ from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXForCausalLM
21
+ from transformers.models.gptj.modeling_gptj import GPTJForCausalLM
22
+ from transformers.models.opt.modeling_opt import OPTForCausalLM
23
+ from transformers.models.opt.modeling_opt import _expand_mask as _expand_mask_opt
24
+ from transformers.models.opt.modeling_opt import _make_causal_mask as _make_causal_mask_opt
25
+ logger = logging.get_logger(__name__)
26
+ _SUPPORTED_GPT_MODELS = (GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM)
27
+ CAUSAL_GPT_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM]
28
+
29
+ def _convert_gpt_causal_lm_to_prefix_lm(model: CAUSAL_GPT_TYPES) -> CAUSAL_GPT_TYPES:
30
+ """Converts a GPT-style Causal LM to a Prefix LM.
31
+
32
+ Supported HuggingFace model classes:
33
+ - `GPT2LMHeadModel`
34
+ - `GPTNeoForCausalLM`
35
+ - `GPTNeoXForCausalLM`
36
+ - `GPTJForCausalLM`
37
+
38
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
39
+ """
40
+ if hasattr(model, '_prefix_lm_converted'):
41
+ return model
42
+ assert isinstance(model, _SUPPORTED_GPT_MODELS)
43
+ assert model.config.add_cross_attention == False, 'Only supports GPT-style decoder-only models'
44
+
45
+ def _get_attn_modules(model: CAUSAL_GPT_TYPES) -> List[torch.nn.Module]:
46
+ """Helper that gets a list of the model's attention modules.
47
+
48
+ Each module has a `bias` buffer used for causal masking. The Prefix LM
49
+ conversion adds logic to dynamically manipulate these biases to support
50
+ Prefix LM attention masking.
51
+ """
52
+ attn_modules = []
53
+ if isinstance(model, GPTNeoXForCausalLM):
54
+ blocks = model.gpt_neox.layers
55
+ else:
56
+ blocks = model.transformer.h
57
+ for block in blocks:
58
+ if isinstance(model, GPTNeoForCausalLM):
59
+ if block.attn.attention_type != 'global':
60
+ continue
61
+ attn_module = block.attn.attention
62
+ elif isinstance(model, GPTNeoXForCausalLM):
63
+ attn_module = block.attention
64
+ else:
65
+ attn_module = block.attn
66
+ attn_modules.append(attn_module)
67
+ return attn_modules
68
+ setattr(model, '_original_forward', getattr(model, 'forward'))
69
+ setattr(model, '_original_generate', getattr(model, 'generate'))
70
+
71
+ def forward(self: CAUSAL_GPT_TYPES, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[Tuple[torch.Tensor]]]=None, attention_mask: Optional[torch.FloatTensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, token_type_ids: Optional[torch.LongTensor]=None, position_ids: Optional[torch.LongTensor]=None, head_mask: Optional[torch.FloatTensor]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
72
+ """Wraps original forward to enable PrefixLM attention."""
73
+
74
+ def call_og_forward():
75
+ if isinstance(self, GPTNeoXForCausalLM):
76
+ return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
77
+ else:
78
+ return self._original_forward(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
79
+ if bidirectional_mask is None:
80
+ return call_og_forward()
81
+ assert isinstance(bidirectional_mask, torch.Tensor)
82
+ attn_modules = _get_attn_modules(model)
83
+ (b, s) = bidirectional_mask.shape
84
+ max_length = attn_modules[0].bias.shape[-1]
85
+ if s > max_length:
86
+ raise ValueError(f'bidirectional_mask sequence length (={s}) exceeds the ' + f'max length allowed by the model ({max_length}).')
87
+ assert s <= max_length
88
+ if s < max_length:
89
+ pad = torch.zeros((int(b), int(max_length - s)), dtype=bidirectional_mask.dtype, device=bidirectional_mask.device)
90
+ bidirectional_mask = torch.cat([bidirectional_mask, pad], dim=1)
91
+ bidirectional = bidirectional_mask.unsqueeze(1).unsqueeze(1)
92
+ for attn_module in attn_modules:
93
+ attn_module.bias.data = torch.logical_or(attn_module.bias.data, bidirectional)
94
+ output = call_og_forward()
95
+ for attn_module in attn_modules:
96
+ attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
97
+ return output
98
+
99
+ def generate(self: CAUSAL_GPT_TYPES, *args: tuple, **kwargs: Dict[str, Any]):
100
+ """Wraps original generate to enable PrefixLM attention."""
101
+ attn_modules = _get_attn_modules(model)
102
+ for attn_module in attn_modules:
103
+ attn_module.bias.data[:] = 1
104
+ output = self._original_generate(*args, **kwargs)
105
+ for attn_module in attn_modules:
106
+ attn_module.bias.data = torch.tril(attn_module.bias.data[0, 0])[None, None]
107
+ return output
108
+ setattr(model, 'forward', MethodType(forward, model))
109
+ setattr(model, 'generate', MethodType(generate, model))
110
+ setattr(model, '_prefix_lm_converted', True)
111
+ return model
112
+
113
+ def _convert_bloom_causal_lm_to_prefix_lm(model: BloomForCausalLM) -> BloomForCausalLM:
114
+ """Converts a BLOOM Causal LM to a Prefix LM.
115
+
116
+ Supported HuggingFace model classes:
117
+ - `BloomForCausalLM`
118
+
119
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
120
+ """
121
+ if hasattr(model, '_prefix_lm_converted'):
122
+ return model
123
+ assert isinstance(model, BloomForCausalLM)
124
+ assert model.config.add_cross_attention == False, 'Only supports BLOOM decoder-only models'
125
+
126
+ def _prepare_attn_mask(self: BloomModel, attention_mask: torch.Tensor, bidirectional_mask: Optional[torch.Tensor], input_shape: Tuple[int, int], past_key_values_length: int) -> torch.BoolTensor:
127
+ combined_attention_mask = None
128
+ device = attention_mask.device
129
+ (_, src_length) = input_shape
130
+ if src_length > 1:
131
+ combined_attention_mask = _make_causal_mask_bloom(input_shape, device=device, past_key_values_length=past_key_values_length)
132
+ if bidirectional_mask is not None:
133
+ assert attention_mask.shape == bidirectional_mask.shape
134
+ expanded_bidirectional_mask = _expand_mask_bloom(bidirectional_mask, tgt_length=src_length)
135
+ combined_attention_mask = torch.logical_and(combined_attention_mask, expanded_bidirectional_mask)
136
+ expanded_attn_mask = _expand_mask_bloom(attention_mask, tgt_length=src_length)
137
+ combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask | combined_attention_mask
138
+ return combined_attention_mask
139
+
140
+ def _build_alibi_tensor(self: BloomModel, batch_size: int, query_length: int, key_length: int, dtype: torch.dtype, device: torch.device) -> torch.Tensor:
141
+ num_heads = self.config.n_head
142
+ closest_power_of_2 = 2 ** math.floor(math.log2(num_heads))
143
+ base = torch.tensor(2 ** (-2 ** (-(math.log2(closest_power_of_2) - 3))), device=device, dtype=torch.float32)
144
+ powers = torch.arange(1, 1 + closest_power_of_2, device=device, dtype=torch.int32)
145
+ slopes = torch.pow(base, powers)
146
+ if closest_power_of_2 != num_heads:
147
+ extra_base = torch.tensor(2 ** (-2 ** (-(math.log2(2 * closest_power_of_2) - 3))), device=device, dtype=torch.float32)
148
+ num_remaining_heads = min(closest_power_of_2, num_heads - closest_power_of_2)
149
+ extra_powers = torch.arange(1, 1 + 2 * num_remaining_heads, 2, device=device, dtype=torch.int32)
150
+ slopes = torch.cat([slopes, torch.pow(extra_base, extra_powers)], dim=0)
151
+ qa = torch.arange(query_length, device=device, dtype=torch.int32).view(-1, 1)
152
+ ka = torch.arange(key_length, device=device, dtype=torch.int32).view(1, -1)
153
+ diffs = qa - ka + key_length - query_length
154
+ diffs = -diffs.abs()
155
+ alibi = slopes.view(1, num_heads, 1, 1) * diffs.view(1, 1, query_length, key_length)
156
+ alibi = alibi.expand(batch_size, -1, -1, -1).reshape(-1, query_length, key_length)
157
+ return alibi.to(dtype)
158
+ KeyValueT = Tuple[torch.Tensor, torch.Tensor]
159
+
160
+ def forward(self: BloomModel, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.LongTensor]=None, inputs_embeds: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor, ...], BaseModelOutputWithPastAndCrossAttentions]:
161
+ if deprecated_arguments.pop('position_ids', False) is not False:
162
+ warnings.warn('`position_ids` have no functionality in BLOOM and will be removed in v5.0.0. ' + 'You can safely ignore passing `position_ids`.', FutureWarning)
163
+ if len(deprecated_arguments) > 0:
164
+ raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
165
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
166
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
167
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
168
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
169
+ if input_ids is not None and inputs_embeds is not None:
170
+ raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time')
171
+ elif input_ids is not None:
172
+ (batch_size, seq_length) = input_ids.shape
173
+ elif inputs_embeds is not None:
174
+ (batch_size, seq_length, _) = inputs_embeds.shape
175
+ else:
176
+ raise ValueError('You have to specify either input_ids or inputs_embeds')
177
+ if past_key_values is None:
178
+ past_key_values = tuple([None] * len(self.h))
179
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
180
+ if inputs_embeds is None:
181
+ inputs_embeds = self.word_embeddings(input_ids)
182
+ hidden_states = self.word_embeddings_layernorm(inputs_embeds)
183
+ presents = () if use_cache else None
184
+ all_self_attentions = () if output_attentions else None
185
+ all_hidden_states = () if output_hidden_states else None
186
+ seq_length_with_past = seq_length
187
+ past_key_values_length = 0
188
+ if past_key_values[0] is not None:
189
+ tmp = past_key_values[0][0]
190
+ past_key_values_length = tmp.shape[2]
191
+ seq_length_with_past = seq_length_with_past + past_key_values_length
192
+ if attention_mask is None:
193
+ attention_mask = torch.ones((batch_size, seq_length_with_past), device=hidden_states.device)
194
+ else:
195
+ attention_mask = attention_mask.to(hidden_states.device)
196
+ alibi = self._build_alibi_tensor(batch_size=batch_size, query_length=seq_length, key_length=seq_length_with_past, dtype=hidden_states.dtype, device=hidden_states.device)
197
+ causal_mask = self._prepare_attn_mask(attention_mask, bidirectional_mask, input_shape=(batch_size, seq_length), past_key_values_length=past_key_values_length)
198
+ for (i, (block, layer_past)) in enumerate(zip(self.h, past_key_values)):
199
+ if output_hidden_states:
200
+ hst = (hidden_states,)
201
+ all_hidden_states = all_hidden_states + hst
202
+ if self.gradient_checkpointing and self.training:
203
+ if use_cache:
204
+ logger.warning('`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`...')
205
+ use_cache = False
206
+
207
+ def create_custom_forward(module):
208
+
209
+ def custom_forward(*inputs):
210
+ return module(*inputs, use_cache=use_cache, output_attentions=output_attentions)
211
+ return custom_forward
212
+ outputs = torch.utils.checkpoint.checkpoint(create_custom_forward(block), hidden_states, alibi, causal_mask, head_mask[i])
213
+ else:
214
+ outputs = block(hidden_states, layer_past=layer_past, attention_mask=causal_mask, head_mask=head_mask[i], use_cache=use_cache, output_attentions=output_attentions, alibi=alibi)
215
+ hidden_states = outputs[0]
216
+ if use_cache is True:
217
+ presents = presents + (outputs[1],)
218
+ if output_attentions:
219
+ oa = (outputs[2 if use_cache else 1],)
220
+ all_self_attentions = all_self_attentions + oa
221
+ hidden_states = self.ln_f(hidden_states)
222
+ if output_hidden_states:
223
+ hst = (hidden_states,)
224
+ all_hidden_states = all_hidden_states + hst
225
+ if not return_dict:
226
+ return tuple((v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None))
227
+ return BaseModelOutputWithPastAndCrossAttentions(last_hidden_state=hidden_states, past_key_values=presents, hidden_states=all_hidden_states, attentions=all_self_attentions)
228
+ setattr(model.transformer, '_prepare_attn_mask', MethodType(_prepare_attn_mask, model.transformer))
229
+ setattr(model.transformer, '_build_alibi_tensor', MethodType(_build_alibi_tensor, model.transformer))
230
+ setattr(model.transformer, 'forward', MethodType(forward, model.transformer))
231
+ KeyValueT = Tuple[torch.Tensor, torch.Tensor]
232
+
233
+ def forward(self: BloomForCausalLM, input_ids: Optional[torch.LongTensor]=None, past_key_values: Optional[Tuple[KeyValueT, ...]]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.Tensor]=None, head_mask: Optional[torch.Tensor]=None, inputs_embeds: Optional[torch.Tensor]=None, labels: Optional[torch.Tensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, **deprecated_arguments) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]:
234
+ """Replacement forward method for BloomCausalLM."""
235
+ if deprecated_arguments.pop('position_ids', False) is not False:
236
+ warnings.warn('`position_ids` have no functionality in BLOOM and will be removed ' + 'in v5.0.0. You can safely ignore passing `position_ids`.', FutureWarning)
237
+ if len(deprecated_arguments) > 0:
238
+ raise ValueError(f'Got unexpected arguments: {deprecated_arguments}')
239
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
240
+ transformer_outputs = self.transformer(input_ids, past_key_values=past_key_values, attention_mask=attention_mask, bidirectional_mask=bidirectional_mask, head_mask=head_mask, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
241
+ hidden_states = transformer_outputs[0]
242
+ lm_logits = self.lm_head(hidden_states)
243
+ loss = None
244
+ if labels is not None:
245
+ shift_logits = lm_logits[..., :-1, :].contiguous()
246
+ shift_labels = labels[..., 1:].contiguous()
247
+ (batch_size, seq_length, vocab_size) = shift_logits.shape
248
+ loss_fct = CrossEntropyLoss()
249
+ loss = loss_fct(shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length))
250
+ if not return_dict:
251
+ output = (lm_logits,) + transformer_outputs[1:]
252
+ return (loss,) + output if loss is not None else output
253
+ return CausalLMOutputWithCrossAttentions(loss=loss, logits=lm_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions)
254
+
255
+ def prepare_inputs_for_generation(self: BloomForCausalLM, input_ids: torch.LongTensor, past: Optional[torch.Tensor]=None, attention_mask: Optional[torch.Tensor]=None, **kwargs) -> dict:
256
+ if past:
257
+ input_ids = input_ids[:, -1].unsqueeze(-1)
258
+ bidirectional_mask = None
259
+ if past[0][0].shape[0] == input_ids.shape[0]:
260
+ past = self._convert_to_bloom_cache(past)
261
+ else:
262
+ bidirectional_mask = torch.ones_like(input_ids)
263
+ return {'input_ids': input_ids, 'past_key_values': past, 'use_cache': True, 'attention_mask': attention_mask, 'bidirectional_mask': bidirectional_mask}
264
+ setattr(model, 'forward', MethodType(forward, model))
265
+ setattr(model, 'prepare_inputs_for_generation', MethodType(prepare_inputs_for_generation, model))
266
+ setattr(model, '_prefix_lm_converted', True)
267
+ return model
268
+
269
+ def _convert_opt_causal_lm_to_prefix_lm(model: OPTForCausalLM) -> OPTForCausalLM:
270
+ """Converts an OPT Causal LM to a Prefix LM.
271
+
272
+ Supported HuggingFace model classes:
273
+ - `OPTForCausalLM`
274
+
275
+ See `convert_hf_causal_lm_to_prefix_lm` for more details.
276
+ """
277
+ if hasattr(model, '_prefix_lm_converted'):
278
+ return model
279
+ assert isinstance(model, OPTForCausalLM)
280
+ assert model.config.add_cross_attention == False, 'Only supports OPT decoder-only models'
281
+ setattr(model, '_original_forward', getattr(model, 'forward'))
282
+ setattr(model, '_original_generate', getattr(model, 'generate'))
283
+ model.model.decoder.bidirectional_mask = None
284
+
285
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
286
+ combined_attention_mask = None
287
+ if input_shape[-1] > 1:
288
+ if self.bidirectional_mask == 'g':
289
+ (bsz, src_length) = input_shape
290
+ combined_attention_mask = torch.zeros((bsz, 1, src_length, src_length + past_key_values_length), dtype=inputs_embeds.dtype, device=inputs_embeds.device)
291
+ else:
292
+ combined_attention_mask = _make_causal_mask_opt(input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length).to(inputs_embeds.device)
293
+ if self.bidirectional_mask is not None:
294
+ assert attention_mask.shape == self.bidirectional_mask.shape
295
+ expanded_bidirectional_mask = _expand_mask_opt(self.bidirectional_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
296
+ combined_attention_mask = torch.maximum(expanded_bidirectional_mask, combined_attention_mask)
297
+ if attention_mask is not None:
298
+ expanded_attn_mask = _expand_mask_opt(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(inputs_embeds.device)
299
+ combined_attention_mask = expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
300
+ return combined_attention_mask
301
+ setattr(model.model.decoder, '_prepare_decoder_attention_mask', MethodType(_prepare_decoder_attention_mask, model.model.decoder))
302
+
303
+ def forward(self: OPTForCausalLM, input_ids: Optional[torch.LongTensor]=None, attention_mask: Optional[torch.Tensor]=None, bidirectional_mask: Optional[torch.ByteTensor]=None, head_mask: Optional[torch.Tensor]=None, past_key_values: Optional[List[torch.FloatTensor]]=None, inputs_embeds: Optional[torch.FloatTensor]=None, labels: Optional[torch.LongTensor]=None, use_cache: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None):
304
+
305
+ def call_og_forward():
306
+ return self._original_forward(input_ids=input_ids, attention_mask=attention_mask, head_mask=head_mask, past_key_values=past_key_values, inputs_embeds=inputs_embeds, labels=labels, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict)
307
+ if bidirectional_mask is None:
308
+ return call_og_forward()
309
+ self.model.decoder.bidirectional_mask = bidirectional_mask
310
+ try:
311
+ outputs = call_og_forward()
312
+ except:
313
+ self.model.decoder.bidirectional_mask = None
314
+ raise
315
+ self.model.decoder.bidirectional_mask = None
316
+ return outputs
317
+
318
+ def generate(self: OPTForCausalLM, *args: tuple, **kwargs: Dict[str, Any]):
319
+ """Wraps original generate to enable PrefixLM-style attention."""
320
+ self.model.decoder.bidirectional_mask = 'g'
321
+ try:
322
+ output = self._original_generate(*args, **kwargs)
323
+ except:
324
+ self.model.decoder.bidirectional_mask = None
325
+ raise
326
+ self.model.decoder.bidirectional_mask = None
327
+ return output
328
+ setattr(model, 'forward', MethodType(forward, model))
329
+ setattr(model, 'generate', MethodType(generate, model))
330
+ setattr(model, '_prefix_lm_converted', True)
331
+ return model
332
+ _SUPPORTED_HF_MODELS = _SUPPORTED_GPT_MODELS + (BloomForCausalLM, OPTForCausalLM)
333
+ CAUSAL_LM_TYPES = Union[GPT2LMHeadModel, GPTJForCausalLM, GPTNeoForCausalLM, GPTNeoXForCausalLM, BloomForCausalLM, OPTForCausalLM]
334
+
335
+ def convert_hf_causal_lm_to_prefix_lm(model: CAUSAL_LM_TYPES) -> CAUSAL_LM_TYPES:
336
+ """Converts a HuggingFace Causal LM to a Prefix LM.
337
+
338
+ Supported HuggingFace model classes:
339
+ - `GPT2LMHeadModel`
340
+ - `GPTNeoForCausalLM`
341
+ - `GPTNeoXForCausalLM`
342
+ - `GPTJForCausalLM`
343
+ - `BloomForCausalLM`
344
+ - `OPTForCausalLM`
345
+
346
+ Conversion to a Prefix LM is done by modifying the `forward` method, and possibly also the
347
+ `generate` method and/or select underlying methods depending on the model class.
348
+
349
+ These changes preserve the model API, but add a new input to `forward`: "bidirectional_mask".
350
+
351
+ Notes on training:
352
+ To actually train the converted model as a Prefix LM, training batches will need to indicate
353
+ the prefix/target structure by including `bidirectional_mask` as part of the batch inputs.
354
+
355
+ **This is not a standard input and requires custom layers either within or after your dataloader.**
356
+
357
+ In addition to adding `bidirectional_mask` to the batch, this custom code should modify `labels`
358
+ such that `batch['labels'][batch['bidirectional_mask'] == 1] == -100`.
359
+ That is, the prefix portion of the sequence should not generate any loss. Loss should only be
360
+ generated by the target portion of the sequence.
361
+
362
+ Notes on `GPTNeoForCausalLM`:
363
+ To simplify the implementation, "global" and "local" attention layers are handled differently.
364
+ For "global" layers, we handle conversion as described above. For "local" layers, which use a
365
+ causal attention mask within a restricted local window, we do not alter the masking.
366
+
367
+ Notes on `forward` method conversion:
368
+ After conversion, the `forward` method will handle a new input, `bidirectional_mask`,
369
+ which should be a [batch_size, seq_length] byte tensor, where 1 indicates token positions
370
+ belonging to the prefix (prefix tokens can attend to one another bidirectionally), and
371
+ 0 indicates token positions belonging to the target.
372
+
373
+ The new `forward` method will incorporate `bidirectional_mask` (if supplied) into the existing
374
+ causal mask, call the original `forward` method, and (if the causal mask is a buffer) reset
375
+ the causal masks before returning the result.
376
+
377
+ Notes on `generate` method conversion:
378
+ After conversion, the `generate` method will have the same signature but will internally
379
+ convert all causal masks to be purely bidirectional, call the original `generate` method, and
380
+ (where appropriate) reset the causal masks before returning the result.
381
+
382
+ This works thanks to the logic of the HuggingFace `generate` API, which first encodes the token
383
+ "prompt" passed to `generate` (which is treated as the prefix) and then sequentially generates
384
+ each new token. Encodings are cached as generation happens, so all prefix tokens can attend to one
385
+ another (as expected in a Prefix LM) and generated tokens can only attend to prefix tokens and
386
+ previously-generated tokens (also as expected in a Prefix LM).
387
+
388
+ To preserve the API, the original methods are renamed to `_original_forward` and
389
+ `_original_generate`, and replaced with new `forward` and `generate` methods that wrap
390
+ them, respectively. Although implementation details vary by model class.
391
+ """
392
+ if isinstance(model, _SUPPORTED_GPT_MODELS):
393
+ return _convert_gpt_causal_lm_to_prefix_lm(model)
394
+ elif isinstance(model, BloomForCausalLM):
395
+ return _convert_bloom_causal_lm_to_prefix_lm(model)
396
+ elif isinstance(model, OPTForCausalLM):
397
+ return _convert_opt_causal_lm_to_prefix_lm(model)
398
+ else:
399
+ raise TypeError(f'Cannot convert model to Prefix LM. ' + f'Model does not belong to set of supported HF models:' + f'\n{_SUPPORTED_HF_MODELS}')
400
+
401
+ def add_bidirectional_mask_if_missing(batch: Dict[str, Any]):
402
+ """Attempts to add bidirectional_mask to batch if missing.
403
+
404
+ Raises:
405
+ KeyError if bidirectional_mask is missing and can't be inferred
406
+ """
407
+ if 'bidirectional_mask' not in batch:
408
+ if batch.get('mode', None) == 'icl_task':
409
+ batch['bidirectional_mask'] = batch['attention_mask'].clone()
410
+ for (i, continuation_indices) in enumerate(batch['continuation_indices']):
411
+ batch['bidirectional_mask'][i, continuation_indices] = 0
412
+ elif 'labels' in batch and 'attention_mask' in batch:
413
+ batch['bidirectional_mask'] = torch.logical_and(torch.eq(batch['attention_mask'], 1), torch.eq(batch['labels'], -100)).type_as(batch['attention_mask'])
414
+ else:
415
+ raise KeyError('No bidirectional_mask in batch and not sure how to construct one.')
dam/model/language_model/mpt_ignored/meta_init_context.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import contextmanager
2
+ import torch
3
+ import torch.nn as nn
4
+
5
+ @contextmanager
6
+ def init_empty_weights(include_buffers: bool=False):
7
+ """Meta initialization context manager.
8
+
9
+ A context manager under which models are initialized with all parameters
10
+ on the meta device, therefore creating an empty model. Useful when just
11
+ initializing the model would blow the available RAM.
12
+
13
+ Args:
14
+ include_buffers (`bool`, *optional*, defaults to `False`): Whether or
15
+ not to also put all buffers on the meta device while initializing.
16
+
17
+ Example:
18
+ ```python
19
+ import torch.nn as nn
20
+
21
+ # Initialize a model with 100 billions parameters in no time and without using any RAM.
22
+ with init_empty_weights():
23
+ tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)])
24
+ ```
25
+
26
+ <Tip warning={true}>
27
+
28
+ Any model created under this context manager has no weights. As such you can't do something like
29
+ `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`].
30
+
31
+ </Tip>
32
+ """
33
+ with init_on_device(torch.device('meta'), include_buffers=include_buffers) as f:
34
+ yield f
35
+
36
+ @contextmanager
37
+ def init_on_device(device: torch.device, include_buffers: bool=False):
38
+ """Device initialization context manager.
39
+
40
+ A context manager under which models are initialized with all parameters
41
+ on the specified device.
42
+
43
+ Args:
44
+ device (`torch.device`): Device to initialize all parameters on.
45
+ include_buffers (`bool`, *optional*, defaults to `False`): Whether or
46
+ not to also put all buffers on the meta device while initializing.
47
+
48
+ Example:
49
+ ```python
50
+ import torch.nn as nn
51
+
52
+ with init_on_device(device=torch.device("cuda")):
53
+ tst = nn.Liner(100, 100) # on `cuda` device
54
+ ```
55
+ """
56
+ old_register_parameter = nn.Module.register_parameter
57
+ if include_buffers:
58
+ old_register_buffer = nn.Module.register_buffer
59
+
60
+ def register_empty_parameter(module, name, param):
61
+ old_register_parameter(module, name, param)
62
+ if param is not None:
63
+ param_cls = type(module._parameters[name])
64
+ kwargs = module._parameters[name].__dict__
65
+ module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs)
66
+
67
+ def register_empty_buffer(module, name, buffer):
68
+ old_register_buffer(module, name, buffer)
69
+ if buffer is not None:
70
+ module._buffers[name] = module._buffers[name].to(device)
71
+ if include_buffers:
72
+ tensor_constructors_to_patch = {torch_function_name: getattr(torch, torch_function_name) for torch_function_name in ['empty', 'zeros', 'ones', 'full']}
73
+ else:
74
+ tensor_constructors_to_patch = {}
75
+
76
+ def patch_tensor_constructor(fn):
77
+
78
+ def wrapper(*args, **kwargs):
79
+ kwargs['device'] = device
80
+ return fn(*args, **kwargs)
81
+ return wrapper
82
+ try:
83
+ nn.Module.register_parameter = register_empty_parameter
84
+ if include_buffers:
85
+ nn.Module.register_buffer = register_empty_buffer
86
+ for torch_function_name in tensor_constructors_to_patch.keys():
87
+ setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name)))
88
+ yield
89
+ finally:
90
+ nn.Module.register_parameter = old_register_parameter
91
+ if include_buffers:
92
+ nn.Module.register_buffer = old_register_buffer
93
+ for (torch_function_name, old_torch_function) in tensor_constructors_to_patch.items():
94
+ setattr(torch, torch_function_name, old_torch_function)
dam/model/language_model/mpt_ignored/modeling_mpt.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A simple, flexible implementation of a GPT model.
2
+
3
+ Inspired by https://github.com/karpathy/minGPT/blob/master/mingpt/model.py
4
+ """
5
+ import math
6
+ import warnings
7
+ from typing import List, Optional, Tuple, Union
8
+ import torch
9
+ import torch.nn as nn
10
+ import torch.nn.functional as F
11
+ from transformers import PreTrainedModel, PreTrainedTokenizer, PreTrainedTokenizerFast
12
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
13
+ from .attention import attn_bias_shape, build_attn_bias
14
+ from .blocks import MPTBlock
15
+ from .custom_embedding import SharedEmbedding
16
+ from .norm import NORM_CLASS_REGISTRY
17
+ from .configuration_mpt import MPTConfig
18
+ from .adapt_tokenizer import AutoTokenizerForMOD, adapt_tokenizer_for_denoising
19
+ from .hf_prefixlm_converter import add_bidirectional_mask_if_missing, convert_hf_causal_lm_to_prefix_lm
20
+ from .meta_init_context import init_empty_weights
21
+ from .param_init_fns import MODEL_INIT_REGISTRY, generic_param_init_fn_
22
+ try:
23
+ from .flash_attn_triton import flash_attn_func
24
+ except:
25
+ pass
26
+ Tokenizer = Union[PreTrainedTokenizer, PreTrainedTokenizerFast]
27
+
28
+ class MPTPreTrainedModel(PreTrainedModel):
29
+ config_class = MPTConfig
30
+ base_model_prefix = 'model'
31
+ _no_split_modules = ['MPTBlock']
32
+
33
+ class MPTModel(MPTPreTrainedModel):
34
+
35
+ def __init__(self, config: MPTConfig):
36
+ config._validate_config()
37
+ super().__init__(config)
38
+ self.attn_impl = config.attn_config['attn_impl']
39
+ self.prefix_lm = config.attn_config['prefix_lm']
40
+ self.attn_uses_sequence_id = config.attn_config['attn_uses_sequence_id']
41
+ self.alibi = config.attn_config['alibi']
42
+ self.alibi_bias_max = config.attn_config['alibi_bias_max']
43
+ if config.init_device == 'mixed':
44
+ if dist.get_local_rank() == 0:
45
+ config.init_device = 'cpu'
46
+ else:
47
+ config.init_device = 'meta'
48
+ if config.norm_type.lower() not in NORM_CLASS_REGISTRY.keys():
49
+ norm_options = ' | '.join(NORM_CLASS_REGISTRY.keys())
50
+ raise NotImplementedError(f'Requested norm type ({config.norm_type}) is not implemented within this repo (Options: {norm_options}).')
51
+ norm_class = NORM_CLASS_REGISTRY[config.norm_type.lower()]
52
+ self.embedding_fraction = config.embedding_fraction
53
+ self.wte = SharedEmbedding(config.vocab_size, config.d_model, device=config.init_device)
54
+ if not self.alibi:
55
+ self.wpe = torch.nn.Embedding(config.max_seq_len, config.d_model, device=config.init_device)
56
+ self.emb_drop = nn.Dropout(config.emb_pdrop)
57
+ self.blocks = nn.ModuleList([MPTBlock(device=config.init_device, **config.to_dict()) for _ in range(config.n_layers)])
58
+ self.norm_f = norm_class(config.d_model, device=config.init_device)
59
+ if config.init_device != 'meta':
60
+ print(f'You are using config.init_device={config.init_device!r}, but you can also use config.init_device="meta" with Composer + FSDP for fast initialization.')
61
+ self.apply(self.param_init_fn)
62
+ self.is_causal = not self.prefix_lm
63
+ self._attn_bias_initialized = False
64
+ self.attn_bias = None
65
+ self.attn_bias_shape = attn_bias_shape(self.attn_impl, config.n_heads, config.max_seq_len, self.alibi, prefix_lm=self.prefix_lm, causal=self.is_causal, use_sequence_id=self.attn_uses_sequence_id)
66
+ if config.no_bias:
67
+ for module in self.modules():
68
+ if hasattr(module, 'bias') and isinstance(module.bias, nn.Parameter):
69
+ if config.verbose:
70
+ warnings.warn(f'Removing bias ({module.bias}) from {module}.')
71
+ module.register_parameter('bias', None)
72
+ if config.verbose and config.verbose > 2:
73
+ print(self)
74
+ if 'verbose' not in self.config.init_config:
75
+ self.config.init_config['verbose'] = self.config.verbose
76
+ if self.config.init_config['verbose'] > 1:
77
+ init_fn_name = self.config.init_config['name']
78
+ warnings.warn(f'Using {init_fn_name} initialization.')
79
+ self.gradient_checkpointing = False
80
+
81
+ def get_input_embeddings(self):
82
+ return self.wte
83
+
84
+ def set_input_embeddings(self, value):
85
+ self.wte = value
86
+
87
+ @torch.no_grad()
88
+ def _attn_bias(self, device, dtype, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None):
89
+ if not self._attn_bias_initialized:
90
+ if self.attn_bias_shape:
91
+ self.attn_bias = torch.zeros(self.attn_bias_shape, device=device, dtype=dtype)
92
+ self.attn_bias = build_attn_bias(self.attn_impl, self.attn_bias, self.config.n_heads, self.config.max_seq_len, causal=self.is_causal, alibi=self.alibi, alibi_bias_max=self.alibi_bias_max)
93
+ self._attn_bias_initialized = True
94
+ if self.attn_impl == 'flash':
95
+ return (self.attn_bias, attention_mask)
96
+ if self.attn_bias is not None:
97
+ self.attn_bias = self.attn_bias.to(dtype=dtype, device=device)
98
+ attn_bias = self.attn_bias
99
+ if self.prefix_lm:
100
+ assert isinstance(attn_bias, torch.Tensor)
101
+ assert isinstance(prefix_mask, torch.Tensor)
102
+ attn_bias = self._apply_prefix_mask(attn_bias, prefix_mask)
103
+ if self.attn_uses_sequence_id and sequence_id is not None:
104
+ assert isinstance(attn_bias, torch.Tensor)
105
+ attn_bias = self._apply_sequence_id(attn_bias, sequence_id)
106
+ if attention_mask is not None:
107
+ s_k = attention_mask.shape[-1]
108
+ if attn_bias is None:
109
+ attn_bias = torch.zeros((1, 1, 1, s_k), device=device, dtype=dtype)
110
+ else:
111
+ _s_k = max(0, attn_bias.size(-1) - s_k)
112
+ attn_bias = attn_bias[:, :, :, _s_k:]
113
+ if prefix_mask is not None and attention_mask.shape != prefix_mask.shape:
114
+ raise ValueError(f'attention_mask shape={attention_mask.shape} ' + f'and prefix_mask shape={prefix_mask.shape} are not equal.')
115
+ min_val = torch.finfo(attn_bias.dtype).min
116
+ attn_bias = attn_bias.masked_fill(~attention_mask.view(-1, 1, 1, s_k), min_val)
117
+ return (attn_bias, None)
118
+
119
+ def _apply_prefix_mask(self, attn_bias: torch.Tensor, prefix_mask: torch.Tensor):
120
+ (s_k, s_q) = attn_bias.shape[-2:]
121
+ if s_k != self.config.max_seq_len or s_q != self.config.max_seq_len:
122
+ raise ValueError('attn_bias does not match the expected shape. ' + f'The last two dimensions should both be {self.config.max_length} ' + f'but are {s_k} and {s_q}.')
123
+ seq_len = prefix_mask.shape[-1]
124
+ if seq_len > self.config.max_seq_len:
125
+ raise ValueError(f'prefix_mask sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
126
+ attn_bias = attn_bias[..., :seq_len, :seq_len]
127
+ causal = torch.tril(torch.ones((seq_len, seq_len), dtype=torch.bool, device=prefix_mask.device)).view(1, 1, seq_len, seq_len)
128
+ prefix = prefix_mask.view(-1, 1, 1, seq_len)
129
+ cannot_attend = ~torch.logical_or(causal, prefix.bool())
130
+ min_val = torch.finfo(attn_bias.dtype).min
131
+ attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
132
+ return attn_bias
133
+
134
+ def _apply_sequence_id(self, attn_bias: torch.Tensor, sequence_id: torch.LongTensor):
135
+ seq_len = sequence_id.shape[-1]
136
+ if seq_len > self.config.max_seq_len:
137
+ raise ValueError(f'sequence_id sequence length cannot exceed max_seq_len={self.config.max_seq_len}')
138
+ attn_bias = attn_bias[..., :seq_len, :seq_len]
139
+ cannot_attend = torch.logical_not(torch.eq(sequence_id.view(-1, seq_len, 1), sequence_id.view(-1, 1, seq_len))).unsqueeze(1)
140
+ min_val = torch.finfo(attn_bias.dtype).min
141
+ attn_bias = attn_bias.masked_fill(cannot_attend, min_val)
142
+ return attn_bias
143
+
144
+ def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.Tensor]=None):
145
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
146
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
147
+ if attention_mask is not None:
148
+ attention_mask = attention_mask.bool()
149
+ if prefix_mask is not None:
150
+ prefix_mask = prefix_mask.bool()
151
+ if not return_dict:
152
+ raise NotImplementedError('return_dict False is not implemented yet for MPT')
153
+ if output_attentions:
154
+ if self.attn_impl != 'torch':
155
+ raise NotImplementedError('output_attentions is not implemented for MPT when using attn_impl `flash` or `triton`.')
156
+ if attention_mask is not None and attention_mask[:, 0].sum() != attention_mask.shape[0] and self.training:
157
+ raise NotImplementedError('MPT does not support training with left padding.')
158
+ if self.prefix_lm and prefix_mask is None:
159
+ raise ValueError('prefix_mask is a required argument when MPT is configured with prefix_lm=True.')
160
+ if self.training:
161
+ if self.attn_uses_sequence_id and sequence_id is None:
162
+ raise ValueError('sequence_id is a required argument when MPT is configured with attn_uses_sequence_id=True ' + 'and the model is in train mode.')
163
+ elif self.attn_uses_sequence_id is False and sequence_id is not None:
164
+ warnings.warn('MPT received non-None input for `sequence_id` but is configured with attn_uses_sequence_id=False. ' + 'This input will be ignored. If you want the model to use `sequence_id`, set attn_uses_sequence_id to True.')
165
+ if input_ids is not None:
166
+ S = input_ids.size(1)
167
+ assert S <= self.config.max_seq_len, f'Cannot forward input with seq_len={S}, this model only supports seq_len<={self.config.max_seq_len}'
168
+ tok_emb = self.wte(input_ids)
169
+ else:
170
+ assert inputs_embeds is not None
171
+ assert self.alibi, 'inputs_embeds is not implemented for MPT unless for alibi.'
172
+ S = inputs_embeds.size(1)
173
+ tok_emb = inputs_embeds
174
+ if self.alibi:
175
+ x = tok_emb
176
+ else:
177
+ past_position = 0
178
+ if past_key_values is not None:
179
+ if len(past_key_values) != self.config.n_layers:
180
+ raise ValueError(f'past_key_values must provide a past_key_value for each attention ' + f'layer in the network (len(past_key_values)={len(past_key_values)!r}; self.config.n_layers={self.config.n_layers!r}).')
181
+ past_position = past_key_values[0][0].size(1)
182
+ if self.attn_impl == 'torch':
183
+ past_position = past_key_values[0][0].size(3)
184
+ if S + past_position > self.config.max_seq_len:
185
+ raise ValueError(f'Cannot forward input with past sequence length {past_position} and current sequence length {S + 1}, this model only supports total sequence length <= {self.config.max_seq_len}.')
186
+ pos = torch.arange(past_position, S + past_position, dtype=torch.long, device=input_ids.device).unsqueeze(0)
187
+ if attention_mask is not None:
188
+ pos = torch.clamp(pos - torch.cumsum((~attention_mask).to(torch.int32), dim=1)[:, past_position:], min=0)
189
+ pos_emb = self.wpe(pos)
190
+ x = tok_emb + pos_emb
191
+ if self.embedding_fraction == 1:
192
+ x = self.emb_drop(x)
193
+ else:
194
+ x_shrunk = x * self.embedding_fraction + x.detach() * (1 - self.embedding_fraction)
195
+ assert isinstance(self.emb_drop, nn.Module)
196
+ x = self.emb_drop(x_shrunk)
197
+ (attn_bias, attention_mask) = self._attn_bias(device=x.device, dtype=torch.float32, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id)
198
+ if use_cache and past_key_values is None:
199
+ past_key_values = [() for _ in range(self.config.n_layers)]
200
+ all_hidden_states = () if output_hidden_states else None
201
+ all_self_attns = () if output_attentions else None
202
+ for (b_idx, block) in enumerate(self.blocks):
203
+ if output_hidden_states:
204
+ assert all_hidden_states is not None
205
+ all_hidden_states = all_hidden_states + (x,)
206
+ past_key_value = past_key_values[b_idx] if past_key_values is not None else None
207
+ if self.gradient_checkpointing and self.training:
208
+ (x, attn_weights, past_key_value) = torch.utils.checkpoint.checkpoint(block, x, past_key_value, attn_bias, attention_mask, self.is_causal)
209
+ else:
210
+ (x, attn_weights, past_key_value) = block(x, past_key_value=past_key_value, attn_bias=attn_bias, attention_mask=attention_mask, is_causal=self.is_causal)
211
+ if past_key_values is not None:
212
+ past_key_values[b_idx] = past_key_value
213
+ if output_attentions:
214
+ assert all_self_attns is not None
215
+ all_self_attns = all_self_attns + (attn_weights,)
216
+ x = self.norm_f(x)
217
+ if output_hidden_states:
218
+ assert all_hidden_states is not None
219
+ all_hidden_states = all_hidden_states + (x,)
220
+ return BaseModelOutputWithPast(last_hidden_state=x, past_key_values=past_key_values, hidden_states=all_hidden_states, attentions=all_self_attns)
221
+
222
+ def param_init_fn(self, module):
223
+ init_fn_name = self.config.init_config['name']
224
+ MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
225
+
226
+ def fsdp_wrap_fn(self, module):
227
+ return isinstance(module, MPTBlock)
228
+
229
+ def activation_checkpointing_fn(self, module):
230
+ return isinstance(module, MPTBlock)
231
+
232
+ class MPTForCausalLM(MPTPreTrainedModel):
233
+
234
+ def __init__(self, config: MPTConfig):
235
+ super().__init__(config)
236
+ if not config.tie_word_embeddings:
237
+ raise ValueError('MPTForCausalLM only supports tied word embeddings')
238
+ print(f'Instantiating an MPTForCausalLM model from {__file__}')
239
+ self.transformer = MPTModel(config)
240
+ for child in self.transformer.children():
241
+ if isinstance(child, torch.nn.ModuleList):
242
+ continue
243
+ if isinstance(child, torch.nn.Module):
244
+ child._fsdp_wrap = True
245
+ self.logit_scale = None
246
+ if config.logit_scale is not None:
247
+ logit_scale = config.logit_scale
248
+ if isinstance(logit_scale, str):
249
+ if logit_scale == 'inv_sqrt_d_model':
250
+ logit_scale = 1 / math.sqrt(config.d_model)
251
+ else:
252
+ raise ValueError(f"logit_scale={logit_scale!r} is not recognized as an option; use numeric value or 'inv_sqrt_d_model'.")
253
+ self.logit_scale = logit_scale
254
+
255
+ def get_input_embeddings(self):
256
+ return self.transformer.wte
257
+
258
+ def set_input_embeddings(self, value):
259
+ self.transformer.wte = value
260
+
261
+ def get_output_embeddings(self):
262
+ return self.transformer.wte
263
+
264
+ def set_output_embeddings(self, new_embeddings):
265
+ self.transformer.wte = new_embeddings
266
+
267
+ def set_decoder(self, decoder):
268
+ self.transformer = decoder
269
+
270
+ def get_decoder(self):
271
+ return self.transformer
272
+
273
+ def forward(self, input_ids: torch.LongTensor, past_key_values: Optional[List[Tuple[torch.FloatTensor]]]=None, attention_mask: Optional[torch.ByteTensor]=None, prefix_mask: Optional[torch.ByteTensor]=None, sequence_id: Optional[torch.LongTensor]=None, labels: Optional[torch.LongTensor]=None, return_dict: Optional[bool]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, use_cache: Optional[bool]=None, inputs_embeds: Optional[torch.FloatTensor]=None):
274
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
275
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
276
+ if inputs_embeds is not None:
277
+ raise NotImplementedError('inputs_embeds has to be None (for hf/peft support).')
278
+ outputs = self.transformer(input_ids=input_ids, past_key_values=past_key_values, attention_mask=attention_mask, prefix_mask=prefix_mask, sequence_id=sequence_id, return_dict=return_dict, output_attentions=output_attentions, output_hidden_states=output_hidden_states, use_cache=use_cache)
279
+ logits = self.transformer.wte(outputs.last_hidden_state.to(self.transformer.wte.weight.device), True)
280
+ if self.logit_scale is not None:
281
+ if self.logit_scale == 0:
282
+ warnings.warn(f'Multiplying logits by self.logit_scale={self.logit_scale!r}. This will produce uniform (uninformative) outputs.')
283
+ logits *= self.logit_scale
284
+ loss = None
285
+ if labels is not None:
286
+ labels = torch.roll(labels, shifts=-1)
287
+ labels[:, -1] = -100
288
+ loss = F.cross_entropy(logits.view(-1, logits.size(-1)), labels.to(logits.device).view(-1))
289
+ return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions)
290
+
291
+ def param_init_fn(self, module):
292
+ init_fn_name = self.config.init_config['name']
293
+ MODEL_INIT_REGISTRY[init_fn_name](module=module, n_layers=self.config.n_layers, d_model=self.config.d_model, **self.config.init_config)
294
+
295
+ def fsdp_wrap_fn(self, module):
296
+ return isinstance(module, MPTBlock)
297
+
298
+ def activation_checkpointing_fn(self, module):
299
+ return isinstance(module, MPTBlock)
300
+
301
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, inputs_embeds=None, **kwargs):
302
+ if inputs_embeds is not None:
303
+ raise NotImplementedError('inputs_embeds is not implemented for MPT yet')
304
+ attention_mask = kwargs['attention_mask'].bool()
305
+ if attention_mask[:, -1].sum() != attention_mask.shape[0]:
306
+ raise NotImplementedError('MPT does not support generation with right padding.')
307
+ if self.transformer.attn_uses_sequence_id and self.training:
308
+ sequence_id = torch.zeros_like(input_ids[:1])
309
+ else:
310
+ sequence_id = None
311
+ if past_key_values is not None:
312
+ input_ids = input_ids[:, -1].unsqueeze(-1)
313
+ if self.transformer.prefix_lm:
314
+ prefix_mask = torch.ones_like(attention_mask)
315
+ if kwargs.get('use_cache') == False:
316
+ raise NotImplementedError('MPT with prefix_lm=True does not support use_cache=False.')
317
+ else:
318
+ prefix_mask = None
319
+ return {'input_ids': input_ids, 'attention_mask': attention_mask, 'prefix_mask': prefix_mask, 'sequence_id': sequence_id, 'past_key_values': past_key_values, 'use_cache': kwargs.get('use_cache', True)}
320
+
321
+ @staticmethod
322
+ def _reorder_cache(past_key_values, beam_idx):
323
+ """Used by HuggingFace generate when using beam search with kv-caching.
324
+
325
+ See https://github.com/huggingface/transformers/blob/3ec7a47664ebe40c40f4b722f6bb1cd30c3821ec/src/transformers/models/gpt2/modeling_gpt2.py#L1122-L1133
326
+ for an example in transformers.
327
+ """
328
+ reordered_past = []
329
+ for layer_past in past_key_values:
330
+ reordered_past += [tuple((past_state.index_select(0, beam_idx) for past_state in layer_past))]
331
+ return reordered_past
dam/model/language_model/mpt_ignored/norm.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ def _cast_if_autocast_enabled(tensor):
4
+ if torch.is_autocast_enabled():
5
+ if tensor.device.type == 'cuda':
6
+ dtype = torch.get_autocast_gpu_dtype()
7
+ elif tensor.device.type == 'cpu':
8
+ dtype = torch.get_autocast_cpu_dtype()
9
+ else:
10
+ raise NotImplementedError()
11
+ return tensor.to(dtype=dtype)
12
+ return tensor
13
+
14
+ class LPLayerNorm(torch.nn.LayerNorm):
15
+
16
+ def __init__(self, normalized_shape, eps=1e-05, elementwise_affine=True, device=None, dtype=None):
17
+ super().__init__(normalized_shape=normalized_shape, eps=eps, elementwise_affine=elementwise_affine, device=device, dtype=dtype)
18
+
19
+ def forward(self, x):
20
+ module_device = x.device
21
+ downcast_x = _cast_if_autocast_enabled(x)
22
+ downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
23
+ downcast_bias = _cast_if_autocast_enabled(self.bias) if self.bias is not None else self.bias
24
+ with torch.autocast(enabled=False, device_type=module_device.type):
25
+ return torch.nn.functional.layer_norm(downcast_x, self.normalized_shape, downcast_weight, downcast_bias, self.eps)
26
+
27
+ def rms_norm(x, weight=None, eps=1e-05):
28
+ output = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps)
29
+ if weight is not None:
30
+ return output * weight
31
+ return output
32
+
33
+ class RMSNorm(torch.nn.Module):
34
+
35
+ def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
36
+ super().__init__()
37
+ self.eps = eps
38
+ if weight:
39
+ self.weight = torch.nn.Parameter(torch.ones(normalized_shape, dtype=dtype, device=device))
40
+ else:
41
+ self.register_parameter('weight', None)
42
+
43
+ def forward(self, x):
44
+ return rms_norm(x.float(), self.weight, self.eps).to(dtype=x.dtype)
45
+
46
+ class LPRMSNorm(RMSNorm):
47
+
48
+ def __init__(self, normalized_shape, eps=1e-05, weight=True, dtype=None, device=None):
49
+ super().__init__(normalized_shape=normalized_shape, eps=eps, weight=weight, dtype=dtype, device=device)
50
+
51
+ def forward(self, x):
52
+ downcast_x = _cast_if_autocast_enabled(x)
53
+ downcast_weight = _cast_if_autocast_enabled(self.weight) if self.weight is not None else self.weight
54
+ with torch.autocast(enabled=False, device_type=x.device.type):
55
+ return rms_norm(downcast_x, downcast_weight, self.eps).to(dtype=x.dtype)
56
+ NORM_CLASS_REGISTRY = {'layernorm': torch.nn.LayerNorm, 'low_precision_layernorm': LPLayerNorm, 'rmsnorm': RMSNorm, 'low_precision_rmsnorm': LPRMSNorm}
dam/model/language_model/mpt_ignored/param_init_fns.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import warnings
3
+ from collections.abc import Sequence
4
+ from functools import partial
5
+ from typing import Optional, Tuple, Union
6
+ import torch
7
+ from torch import nn
8
+ from .norm import NORM_CLASS_REGISTRY
9
+
10
+ def torch_default_param_init_fn_(module: nn.Module, verbose: int=0, **kwargs):
11
+ del kwargs
12
+ if verbose > 1:
13
+ warnings.warn(f"Initializing network using module's reset_parameters attribute")
14
+ if hasattr(module, 'reset_parameters'):
15
+ module.reset_parameters()
16
+
17
+ def fused_init_helper_(module: nn.Module, init_fn_):
18
+ _fused = getattr(module, '_fused', None)
19
+ if _fused is None:
20
+ raise RuntimeError(f'Internal logic error')
21
+ (dim, splits) = _fused
22
+ splits = (0, *splits, module.weight.size(dim))
23
+ for (s, e) in zip(splits[:-1], splits[1:]):
24
+ slice_indices = [slice(None)] * module.weight.ndim
25
+ slice_indices[dim] = slice(s, e)
26
+ init_fn_(module.weight[slice_indices])
27
+
28
+ def generic_param_init_fn_(module: nn.Module, init_fn_, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
29
+ del kwargs
30
+ if verbose > 1:
31
+ warnings.warn(f'If model has bias parameters they are initialized to 0.')
32
+ init_div_is_residual = init_div_is_residual
33
+ if init_div_is_residual is False:
34
+ div_is_residual = 1.0
35
+ elif init_div_is_residual is True:
36
+ div_is_residual = math.sqrt(2 * n_layers)
37
+ elif isinstance(init_div_is_residual, float) or isinstance(init_div_is_residual, int):
38
+ div_is_residual = init_div_is_residual
39
+ elif isinstance(init_div_is_residual, str) and init_div_is_residual.isnumeric():
40
+ div_is_residual = float(init_div_is_residual)
41
+ else:
42
+ div_is_residual = 1.0
43
+ raise ValueError(f'Expected init_div_is_residual to be boolean or numeric, got {init_div_is_residual}')
44
+ if init_div_is_residual is not False:
45
+ if verbose > 1:
46
+ warnings.warn(f'Initializing _is_residual layers then dividing them by {div_is_residual:.3f}. ' + f'Set `init_div_is_residual: false` in init config to disable this.')
47
+ if isinstance(module, nn.Linear):
48
+ if hasattr(module, '_fused'):
49
+ fused_init_helper_(module, init_fn_)
50
+ else:
51
+ init_fn_(module.weight)
52
+ if module.bias is not None:
53
+ torch.nn.init.zeros_(module.bias)
54
+ if init_div_is_residual is not False and getattr(module, '_is_residual', False):
55
+ with torch.no_grad():
56
+ module.weight.div_(div_is_residual)
57
+ elif isinstance(module, nn.Embedding):
58
+ if emb_init_std is not None:
59
+ std = emb_init_std
60
+ if std == 0:
61
+ warnings.warn(f'Embedding layer initialized to 0.')
62
+ emb_init_fn_ = partial(torch.nn.init.normal_, mean=0.0, std=std)
63
+ if verbose > 1:
64
+ warnings.warn(f'Embedding layer initialized using normal distribution with mean=0 and std={std!r}.')
65
+ elif emb_init_uniform_lim is not None:
66
+ lim = emb_init_uniform_lim
67
+ if isinstance(lim, Sequence):
68
+ if len(lim) > 2:
69
+ raise ValueError(f'Uniform init requires a min and a max limit. User input: {lim}.')
70
+ if lim[0] == lim[1]:
71
+ warnings.warn(f'Embedding layer initialized to {lim[0]}.')
72
+ else:
73
+ if lim == 0:
74
+ warnings.warn(f'Embedding layer initialized to 0.')
75
+ lim = [-lim, lim]
76
+ (a, b) = lim
77
+ emb_init_fn_ = partial(torch.nn.init.uniform_, a=a, b=b)
78
+ if verbose > 1:
79
+ warnings.warn(f'Embedding layer initialized using uniform distribution in range {lim}.')
80
+ else:
81
+ emb_init_fn_ = init_fn_
82
+ emb_init_fn_(module.weight)
83
+ elif isinstance(module, tuple(set(NORM_CLASS_REGISTRY.values()))):
84
+ if verbose > 1:
85
+ warnings.warn(f'Norm weights are set to 1. If norm layer has a bias it is initialized to 0.')
86
+ if hasattr(module, 'weight') and module.weight is not None:
87
+ torch.nn.init.ones_(module.weight)
88
+ if hasattr(module, 'bias') and module.bias is not None:
89
+ torch.nn.init.zeros_(module.bias)
90
+ elif isinstance(module, nn.MultiheadAttention):
91
+ if module._qkv_same_embed_dim:
92
+ assert module.in_proj_weight is not None
93
+ assert module.q_proj_weight is None and module.k_proj_weight is None and (module.v_proj_weight is None)
94
+ assert d_model is not None
95
+ _d = d_model
96
+ splits = (0, _d, 2 * _d, 3 * _d)
97
+ for (s, e) in zip(splits[:-1], splits[1:]):
98
+ init_fn_(module.in_proj_weight[s:e])
99
+ else:
100
+ assert module.q_proj_weight is not None and module.k_proj_weight is not None and (module.v_proj_weight is not None)
101
+ assert module.in_proj_weight is None
102
+ init_fn_(module.q_proj_weight)
103
+ init_fn_(module.k_proj_weight)
104
+ init_fn_(module.v_proj_weight)
105
+ if module.in_proj_bias is not None:
106
+ torch.nn.init.zeros_(module.in_proj_bias)
107
+ if module.bias_k is not None:
108
+ torch.nn.init.zeros_(module.bias_k)
109
+ if module.bias_v is not None:
110
+ torch.nn.init.zeros_(module.bias_v)
111
+ init_fn_(module.out_proj.weight)
112
+ if init_div_is_residual is not False and getattr(module.out_proj, '_is_residual', False):
113
+ with torch.no_grad():
114
+ module.out_proj.weight.div_(div_is_residual)
115
+ if module.out_proj.bias is not None:
116
+ torch.nn.init.zeros_(module.out_proj.bias)
117
+ else:
118
+ for _ in module.parameters(recurse=False):
119
+ raise NotImplementedError(f'{module.__class__.__name__} parameters are not initialized by param_init_fn.')
120
+
121
+ def _normal_init_(std, mean=0.0):
122
+ return partial(torch.nn.init.normal_, mean=mean, std=std)
123
+
124
+ def _normal_param_init_fn_(module: nn.Module, std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
125
+ del kwargs
126
+ init_fn_ = _normal_init_(std=std)
127
+ if verbose > 1:
128
+ warnings.warn(f'Using torch.nn.init.normal_ init fn mean=0.0, std={std}')
129
+ generic_param_init_fn_(module=module, init_fn_=init_fn_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
130
+
131
+ def baseline_param_init_fn_(module: nn.Module, init_std: float, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
132
+ del kwargs
133
+ if init_std is None:
134
+ raise ValueError("You must set model.init_config['init_std'] to a float value to use the default initialization scheme.")
135
+ _normal_param_init_fn_(module=module, std=init_std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
136
+
137
+ def small_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
138
+ del kwargs
139
+ std = math.sqrt(2 / (5 * d_model))
140
+ _normal_param_init_fn_(module=module, std=std, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
141
+
142
+ def neox_param_init_fn_(module: nn.Module, n_layers: int, d_model: int, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, verbose: int=0, **kwargs):
143
+ """From section 2.3.1 of GPT-NeoX-20B:
144
+
145
+ An Open-Source AutoregressiveLanguage Model — Black et. al. (2022)
146
+ see https://github.com/EleutherAI/gpt-neox/blob/9610391ab319403cef079b438edd016a2443af54/megatron/model/init_functions.py#L151
147
+ and https://github.com/EleutherAI/gpt-neox/blob/main/megatron/model/transformer.py
148
+ """
149
+ del kwargs
150
+ residual_div = n_layers / math.sqrt(10)
151
+ if verbose > 1:
152
+ warnings.warn(f'setting init_div_is_residual to {residual_div}')
153
+ small_param_init_fn_(module=module, d_model=d_model, n_layers=n_layers, init_div_is_residual=residual_div, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
154
+
155
+ def kaiming_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
156
+ del kwargs
157
+ if verbose > 1:
158
+ warnings.warn(f'Using nn.init.kaiming_uniform_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
159
+ kaiming_uniform_ = partial(nn.init.kaiming_uniform_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
160
+ generic_param_init_fn_(module=module, init_fn_=kaiming_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
161
+
162
+ def kaiming_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, fan_mode: str='fan_in', init_nonlinearity: str='leaky_relu', verbose: int=0, **kwargs):
163
+ del kwargs
164
+ if verbose > 1:
165
+ warnings.warn(f'Using nn.init.kaiming_normal_ init fn with parameters: ' + f'a={init_gain}, mode={fan_mode}, nonlinearity={init_nonlinearity}')
166
+ kaiming_normal_ = partial(torch.nn.init.kaiming_normal_, a=init_gain, mode=fan_mode, nonlinearity=init_nonlinearity)
167
+ generic_param_init_fn_(module=module, init_fn_=kaiming_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
168
+
169
+ def xavier_uniform_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
170
+ del kwargs
171
+ xavier_uniform_ = partial(torch.nn.init.xavier_uniform_, gain=init_gain)
172
+ if verbose > 1:
173
+ warnings.warn(f'Using torch.nn.init.xavier_uniform_ init fn with parameters: ' + f'gain={init_gain}')
174
+ generic_param_init_fn_(module=module, init_fn_=xavier_uniform_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
175
+
176
+ def xavier_normal_param_init_fn_(module: nn.Module, n_layers: int, d_model: Optional[int]=None, init_div_is_residual: Union[int, float, str, bool]=True, emb_init_std: Optional[float]=None, emb_init_uniform_lim: Optional[Union[Tuple[float, float], float]]=None, init_gain: float=0, verbose: int=0, **kwargs):
177
+ xavier_normal_ = partial(torch.nn.init.xavier_normal_, gain=init_gain)
178
+ if verbose > 1:
179
+ warnings.warn(f'Using torch.nn.init.xavier_normal_ init fn with parameters: ' + f'gain={init_gain}')
180
+ generic_param_init_fn_(module=module, init_fn_=xavier_normal_, d_model=d_model, n_layers=n_layers, init_div_is_residual=init_div_is_residual, emb_init_std=emb_init_std, emb_init_uniform_lim=emb_init_uniform_lim, verbose=verbose)
181
+ MODEL_INIT_REGISTRY = {'default_': torch_default_param_init_fn_, 'baseline_': baseline_param_init_fn_, 'kaiming_uniform_': kaiming_uniform_param_init_fn_, 'kaiming_normal_': kaiming_normal_param_init_fn_, 'neox_init_': neox_param_init_fn_, 'small_init_': small_param_init_fn_, 'xavier_uniform_': xavier_uniform_param_init_fn_, 'xavier_normal_': xavier_normal_param_init_fn_}
dam/model/llava_arch.py ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 Haotian Liu
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os, sys, os.path as osp
16
+ import warnings
17
+ from abc import ABC, abstractmethod
18
+
19
+ import torch, logging
20
+
21
+ from transformers import (
22
+ AutoTokenizer,
23
+ AutoModel,
24
+ AutoModelForCausalLM,
25
+ AutoConfig,
26
+ BitsAndBytesConfig,
27
+ PretrainedConfig,
28
+ PreTrainedModel,
29
+ )
30
+
31
+ from .constants import (
32
+ DEFAULT_IM_END_TOKEN,
33
+ DEFAULT_IM_START_TOKEN,
34
+ DEFAULT_IMAGE_PATCH_TOKEN,
35
+ IGNORE_INDEX,
36
+ IMAGE_TOKEN_INDEX,
37
+ MASK_TOKEN_INDEX,
38
+ )
39
+
40
+ from collections import OrderedDict
41
+ from .utils import get_model_config
42
+ from .language_model.builder import build_llm_and_tokenizer
43
+ from .multimodal_encoder.builder import build_vision_tower, build_context_provider
44
+ from .multimodal_projector.builder import build_mm_projector
45
+ from .configuration_llava import LlavaConfig
46
+
47
+ from transformers.modeling_utils import ContextManagers, no_init_weights
48
+
49
+ ## TODO decide whether should we use metaclass
50
+ class LlavaMetaModel(ABC):
51
+ def init_vlm(self, config: PreTrainedModel = None, *args, **kwargs):
52
+ # TODO(ligeng): figure out how from_config and from_pretrained works in HF implementation.
53
+ if hasattr(self, "llm") or hasattr(self, "vision_tower") or hasattr(self, "mm_projector"):
54
+ # already initialized, skipped
55
+ return
56
+
57
+ model_dtype = getattr(config, "model_dtype", "torch.float16")
58
+ if not hasattr(config, "model_dtype"):
59
+ warnings.warn("model_dtype not found in config, defaulting to torch.float16.")
60
+ config.model_dtype = model_dtype
61
+
62
+ # print("init_vlm(): config", config); input("DEBUG init_vlm")
63
+ cfgs = get_model_config(config)
64
+ # Only the first three are required. Others are optional.
65
+ llm_cfg, vision_tower_cfg, mm_projector_cfg, mask_encoder_cfg, context_provider_cfg = cfgs
66
+ if llm_cfg is None or vision_tower_cfg is None or mm_projector_cfg is None:
67
+ raise ValueError("`llm_cfg` `mm_projector_cfg` `vision_tower_cfg` not found in the config.")
68
+ # print("init_vlm():", cfgs); input("DEBUG init_vlm")
69
+ # print(llm_cfg, vision_tower_cfg, mm_projector_cfg); input("DEBUG init_vlm")
70
+ self.llm, self.tokenizer = build_llm_and_tokenizer(llm_cfg, config, *args, **kwargs)
71
+ self.vision_tower = build_vision_tower(vision_tower_cfg, config)
72
+ self.mm_projector = build_mm_projector(mm_projector_cfg, config)
73
+ self.context_provider = build_context_provider(context_provider_cfg, config) if context_provider_cfg is not None else None
74
+
75
+ self.post_config()
76
+ self.is_loaded = True
77
+
78
+ assert (
79
+ self.llm is not None or self.vision_tower is not None or self.mm_projector is not None
80
+ ), "At least one of the components must be instantiated."
81
+
82
+ @classmethod
83
+ def load_from_config(cls, model_path_or_config, *args, **kwargs):
84
+ pass
85
+
86
+ ## FIXME we will use this function to load model in the future
87
+ @classmethod
88
+ def load_pretrained(cls, model_path_or_config, *args, **kwargs):
89
+ kwargs.pop("config", None)
90
+
91
+ if isinstance(model_path_or_config, str):
92
+ config = AutoConfig.from_pretrained(model_path_or_config)
93
+ elif isinstance(model_path_or_config, LlavaConfig):
94
+ config = model_path_or_config
95
+ else:
96
+ raise NotImplementedError(f"wrong type, {type(model_path_or_config)} \
97
+ {isinstance(model_path_or_config, LlavaConfig)}")
98
+
99
+ model_dtype = getattr(config, "model_dtype", "torch.float16")
100
+ if not hasattr(config, "model_dtype"):
101
+ warnings.warn("model_dtype not found in config, defaulting to torch.float16.")
102
+ config.model_dtype = model_dtype
103
+
104
+ cfgs = get_model_config(config)
105
+ # Only the first three are required. Others are optional.
106
+ llm_cfg, vision_tower_cfg, mm_projector_cfg, mask_encoder_cfg, context_provider_cfg = cfgs
107
+ if llm_cfg is None or vision_tower_cfg is None or mm_projector_cfg is None:
108
+ raise ValueError("`llm_cfg` `mm_projector_cfg` `vision_tower_cfg` not found in the config.")
109
+
110
+ # print(llm_cfg, vision_tower_cfg, mm_projector_cfg); input("DEBUG load_pretrained")
111
+ with ContextManagers([no_init_weights(_enable=True),]):
112
+ vlm = cls(config, *args, **kwargs)
113
+ # print(llm_cfg, vision_tower_cfg, mm_projector_cfg); input("DEBUG load_pretrained finish")
114
+
115
+ if hasattr(vlm, "llm") or hasattr(vlm, "vision_tower") or hasattr(vlm, "mm_projector"):
116
+ if vlm.is_loaded:
117
+ return vlm
118
+
119
+ vlm.llm, vlm.tokenizer = build_llm_and_tokenizer(llm_cfg, config, *args, **kwargs)
120
+ vlm.vision_tower = build_vision_tower(vision_tower_cfg, config)
121
+ vlm.mm_projector = build_mm_projector(mm_projector_cfg, config)
122
+ if mask_encoder_cfg is not None:
123
+ raise NotImplementedError("Mask encoder is not supported.")
124
+ vlm.context_provider = build_context_provider(context_provider_cfg, config) if context_provider_cfg is not None else None
125
+
126
+ self.post_config()
127
+ self.is_loaded = True
128
+
129
+ # FIXME(ligeng, yunhao): llm should never be none here.
130
+ assert (
131
+ vlm.llm is not None or vlm.vision_tower is not None or vlm.mm_projector is not None
132
+ ), "At least one of the components must be instantiated."
133
+ return vlm
134
+
135
+ ## FIXME we will use this function to save the model in the future
136
+ def save_pretrained(self, output_dir, state_dict=None):
137
+ if state_dict is None:
138
+ # other wise fetch from deepspeed
139
+ # state_dict = accelerator.get_state_dict(is_deepspeed_enabled)
140
+ state_dict = self.state_dict()
141
+
142
+ if getattr(self, "tokenizer", None):
143
+ self.tokenizer.save_pretrained(osp.join(output_dir, "llm"))
144
+
145
+ if self.get_llm():
146
+ print(f"saving llm to {osp.join(output_dir, 'llm')}")
147
+ self.llm.config._name_or_path = osp.join(output_dir, "llm")
148
+ llm_state_dict = OrderedDict({k.split("llm.")[-1]: v for k, v in state_dict.items() if "llm" in k})
149
+ self.llm.save_pretrained(os.path.join(output_dir, "llm"), state_dict=llm_state_dict)
150
+ self.config.llm_cfg = self.llm.config
151
+
152
+ if self.get_vision_tower() and "radio" not in self.get_vision_tower().__class__.__name__.lower():
153
+ print(f"saving vision_tower to {osp.join(output_dir, 'vision_tower')}")
154
+ self.vision_tower.config._name_or_path = osp.join(output_dir, "vision_tower")
155
+ vision_tower_state_dict = OrderedDict(
156
+ {k.split("vision_tower.vision_tower.")[-1]: v for k, v in state_dict.items() if "vision_tower" in k}
157
+ )
158
+ self.vision_tower.vision_tower.save_pretrained(
159
+ os.path.join(output_dir, "vision_tower"),
160
+ state_dict=vision_tower_state_dict,
161
+ )
162
+ self.vision_tower.image_processor.save_pretrained(os.path.join(output_dir, "vision_tower"))
163
+ self.config.vision_tower_cfg = self.vision_tower.config
164
+ if hasattr(self.config.vision_tower_cfg, 'auto_map'):
165
+ delattr(self.config.vision_tower_cfg, 'auto_map')
166
+
167
+ if self.get_mm_projector():
168
+ print(f"saving mm_projector to {osp.join(output_dir, 'mm_projector')}")
169
+ self.mm_projector.config._name_or_path = osp.join(output_dir, "mm_projector")
170
+ mm_projector_state_dict = OrderedDict(
171
+ {k.split("mm_projector.")[-1]: v for k, v in state_dict.items() if "mm_projector" in k}
172
+ )
173
+ self.mm_projector.save_pretrained(
174
+ os.path.join(output_dir, "mm_projector"),
175
+ state_dict=mm_projector_state_dict,
176
+ )
177
+ self.config.mm_projector_cfg = self.mm_projector.config
178
+
179
+ if self.get_context_provider():
180
+ print(f"saving context_provider to {osp.join(output_dir, 'context_provider')}")
181
+ self.context_provider.config._name_or_path = osp.join(output_dir, "context_provider")
182
+ context_provider_state_dict = OrderedDict(
183
+ {k.split("context_provider.")[-1]: v for k, v in state_dict.items() if "context_provider" in k}
184
+ )
185
+ self.context_provider.save_pretrained(
186
+ os.path.join(output_dir, "context_provider"),
187
+ state_dict=context_provider_state_dict,
188
+ )
189
+ self.config.context_provider_cfg = self.context_provider.config
190
+
191
+ ## update and save top-level config
192
+ self.config._name_or_path = output_dir
193
+ self.config.architectures = [self.__class__.__name__]
194
+ self.config.save_pretrained(output_dir)
195
+
196
+
197
+ def get_llm(self):
198
+ llm = getattr(self, "llm", None)
199
+ if type(llm) is list:
200
+ llm = llm[0]
201
+ return llm
202
+
203
+ def get_lm_head(self):
204
+ lm_head = getattr(self.get_llm(), "lm_head", None)
205
+ return lm_head
206
+
207
+ def get_vision_tower(self):
208
+ vision_tower = getattr(self, "vision_tower", None)
209
+ if type(vision_tower) is list:
210
+ vision_tower = vision_tower[0]
211
+ return vision_tower
212
+
213
+ def get_mm_projector(self):
214
+ mm_projector = getattr(self, "mm_projector", None)
215
+ if type(mm_projector) is list:
216
+ mm_projector = mm_projector[0]
217
+ return mm_projector
218
+
219
+ def get_context_provider(self):
220
+ context_provider = getattr(self, "context_provider", None)
221
+ return context_provider
222
+
223
+ def post_config(self):
224
+ self.training = self.get_llm().training
225
+ ## configuration
226
+ if getattr(self.config, "llm_cfg", None) is None:
227
+ self.config.llm_cfg = self.llm.config
228
+ if getattr(self.config, "vision_tower_cfg", None) is None:
229
+ self.config.vision_tower_cfg = self.vision_tower.config
230
+ if getattr(self.config, "mm_projector_cfg", None) is None:
231
+ self.config.mm_projector_cfg = self.mm_projector.config
232
+ if getattr(self.config, "context_provider_cfg", None) is None and self.context_provider is not None:
233
+ self.config.context_provider_cfg = self.context_provider.config
234
+
235
+ def freezed_module_patch(self):
236
+ '''
237
+ Huggingface will call model.train() at each training_step. To ensure the expected behaviors for modules like dropout, batchnorm, etc., we need to call model.eval() for the freezed modules.
238
+ '''
239
+ if self.training:
240
+ if self.get_llm() and not getattr(self.config, "tune_language_model", False):
241
+ logging.warning("Caution: Your LLM is currently in training mode, ensuring accurate gradient computation. Please be vigilant, particularly regarding BatchNorm and Dropout operations.")
242
+ if self.get_vision_tower() and not getattr(self.config, "tune_vision_tower", False):
243
+ self.get_vision_tower().eval()
244
+ if self.get_mm_projector() and not getattr(self.config, "tune_mm_projector", False):
245
+ self.get_mm_projector().eval()
246
+ if self.get_context_provider() and not getattr(self.config, "tune_context_provider", False):
247
+ self.get_context_provider().eval()
248
+
249
+ def encode_images(self, images):
250
+ image_features = self.get_vision_tower()(images)
251
+ image_features = self.get_mm_projector()(image_features)
252
+ return image_features
253
+
254
+ def encode_images_with_context(self, images):
255
+ context_provider = self.get_context_provider()
256
+ # If the channels completely match, they are cimage (image with context).
257
+ cimage_mask = torch.any((images[:, :4, ...] != images[:, 4:, ...]).flatten(start_dim=1), dim=1)
258
+
259
+ if context_provider.treat_image_as_cimage:
260
+ # If the context provider treats the image as cimage, then all images are cimage.
261
+ cimage_mask[:] = True
262
+
263
+ if context_provider.context_image_as_queries:
264
+ # Swap the crop image and full image since the model uses the full image as queries by default
265
+ images = torch.cat((images[:, 4:, ...], images[:, :4, ...]), dim=1)
266
+
267
+ # Process the first 4 channels for all images: for image it's the image, for cimage it's the full image
268
+ vision_tower = self.get_vision_tower()
269
+ # Encode context images (full images)
270
+ image_features = vision_tower(images[:, :4, ...]).to(self.device)
271
+ # Each cimage has 8 channels (full and crop concatenated)
272
+ cimage_concatenated = images[cimage_mask]
273
+ cimage_full_features = image_features[cimage_mask]
274
+ if context_provider.context_provider_type == "cross_attn_end_to_all":
275
+ cimage_features = self.context_provider(
276
+ cimage_full_features=cimage_full_features,
277
+ cimage_concatenated=cimage_concatenated,
278
+ vision_tower=vision_tower
279
+ ).to(self.device)
280
+ elif context_provider.context_provider_type == "concat":
281
+ # Full features of cimages are computed but not used.
282
+ cimage_features = self.context_provider(
283
+ cimage_concatenated=cimage_concatenated,
284
+ vision_tower=vision_tower
285
+ ).to(self.device)
286
+ else:
287
+ raise NotImplementedError(f"Context provider type {context_provider.context_provider_type} not implemented.")
288
+ # Put cimage_features into image_features
289
+ image_features[cimage_mask] = cimage_features
290
+
291
+ # Project to the llm space
292
+ image_features = self.get_mm_projector()(image_features)
293
+
294
+ return image_features
295
+
296
+ ## @yunhao: is there a better way to handle function call and attributes for llm?
297
+ ## support beam search
298
+ def _temporary_reorder_cache(self, past_key_values, sorted_idx):
299
+ return self.get_llm()._temporary_reorder_cache(past_key_values, sorted_idx)
300
+
301
+ def get_input_embeddings(self):
302
+ return self.get_llm().get_input_embeddings()
303
+
304
+ def get_output_embeddings(self):
305
+ return self.get_llm().get_output_embeddings()
306
+
307
+ def resize_token_embeddings(self, embed_size):
308
+ self.get_llm().resize_token_embeddings(embed_size)
309
+
310
+
311
+
312
+ class LlavaMetaForCausalLM(ABC):
313
+ """This class is originally implemented by the LLaVA team and
314
+ modified by Haotian Tang and Jason Lu based on Ji Lin's implementation
315
+ to support multiple images and input packing."""
316
+
317
+ ## TODO move the forward function here if there is no need to override it
318
+ def prepare_inputs_labels_for_multimodal(
319
+ self, input_ids, position_ids, attention_mask, past_key_values, labels, images
320
+ ):
321
+ vision_tower = self.get_vision_tower()
322
+ if vision_tower is None or images is None or input_ids.shape[1] == 1:
323
+ if (
324
+ past_key_values is not None
325
+ and vision_tower is not None
326
+ and images is not None
327
+ and input_ids.shape[1] == 1
328
+ ):
329
+ target_shape = past_key_values[-1][-1].shape[-2] + 1
330
+ attention_mask = torch.cat(
331
+ (
332
+ attention_mask,
333
+ torch.ones(
334
+ (
335
+ attention_mask.shape[0],
336
+ target_shape - attention_mask.shape[1],
337
+ ),
338
+ dtype=attention_mask.dtype,
339
+ device=attention_mask.device,
340
+ ),
341
+ ),
342
+ dim=1,
343
+ )
344
+ position_ids = torch.sum(attention_mask, dim=1).unsqueeze(-1) - 1
345
+ return (
346
+ input_ids,
347
+ position_ids,
348
+ attention_mask,
349
+ past_key_values,
350
+ None,
351
+ labels,
352
+ )
353
+ # handle different image dtypes for packing
354
+ if type(images) is list:
355
+ images = torch.cat(images, dim=0)
356
+ elif images.ndim == 5: # batch_size x seq_len x image_channels
357
+ images = images.flatten(0, 1)
358
+ if getattr(self, "context_provider", None):
359
+ image_features = self.encode_images_with_context(images)
360
+ else:
361
+ # Since we slice it with index below, turning it into a list splits things by the first index which does not result in data copy or degrade performance.
362
+ # Example dimension: [1, 196, 2560]
363
+ assert images.shape[1] <= 4, f"images have more than 4 channels, but context provider is not included"
364
+ image_features = self.encode_images(images).to(self.device)
365
+ # Note (kentang-mit@): image start / end is not implemented here to support pretraining.
366
+ if getattr(self.config, "turn_mm_projector", False) and getattr(self.config, "mm_use_im_start_end", False):
367
+ raise NotImplementedError
368
+
369
+ # Let's just add dummy tensors if they do not exist,
370
+ # it is a headache to deal with None all the time.
371
+ # But it is not ideal, and if you have a better idea,
372
+ # please open an issue / submit a PR, thanks.
373
+ _labels = labels
374
+ _position_ids = position_ids
375
+ _attention_mask = attention_mask
376
+ if attention_mask is None:
377
+ attention_mask = torch.ones_like(input_ids, dtype=torch.bool)
378
+ else:
379
+ attention_mask = attention_mask.bool()
380
+ if position_ids is None:
381
+ position_ids = torch.arange(0, input_ids.shape[1], dtype=torch.long, device=input_ids.device)
382
+ if labels is None:
383
+ labels = torch.full_like(input_ids, IGNORE_INDEX)
384
+
385
+ # remove the padding using attention_mask
386
+ input_ids_copy = input_ids.clone()
387
+ # kentang-mit@: Otherwise tokenizer out of bounds. Embeddings of image tokens will not be used.
388
+ input_ids_copy[input_ids_copy == IMAGE_TOKEN_INDEX] = 0
389
+ input_embeds = self.llm.model.embed_tokens(input_ids_copy)
390
+
391
+ input_ids = [
392
+ cur_input_ids[cur_attention_mask] for cur_input_ids, cur_attention_mask in zip(input_ids, attention_mask)
393
+ ]
394
+ input_embeds_1 = [
395
+ cur_input_embeds[cur_attention_mask]
396
+ for cur_input_embeds, cur_attention_mask in zip(input_embeds, attention_mask)
397
+ ]
398
+ labels = [cur_labels[cur_attention_mask] for cur_labels, cur_attention_mask in zip(labels, attention_mask)]
399
+
400
+ new_input_embeds = []
401
+ new_labels = []
402
+ cur_image_idx = 0
403
+
404
+ # print("BEFORE BATCH LOOP:", len(input_ids), input_ids[0].shape, input_ids[0].device, [(x == IMAGE_TOKEN_INDEX).sum() for x in input_ids])
405
+
406
+ # kentang-mit@: If some part of the model is executed in the loop, the the loop length needs to be a constant.
407
+ for batch_idx, cur_input_ids in enumerate(input_ids):
408
+ cur_input_ids = input_ids[batch_idx]
409
+ num_images = (cur_input_ids == IMAGE_TOKEN_INDEX).sum()
410
+ if num_images == 0:
411
+ cur_image_features = image_features[0]
412
+ # cur_input_embeds_1 = self.get_llm().embed_tokens(cur_input_ids)
413
+ cur_input_embeds_1 = input_embeds_1[batch_idx]
414
+ cur_input_embeds = torch.cat([cur_input_embeds_1, cur_image_features[0:0]], dim=0)
415
+ new_input_embeds.append(cur_input_embeds)
416
+ new_labels.append(labels[batch_idx])
417
+ # kenang-mit@: we do not have placeholdr image for text-only data now.
418
+ # cur_image_idx += 1
419
+ continue
420
+
421
+ cur_input_embeds = input_embeds_1[batch_idx]
422
+ image_token_indices = (
423
+ [-1] + torch.where(cur_input_ids == IMAGE_TOKEN_INDEX)[0].tolist() + [cur_input_ids.shape[0]]
424
+ )
425
+ cur_input_ids_noim = []
426
+ cur_labels = labels[batch_idx]
427
+ cur_labels_noim = []
428
+ cur_input_embeds_no_im = []
429
+ for i in range(len(image_token_indices) - 1):
430
+ cur_input_ids_noim.append(cur_input_ids[image_token_indices[i] + 1 : image_token_indices[i + 1]])
431
+ cur_labels_noim.append(cur_labels[image_token_indices[i] + 1 : image_token_indices[i + 1]])
432
+ cur_input_embeds_no_im.append(cur_input_embeds[image_token_indices[i] + 1 : image_token_indices[i + 1]])
433
+ split_sizes = [x.shape[0] for x in cur_labels_noim]
434
+ # cur_input_embeds = self.get_llm().embed_tokens(torch.cat(cur_input_ids_noim))
435
+ # cur_input_embeds_no_im = torch.split(cur_input_embeds, split_sizes, dim=0)
436
+ cur_new_input_embeds = []
437
+ cur_new_labels = []
438
+ for i in range(num_images + 1):
439
+ cur_new_input_embeds.append(cur_input_embeds_no_im[i])
440
+ cur_new_labels.append(cur_labels_noim[i])
441
+ if i < num_images:
442
+ cur_image_features = image_features[cur_image_idx]
443
+ cur_image_idx += 1
444
+ cur_new_input_embeds.append(cur_image_features)
445
+ cur_new_labels.append(
446
+ torch.full(
447
+ (cur_image_features.shape[0],),
448
+ IGNORE_INDEX,
449
+ device=cur_labels.device,
450
+ dtype=cur_labels.dtype,
451
+ )
452
+ )
453
+
454
+ cur_new_input_embeds = torch.cat(cur_new_input_embeds)
455
+ cur_new_labels = torch.cat(cur_new_labels)
456
+
457
+ new_input_embeds.append(cur_new_input_embeds)
458
+ new_labels.append(cur_new_labels)
459
+
460
+ # Truncate sequences to max length as image embeddings can make the sequence longer
461
+ tokenizer_model_max_length = getattr(self.llm.config, "tokenizer_model_max_length", None)
462
+ if tokenizer_model_max_length is not None:
463
+ if any(len(x) > tokenizer_model_max_length for x in new_input_embeds):
464
+ warnings.warn("Inputs truncated!")
465
+ new_input_embeds = [x[:tokenizer_model_max_length] for x in new_input_embeds]
466
+ new_labels = [x[:tokenizer_model_max_length] for x in new_labels]
467
+ # Combine them
468
+ max_len = max(x.shape[0] for x in new_input_embeds)
469
+ batch_size = len(new_input_embeds)
470
+
471
+ new_input_embeds_padded = []
472
+ new_labels_padded = torch.full(
473
+ (batch_size, max_len),
474
+ IGNORE_INDEX,
475
+ dtype=new_labels[0].dtype,
476
+ device=new_labels[0].device,
477
+ )
478
+ attention_mask = torch.zeros(
479
+ (batch_size, max_len),
480
+ dtype=attention_mask.dtype,
481
+ device=attention_mask.device,
482
+ )
483
+ position_ids = torch.zeros((batch_size, max_len), dtype=position_ids.dtype, device=position_ids.device)
484
+
485
+ for i, (cur_new_embed, cur_new_labels) in enumerate(zip(new_input_embeds, new_labels)):
486
+ cur_len = cur_new_embed.shape[0]
487
+ if getattr(self.llm.config, "tokenizer_padding_side", "right") == "left":
488
+ new_input_embeds_padded.append(
489
+ torch.cat(
490
+ (
491
+ torch.zeros(
492
+ (max_len - cur_len, cur_new_embed.shape[1]),
493
+ dtype=cur_new_embed.dtype,
494
+ device=cur_new_embed.device,
495
+ ),
496
+ cur_new_embed,
497
+ ),
498
+ dim=0,
499
+ )
500
+ )
501
+ if cur_len > 0:
502
+ new_labels_padded[i, -cur_len:] = cur_new_labels
503
+ attention_mask[i, -cur_len:] = True
504
+ position_ids[i, -cur_len:] = torch.arange(
505
+ 0, cur_len, dtype=position_ids.dtype, device=position_ids.device
506
+ )
507
+ else:
508
+ new_input_embeds_padded.append(
509
+ torch.cat(
510
+ (
511
+ cur_new_embed,
512
+ torch.zeros(
513
+ (max_len - cur_len, cur_new_embed.shape[1]),
514
+ dtype=cur_new_embed.dtype,
515
+ device=cur_new_embed.device,
516
+ ),
517
+ ),
518
+ dim=0,
519
+ )
520
+ )
521
+ if cur_len > 0:
522
+ new_labels_padded[i, :cur_len] = cur_new_labels
523
+ attention_mask[i, :cur_len] = True
524
+ position_ids[i, :cur_len] = torch.arange(
525
+ 0, cur_len, dtype=position_ids.dtype, device=position_ids.device
526
+ )
527
+
528
+ new_input_embeds = torch.stack(new_input_embeds_padded, dim=0)
529
+
530
+ if _labels is None:
531
+ new_labels = None
532
+ else:
533
+ new_labels = new_labels_padded
534
+
535
+ if _attention_mask is None:
536
+ attention_mask = None
537
+ else:
538
+ attention_mask = attention_mask.to(dtype=_attention_mask.dtype)
539
+
540
+ if _position_ids is None:
541
+ position_ids = None
542
+
543
+ return (
544
+ None,
545
+ position_ids,
546
+ attention_mask,
547
+ past_key_values,
548
+ new_input_embeds,
549
+ new_labels,
550
+ )
551
+
552
+ def repack_multimodal_data(
553
+ self,
554
+ input_ids,
555
+ position_ids,
556
+ attention_mask,
557
+ past_key_values,
558
+ inputs_embeds,
559
+ labels,
560
+ ):
561
+ # kentang-mit@: reorder and repack (reduce computation overhead)
562
+ # requires transformers replacement.
563
+ new_inputs_embeds = []
564
+ new_position_ids = []
565
+ new_labels = []
566
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
567
+ sorted_seqlens_in_batch, sorted_idx = torch.sort(seqlens_in_batch, descending=True)
568
+ # print(sorted_seqlens_in_batch)
569
+ max_seqlen = inputs_embeds.shape[1]
570
+
571
+ cur_inputs_embeds = []
572
+ cur_position_ids = []
573
+ cur_labels = []
574
+ cur_batch_len = 0
575
+ # print(sorted_seqlens_in_batch.device, len(sorted_seqlens_in_batch), max_seqlen)
576
+ for i in range(len(sorted_seqlens_in_batch)):
577
+ cur_seqlen = sorted_seqlens_in_batch[i].item()
578
+ if cur_seqlen + cur_batch_len <= max_seqlen:
579
+ cur_batch_len += cur_seqlen
580
+ # each item: num_tokens x num_channels
581
+ # remove padding on-the-fly
582
+ cur_inputs_embeds.append(inputs_embeds[sorted_idx[i]][attention_mask[sorted_idx[i]]])
583
+ # each item: num_tokens
584
+ cur_position_ids.append(
585
+ torch.arange(
586
+ cur_inputs_embeds[-1].shape[0],
587
+ device=cur_inputs_embeds[-1].device,
588
+ )
589
+ )
590
+ # each item: num_tokens
591
+ # remove padding on-the-fly
592
+ cur_labels.append(labels[sorted_idx[i]][attention_mask[sorted_idx[i]]])
593
+ else:
594
+ new_inputs_embeds.append(torch.cat(cur_inputs_embeds, 0))
595
+ new_position_ids.append(torch.cat(cur_position_ids, 0))
596
+ new_labels.append(torch.cat(cur_labels, 0))
597
+ # The current batch is too long. We will start a new batch.
598
+ cur_batch_len = cur_seqlen
599
+ cur_inputs_embeds = [inputs_embeds[sorted_idx[i]][attention_mask[sorted_idx[i]]]]
600
+ cur_position_ids = [
601
+ torch.arange(
602
+ cur_inputs_embeds[-1].shape[0],
603
+ device=cur_inputs_embeds[-1].device,
604
+ )
605
+ ]
606
+ cur_labels = [labels[sorted_idx[i]][attention_mask[sorted_idx[i]]]]
607
+
608
+ if len(cur_inputs_embeds):
609
+ new_inputs_embeds.append(torch.cat(cur_inputs_embeds, 0))
610
+ new_position_ids.append(torch.cat(cur_position_ids, 0))
611
+ new_labels.append(torch.cat(cur_labels, 0))
612
+
613
+ # print(new_position_ids[0].device, [x.shape for x in new_inputs_embeds], [x.shape for x in new_labels], [x.shape for x in new_position_ids])
614
+ # assert 0
615
+ new_inputs_embeds = torch.nn.utils.rnn.pad_sequence(
616
+ new_inputs_embeds, batch_first=True, padding_value=self.llm.pad_token_id
617
+ )
618
+
619
+ new_position_ids = torch.nn.utils.rnn.pad_sequence(new_position_ids, batch_first=True, padding_value=-1)
620
+
621
+ new_labels = torch.nn.utils.rnn.pad_sequence(new_labels, batch_first=True, padding_value=IGNORE_INDEX)
622
+ ## yunhao: it's currently a workaround to avoid errors for seq_len < 100
623
+ new_attention_mask = new_position_ids.ne(-1)
624
+ # sanity check
625
+ assert new_attention_mask.sum() == attention_mask.sum()
626
+ # print(new_inputs_embeds.shape, (new_attention_mask.sum(1)))
627
+ # print(sorted_seqlens_in_batch.device, sorted_seqlens_in_batch, new_attention_mask.sum(1))
628
+
629
+ # return None, position_ids, attention_mask, past_key_values, new_input_embeds, new_labels
630
+ return (
631
+ None,
632
+ new_position_ids,
633
+ new_attention_mask,
634
+ past_key_values,
635
+ new_inputs_embeds,
636
+ new_labels,
637
+ sorted_seqlens_in_batch,
638
+ )
639
+
640
+ def initialize_vision_tokenizer(self, model_args, tokenizer):
641
+ if model_args.mm_use_im_patch_token:
642
+ tokenizer.add_tokens([DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
643
+ self.resize_token_embeddings(len(tokenizer))
644
+
645
+ if model_args.mm_use_im_start_end:
646
+ num_new_tokens = tokenizer.add_tokens([DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True)
647
+ self.resize_token_embeddings(len(tokenizer))
648
+
649
+ if num_new_tokens > 0:
650
+ input_embeddings = self.get_input_embeddings().weight.data
651
+ output_embeddings = self.get_output_embeddings().weight.data
652
+
653
+ input_embeddings_avg = input_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
654
+ output_embeddings_avg = output_embeddings[:-num_new_tokens].mean(dim=0, keepdim=True)
655
+
656
+ input_embeddings[-num_new_tokens:] = input_embeddings_avg
657
+ output_embeddings[-num_new_tokens:] = output_embeddings_avg
658
+ ## TODO yunhao: handle cases for <im_st> <im_end>
659
+ if model_args.pretrain_mm_mlp_adapter:
660
+ mm_projector_weights = torch.load(model_args.pretrain_mm_mlp_adapter, map_location="cpu")
661
+ embed_tokens_weight = mm_projector_weights["model.embed_tokens.weight"]
662
+ assert num_new_tokens == 2
663
+ if input_embeddings.shape == embed_tokens_weight.shape:
664
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight[-num_new_tokens:]
665
+ elif embed_tokens_weight.shape[0] == num_new_tokens:
666
+ input_embeddings[-num_new_tokens:] = embed_tokens_weight
667
+ else:
668
+ raise ValueError(
669
+ f"Unexpected embed_tokens_weight shape. Pretrained: {embed_tokens_weight.shape}. Current: {input_embeddings.shape}. Numer of new tokens: {num_new_tokens}."
670
+ )
671
+ elif model_args.mm_use_im_patch_token:
672
+ if model_args.mm_projector:
673
+ for p in self.get_input_embeddings().parameters():
674
+ p.requires_grad = False
675
+ for p in self.get_output_embeddings().parameters():
676
+ p.requires_grad = False
dam/model/mm_utils.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 NVIDIA CORPORATION & AFFILIATES
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ #
15
+ # SPDX-License-Identifier: Apache-2.0
16
+
17
+ from PIL import Image
18
+ from io import BytesIO
19
+ import base64
20
+ import numpy as np
21
+ import os
22
+
23
+ import torch
24
+ from transformers import StoppingCriteria
25
+ from .constants import IMAGE_TOKEN_INDEX
26
+
27
+ import tempfile
28
+ from io import BytesIO
29
+
30
+
31
+ def get_frame_from_vcap(vidcap, num_frames=10, fps=None, frame_count=None):
32
+ import cv2
33
+
34
+ if fps == None or frame_count == None:
35
+ # if one of fps or frame_count is None, still recompute
36
+ fps = vidcap.get(cv2.CAP_PROP_FPS)
37
+ frame_count = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
38
+ if fps == 0 or frame_count == 0:
39
+ print("Video file not found. return empty images.")
40
+ return [
41
+ Image.new("RGB", (720, 720)),
42
+ ] * num_frames
43
+
44
+ duration = frame_count / fps
45
+ frame_interval = frame_count // num_frames
46
+ if frame_interval == 0 and frame_count <= 1:
47
+ print("frame_interval is equal to 0. return empty image.")
48
+ return [
49
+ Image.new("RGB", (720, 720)),
50
+ ] * num_frames
51
+ # print("duration:", duration, "frames:", frame_count, "intervals:", frame_interval)
52
+
53
+ images = []
54
+ count = 0
55
+ success = True
56
+ frame_indices = np.linspace(0, frame_count - 2, num_frames, dtype=int)
57
+
58
+ while success:
59
+ # print("frame_count:", frame_count, "count:", count, "num_frames:", num_frames, "frame_interval:", frame_interval)
60
+ if frame_count >= num_frames:
61
+ success, frame = vidcap.read()
62
+ if count in frame_indices:
63
+ img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
64
+ im_pil = Image.fromarray(img)
65
+ images.append(im_pil)
66
+ if len(images) >= num_frames:
67
+ return images
68
+ count += 1
69
+ else:
70
+ # Left padding frames if the video is not long enough
71
+ success, frame = vidcap.read()
72
+ if success:
73
+ img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
74
+ im_pil = Image.fromarray(img)
75
+ images.append(im_pil)
76
+ count += 1
77
+ elif count >= 1:
78
+ width, height = images[-1].size
79
+ images = [Image.new("RGB", (width, height))] * \
80
+ (num_frames - len(images)) + images
81
+ print("padding frames:", (num_frames - len(images)))
82
+ return images
83
+ else:
84
+ break
85
+ raise ValueError(
86
+ "Did not find enough frames in the video. return empty image.")
87
+
88
+
89
+ def opencv_extract_frames(vpath_or_bytesio, frames=6, fps=None, frame_count=None):
90
+ """
91
+ Extract frames from a video using OpenCV.
92
+
93
+ Args:
94
+ vpath_or_bytesio (str or BytesIO): Path to the video file or BytesIO object containing the video.
95
+ frames (int): Number of frames to extract from the video.
96
+
97
+ Returns:
98
+ list: List of PIL Images extracted from the video.
99
+
100
+ Raises:
101
+ NotImplementedError: If the type of `vpath_or_bytesio` is not supported.
102
+ """
103
+ import cv2
104
+
105
+ if isinstance(vpath_or_bytesio, str):
106
+ vidcap = cv2.VideoCapture(vpath_or_bytesio)
107
+ return get_frame_from_vcap(vidcap, frames, fps=fps, frame_count=frame_count)
108
+ elif isinstance(vpath_or_bytesio, (BytesIO,)):
109
+ # assuming mp4
110
+ with tempfile.NamedTemporaryFile(delete=True, suffix=".mp4") as temp_video:
111
+ temp_video.write(vpath_or_bytesio.read())
112
+ temp_video_name = temp_video.name
113
+ vidcap = cv2.VideoCapture(temp_video_name)
114
+ return get_frame_from_vcap(vidcap, frames, fps=fps, frame_count=frame_count)
115
+ else:
116
+ raise NotImplementedError(type(vpath_or_bytesio))
117
+
118
+
119
+ def load_image_from_base64(image):
120
+ return Image.open(BytesIO(base64.b64decode(image)))
121
+
122
+
123
+ def expand2square(pil_img, background_color):
124
+ """
125
+ Expand the given PIL image to a square shape by adding padding.
126
+
127
+ Parameters:
128
+ - pil_img: The PIL image to be expanded.
129
+ - background_color: The color of the padding to be added.
130
+
131
+ Returns:
132
+ - The expanded PIL image.
133
+
134
+ If the image is already square, it is returned as is.
135
+ If the image is wider than it is tall, padding is added to the top and bottom.
136
+ If the image is taller than it is wide, padding is added to the left and right.
137
+ """
138
+ width, height = pil_img.size
139
+ if pil_img.mode == 'L':
140
+ background_color = background_color[0]
141
+ if width == height:
142
+ return pil_img
143
+ elif width > height:
144
+ result = Image.new(pil_img.mode, (width, width), background_color)
145
+ result.paste(pil_img, (0, (width - height) // 2))
146
+ return result
147
+ else:
148
+ result = Image.new(pil_img.mode, (height, height), background_color)
149
+ result.paste(pil_img, ((height - width) // 2, 0))
150
+ return result
151
+
152
+
153
+ def process_image(image_file, data_args, image_folder, pil_preprocess_fn=None):
154
+ processor = data_args.image_processor
155
+ if isinstance(image_file, str):
156
+ if image_folder is not None:
157
+ image = Image.open(os.path.join(
158
+ image_folder, image_file)).convert("RGB")
159
+ else:
160
+ image = Image.open(image_file).convert("RGB")
161
+ else:
162
+ # image is stored in bytearray
163
+ image = image_file.convert("RGB")
164
+
165
+ info = None
166
+
167
+ if pil_preprocess_fn is not None:
168
+ image = pil_preprocess_fn(image)
169
+ if isinstance(image, tuple):
170
+ image, info = image
171
+
172
+ if data_args.image_aspect_ratio == "resize":
173
+ if hasattr(data_args.image_processor, "crop_size"):
174
+ # CLIP vision tower
175
+ crop_size = data_args.image_processor.crop_size
176
+ else:
177
+ # SIGLIP vision tower
178
+ assert hasattr(data_args.image_processor, "size")
179
+ crop_size = data_args.image_processor.size
180
+ image = image.resize((crop_size["height"], crop_size["width"]))
181
+ if data_args.image_aspect_ratio == "pad":
182
+
183
+ def expand2square(pil_img, background_color):
184
+ width, height = pil_img.size
185
+ if width == height:
186
+ return pil_img
187
+ elif width > height:
188
+ result = Image.new(
189
+ pil_img.mode, (width, width), background_color)
190
+ result.paste(pil_img, (0, (width - height) // 2))
191
+ return result
192
+ else:
193
+ result = Image.new(
194
+ pil_img.mode, (height, height), background_color)
195
+ result.paste(pil_img, ((height - width) // 2, 0))
196
+ return result
197
+
198
+ image = expand2square(image, tuple(int(x * 255)
199
+ for x in processor.image_mean))
200
+ image = processor.preprocess(image, return_tensors="pt")[
201
+ "pixel_values"][0]
202
+ else:
203
+ # Using default behavior of the vision encoder
204
+ # For CLIP, default is central crop
205
+ # For Radio, default is central crop
206
+ # For Siglip, default is resize
207
+ # For InternVIT, default is resize
208
+ image = processor.preprocess(image, return_tensors="pt")[
209
+ "pixel_values"][0]
210
+ if info is not None:
211
+ return image, info
212
+ return image
213
+
214
+
215
+ def process_images(images, image_processor, model_cfg):
216
+
217
+ model_cfg.image_processor = image_processor
218
+ new_images = [process_image(image, model_cfg, None) for image in images]
219
+
220
+ if all(x.shape == new_images[0].shape for x in new_images):
221
+ new_images = torch.stack(new_images, dim=0)
222
+ return new_images
223
+
224
+
225
+ # Note that newer VILA codebase adds an lstrip option that defaults to False, and the functionality is the same by default
226
+ def tokenizer_image_token(
227
+ prompt, tokenizer, image_token_index=IMAGE_TOKEN_INDEX, return_tensors=None
228
+ ):
229
+ prompt_chunks = [
230
+ tokenizer(chunk).input_ids for chunk in prompt.split("<image>")]
231
+
232
+ def insert_separator(X, sep):
233
+ return [ele for sublist in zip(X, [sep] * len(X)) for ele in sublist][:-1]
234
+
235
+ input_ids = []
236
+ offset = 0
237
+ if (
238
+ len(prompt_chunks) > 0
239
+ and len(prompt_chunks[0]) > 0
240
+ and prompt_chunks[0][0] == tokenizer.bos_token_id
241
+ ):
242
+ offset = 1
243
+ input_ids.append(prompt_chunks[0][0])
244
+
245
+ for x in insert_separator(prompt_chunks, [image_token_index] * (offset + 1)):
246
+ input_ids.extend(x[offset:])
247
+
248
+ if return_tensors is not None:
249
+ if return_tensors == "pt":
250
+ return torch.tensor(input_ids, dtype=torch.long)
251
+ raise ValueError(f"Unsupported tensor type: {return_tensors}")
252
+ return input_ids
253
+
254
+
255
+ def is_gemma_tokenizer(tokenizer):
256
+ return "gemma" in tokenizer.__class__.__name__.lower()
257
+
258
+
259
+ def get_model_name_from_path(model_path):
260
+ model_path = model_path.strip("/")
261
+ model_paths = model_path.split("/")
262
+ if model_paths[-1].startswith("checkpoint-"):
263
+ return model_paths[-2] + "_" + model_paths[-1]
264
+ else:
265
+ return model_paths[-1]
266
+
267
+
268
+ class KeywordsStoppingCriteria(StoppingCriteria):
269
+ def __init__(self, keywords, tokenizer, input_ids):
270
+ self.keywords = keywords
271
+ self.keyword_ids = []
272
+ self.max_keyword_len = 0
273
+ for keyword in keywords:
274
+ cur_keyword_ids = tokenizer(keyword).input_ids
275
+ if (
276
+ len(cur_keyword_ids) > 1
277
+ and cur_keyword_ids[0] == tokenizer.bos_token_id
278
+ ):
279
+ cur_keyword_ids = cur_keyword_ids[1:]
280
+ if len(cur_keyword_ids) > self.max_keyword_len:
281
+ self.max_keyword_len = len(cur_keyword_ids)
282
+ self.keyword_ids.append(torch.tensor(cur_keyword_ids))
283
+ self.tokenizer = tokenizer
284
+ self.start_len = input_ids.shape[1]
285
+
286
+ def call_for_batch(
287
+ self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs
288
+ ) -> bool:
289
+ offset = min(output_ids.shape[1] -
290
+ self.start_len, self.max_keyword_len)
291
+ self.keyword_ids = [
292
+ keyword_id.to(output_ids.device) for keyword_id in self.keyword_ids
293
+ ]
294
+ for keyword_id in self.keyword_ids:
295
+ if (output_ids[0, -keyword_id.shape[0]:] == keyword_id).all():
296
+ return True
297
+ outputs = self.tokenizer.batch_decode(
298
+ output_ids[:, -offset:], skip_special_tokens=True
299
+ )[0]
300
+ for keyword in self.keywords:
301
+ if keyword in outputs:
302
+ return True
303
+ return False
304
+
305
+ def __call__(
306
+ self, output_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs
307
+ ) -> bool:
308
+ outputs = []
309
+ for i in range(output_ids.shape[0]):
310
+ outputs.append(self.call_for_batch(
311
+ output_ids[i].unsqueeze(0), scores))
312
+ return all(outputs)
dam/model/model_utils.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import AutoModelForCausalLM, AutoTokenizer
2
+ import torch
3
+ import torch.nn as nn
4
+ import os
5
+ import warnings
6
+ from typing import Optional, Union, List, Tuple
7
+ from transformers import (
8
+ AutoTokenizer,
9
+ AutoModel,
10
+ AutoModelForCausalLM,
11
+ AutoConfig,
12
+ BitsAndBytesConfig,
13
+ PretrainedConfig,
14
+ PreTrainedModel,
15
+ LlamaConfig,
16
+ LlamaModel,
17
+ )
18
+ from transformers.modeling_outputs import CausalLMOutputWithPast
19
+ from transformers import PretrainedConfig
20
+
21
+ from .llava_arch import LlavaMetaModel, LlavaMetaForCausalLM
22
+ from .language_model.llava_llama import LlavaLlamaConfig
23
+ # TODO: we may move LlavaConfig to configuration_llava.py
24
+ # from model.configuration_llava import LlavaConfig
25
+
26
+ class LlavaLlamaModel(LlavaMetaModel, LlavaMetaForCausalLM, PreTrainedModel):
27
+ config_class = LlavaLlamaConfig
28
+ main_input_name = "input_embeds"
29
+ supports_gradient_checkpointing = True
30
+
31
+ def __init__(self, config: LlavaLlamaConfig = None, *args, **kwargs) -> None:
32
+ super().__init__(config)
33
+ self.init_vlm(config=config, *args, **kwargs)
34
+
35
+ @classmethod
36
+ def from_pretrained(
37
+ cls,
38
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
39
+ *model_args,
40
+ config: Optional[Union[PretrainedConfig, str, os.PathLike]] = None,
41
+ cache_dir: Optional[Union[str, os.PathLike]] = None,
42
+ ignore_mismatched_sizes: bool = False,
43
+ force_download: bool = False,
44
+ local_files_only: bool = False,
45
+ token: Optional[Union[str, bool]] = None,
46
+ revision: str = "main",
47
+ use_safetensors: bool = None,
48
+ **kwargs,
49
+ ):
50
+ if hasattr(cls, "load_pretrained"):
51
+ return cls.load_pretrained(pretrained_model_name_or_path,
52
+ *model_args, config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes, force_download=force_download, local_files_only=local_files_only, token=token,
53
+ revision=revision, use_safetensors=use_safetensors, **kwargs
54
+ )
55
+ return super(LlavaLlamaModel).from_pretrained(pretrained_model_name_or_path,
56
+ *model_args, config=config, cache_dir=cache_dir, ignore_mismatched_sizes=ignore_mismatched_sizes, force_download=force_download, local_files_only=local_files_only, token=token,
57
+ revision=revision, use_safetensors=use_safetensors, **kwargs)
58
+
59
+ def forward(
60
+ self,
61
+ input_ids: torch.LongTensor = None,
62
+ images: Optional[torch.FloatTensor] = None,
63
+ attention_mask: Optional[torch.Tensor] = None,
64
+ position_ids: Optional[torch.LongTensor] = None,
65
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
66
+ inputs_embeds: Optional[torch.FloatTensor] = None,
67
+ labels: Optional[torch.LongTensor] = None,
68
+ use_cache: Optional[bool] = None,
69
+ output_attentions: Optional[bool] = None,
70
+ output_hidden_states: Optional[bool] = None,
71
+ return_dict: Optional[bool] = None,
72
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
73
+ self.freezed_module_patch()
74
+ if inputs_embeds is None:
75
+ (
76
+ input_ids,
77
+ position_ids,
78
+ attention_mask,
79
+ past_key_values,
80
+ inputs_embeds,
81
+ labels,
82
+ ) = self.prepare_inputs_labels_for_multimodal(
83
+ input_ids, position_ids, attention_mask, past_key_values, labels, images
84
+ )
85
+ # Note (kentang-mit@): we have a unit test for this function.
86
+ if self.training:
87
+ (
88
+ _,
89
+ new_position_ids,
90
+ new_attention_mask,
91
+ _,
92
+ new_inputs_embeds,
93
+ new_labels,
94
+ sorted_seqlens_in_batch,
95
+ ) = self.repack_multimodal_data(
96
+ input_ids,
97
+ position_ids,
98
+ attention_mask,
99
+ past_key_values,
100
+ inputs_embeds,
101
+ labels,
102
+ )
103
+ new_input_ids = None
104
+ past_key_values = None
105
+ else:
106
+ new_attention_mask = attention_mask
107
+ new_position_ids = position_ids
108
+ new_inputs_embeds = inputs_embeds
109
+ new_labels = labels
110
+ sorted_seqlens_in_batch = attention_mask.sum(-1).int()
111
+ new_input_ids = input_ids
112
+
113
+ outputs = self.llm.forward(
114
+ input_ids=new_input_ids,
115
+ attention_mask=new_attention_mask,
116
+ position_ids=new_position_ids,
117
+ past_key_values=past_key_values,
118
+ inputs_embeds=new_inputs_embeds,
119
+ labels=new_labels,
120
+ use_cache=use_cache,
121
+ output_attentions=output_attentions,
122
+ output_hidden_states=output_hidden_states,
123
+ return_dict=return_dict,
124
+ seqlens_in_batch=sorted_seqlens_in_batch,
125
+ )
126
+ return outputs
127
+
128
+ @torch.no_grad()
129
+ def generate(
130
+ self,
131
+ input_ids: Optional[torch.FloatTensor] = None,
132
+ images: Optional[torch.FloatTensor] = None,
133
+ attention_mask: Optional[torch.LongTensor] = None,
134
+ **generation_kwargs,
135
+ ):
136
+ if images is not None:
137
+ (
138
+ _,
139
+ _,
140
+ attention_mask,
141
+ _,
142
+ inputs_embeds,
143
+ _,
144
+ ) = self.prepare_inputs_labels_for_multimodal(
145
+ input_ids, None, attention_mask, None, None, images
146
+ )
147
+ else:
148
+ inputs_embeds = self.get_input_embeddings()(input_ids)
149
+ inputs_embeds = inputs_embeds.to(self.dtype)
150
+
151
+ outputs = self.llm.generate(
152
+ inputs_embeds=inputs_embeds,
153
+ attention_mask=attention_mask,
154
+ **generation_kwargs
155
+ )
156
+ return outputs
157
+
158
+
159
+ def disable_torch_init():
160
+ """
161
+ Disable the redundant torch default initialization to accelerate model creation.
162
+ """
163
+ import torch
164
+ setattr(torch.nn.Linear, "reset_parameters", lambda self: None)
165
+ setattr(torch.nn.LayerNorm, "reset_parameters", lambda self: None)
166
+
167
+
168
+ def load_pretrained_model(
169
+ model_path,
170
+ model_name,
171
+ model_base=None,
172
+ load_8bit=False,
173
+ load_4bit=False,
174
+ device_map="auto",
175
+ device="cuda",
176
+ **kwargs,
177
+ ):
178
+ kwargs = {"device_map": device_map, **kwargs}
179
+
180
+ if device != "cuda":
181
+ kwargs["device_map"] = {"": device}
182
+
183
+ if load_8bit:
184
+ kwargs["load_in_8bit"] = True
185
+ elif load_4bit:
186
+ kwargs["load_in_4bit"] = True
187
+ kwargs["quantization_config"] = BitsAndBytesConfig(
188
+ load_in_4bit=True,
189
+ bnb_4bit_compute_dtype=torch.float16,
190
+ bnb_4bit_use_double_quant=True,
191
+ bnb_4bit_quant_type="nf4",
192
+ )
193
+ else:
194
+ kwargs["torch_dtype"] = torch.float16
195
+
196
+ config = AutoConfig.from_pretrained(model_path)
197
+ config.resume_path = model_path
198
+ prepare_config_for_eval(config, kwargs)
199
+
200
+ model = LlavaLlamaModel(
201
+ config=config,
202
+ low_cpu_mem_usage=True,
203
+ **kwargs
204
+ )
205
+ tokenizer = model.tokenizer
206
+
207
+ model.eval()
208
+
209
+ # mm_use_im_start_end = getattr(
210
+ # model.config, "mm_use_im_start_end", False)
211
+ # mm_use_im_patch_token = getattr(
212
+ # model.config, "mm_use_im_patch_token", True)
213
+ # if mm_use_im_patch_token:
214
+ # tokenizer.add_tokens(
215
+ # [DEFAULT_IMAGE_PATCH_TOKEN], special_tokens=True)
216
+ # if mm_use_im_start_end:
217
+ # tokenizer.add_tokens(
218
+ # [DEFAULT_IM_START_TOKEN, DEFAULT_IM_END_TOKEN], special_tokens=True
219
+ # )
220
+
221
+ model.resize_token_embeddings(len(tokenizer))
222
+ vision_tower = model.get_vision_tower()
223
+ vision_tower.to(device=device, dtype=torch.float16)
224
+ mm_projector = model.get_mm_projector()
225
+ mm_projector.to(device=device, dtype=torch.float16)
226
+ context_provider = model.get_context_provider()
227
+ if context_provider is not None:
228
+ context_provider.to(device=device, dtype=torch.float16)
229
+ image_processor = vision_tower.image_processor
230
+
231
+ if hasattr(model.llm.config, "max_sequence_length"):
232
+ context_len = model.config.max_sequence_length
233
+ else:
234
+ context_len = 2048
235
+
236
+ return tokenizer, model, image_processor, context_len
237
+
238
+
239
+ def parse_model_name_or_path(config: PretrainedConfig, model_name="llm", suffix="_cfg"):
240
+ target_model = f"{model_name}{suffix}"
241
+ target_cfg = getattr(config, target_model, None)
242
+
243
+ if isinstance(target_cfg, str):
244
+ return target_cfg
245
+ elif isinstance(target_cfg, dict):
246
+ return target_cfg["architectures"][0]
247
+ else:
248
+ raise ValueError(f"Invalid {target_model} configuration!")
249
+
250
+
251
+ def prepare_config_for_eval(config: PretrainedConfig, kwargs: dict):
252
+ try:
253
+ # compatible with deprecated config convention
254
+ if getattr(config, "vision_tower_cfg", None) is None:
255
+ config.vision_tower_cfg = config.mm_vision_tower
256
+ except AttributeError:
257
+ raise ValueError(
258
+ f"Invalid configuration! Cannot find vision_tower in config:\n{config}")
259
+
260
+ config.model_dtype = kwargs.pop("torch_dtype").__str__()
261
+ # siglip does not support device_map = "auto"
262
+ vision_tower_name = parse_model_name_or_path(config, "vision_tower")
263
+ if "siglip" in vision_tower_name.lower():
264
+ kwargs["device_map"] = "cuda"
265
+
266
+
267
+ AutoConfig.register("llava_llama", LlavaLlamaConfig)
268
+ AutoModel.register(LlavaLlamaConfig, LlavaLlamaModel)
dam/model/multimodal_encoder/__pycache__/builder.cpython-310.pyc ADDED
Binary file (1.55 kB). View file
 
dam/model/multimodal_encoder/__pycache__/context_provider.cpython-310.pyc ADDED
Binary file (9.85 kB). View file
 
dam/model/multimodal_encoder/__pycache__/siglip_encoder.cpython-310.pyc ADDED
Binary file (1.11 kB). View file
 
dam/model/multimodal_encoder/__pycache__/vision_encoder.cpython-310.pyc ADDED
Binary file (4.79 kB). View file
 
dam/model/multimodal_encoder/builder.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
2
+ import torch
3
+ import os
4
+ from transformers import AutoConfig, PretrainedConfig, PreTrainedModel
5
+ from .siglip_encoder import SiglipVisionTower
6
+ from .context_provider import ContextProvider, ContextProviderConfig
7
+
8
+ def build_vision_tower(
9
+ model_name_or_path: str, config: PretrainedConfig
10
+ ) -> PreTrainedModel:
11
+ ## skip vision tower instantiation
12
+ if model_name_or_path is None:
13
+ return None
14
+
15
+ vision_tower_arch = None
16
+ if config.resume_path and "radio" not in model_name_or_path:
17
+ assert os.path.exists(
18
+ model_name_or_path
19
+ ), f"Resume vision tower path {model_name_or_path} does not exist!"
20
+ vision_tower_cfg = AutoConfig.from_pretrained(model_name_or_path, trust_remote_code=True)
21
+ vision_tower_arch = vision_tower_cfg.architectures[0].lower()
22
+ vision_tower_name = (
23
+ vision_tower_arch if vision_tower_arch is not None else model_name_or_path
24
+ )
25
+
26
+ if "siglip" in vision_tower_name:
27
+ vision_tower = SiglipVisionTower(model_name_or_path, config)
28
+ else:
29
+ raise ValueError(f"Unknown vision tower: {model_name_or_path}")
30
+
31
+ config.mm_hidden_size = vision_tower.config.hidden_size
32
+ return vision_tower
33
+
34
+ def build_context_provider(
35
+ model_type_or_path: str, config: PretrainedConfig
36
+ ) -> PreTrainedModel:
37
+ if model_type_or_path is None:
38
+ return None
39
+
40
+ ## load from pretrained model
41
+ if config.resume_path:
42
+ assert os.path.exists(
43
+ model_type_or_path
44
+ ), f"Resume context provider path {model_type_or_path} does not exist!"
45
+ return ContextProvider.from_pretrained(
46
+ model_type_or_path, config, torch_dtype=eval(config.model_dtype)
47
+ )
48
+ ## build from scratch
49
+ else:
50
+ mm_projector_cfg = ContextProviderConfig(model_type_or_path)
51
+ mm_projector = ContextProvider(mm_projector_cfg, config).to(
52
+ eval(config.model_dtype)
53
+ )
54
+ return mm_projector
dam/model/multimodal_encoder/clip_encoder_ignored.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is modified from https://github.com/haotian-liu/LLaVA/
2
+ import torch
3
+
4
+ from llava.model.multimodal_encoder.vision_encoder import VisionTower
5
+ from transformers import (
6
+ PretrainedConfig,
7
+ CLIPVisionModel,
8
+ CLIPImageProcessor,
9
+ )
10
+
11
+
12
+ class CLIPVisionTower(VisionTower):
13
+ def __init__(self, model_name_or_path: str, config: PretrainedConfig):
14
+ super().__init__(model_name_or_path, config)
15
+ self.image_processor = CLIPImageProcessor.from_pretrained(model_name_or_path)
16
+ self.vision_tower = CLIPVisionModel.from_pretrained(
17
+ model_name_or_path, torch_dtype=eval(config.model_dtype)
18
+ )
19
+ self.is_loaded = True