JayRay5 commited on
Commit
bde2bb5
·
verified ·
1 Parent(s): 3a67d30

Delete src

Browse files
src/__init__.py DELETED
File without changes
src/__pycache__/__init__.cpython-312.pyc DELETED
Binary file (168 Bytes)
 
src/__pycache__/configuration_divedoc.cpython-312.pyc DELETED
Binary file (6.64 kB)
 
src/__pycache__/modeling_divedoc.cpython-312.pyc DELETED
Binary file (26.1 kB)
 
src/__pycache__/processing_divedoc.cpython-312.pyc DELETED
Binary file (16.1 kB)
 
src/configuration_divedoc.py DELETED
@@ -1,211 +0,0 @@
1
- from transformers import PretrainedConfig, DonutSwinConfig, GemmaConfig, CONFIG_MAPPING
2
- from typing import Tuple, Literal
3
-
4
-
5
- class PamConfig(PretrainedConfig):
6
- model_type = "pam"
7
-
8
- def __init__(
9
- self,
10
- sequence_mapping_layer_type: Literal[
11
- "linear_projection", "bilinear_interpolation"
12
- ] = "bilinear_interpolation",
13
- student_fmap_dim: Tuple[int, int] = (80, 60),
14
- student_embedding_dim: int = 1024,
15
- teacher_fmap_dim: Tuple[int, int] = (64, 64),
16
- teacher_embedding_dim: int = 1152,
17
- **kwargs,
18
- ):
19
- self.sequence_mapping_layer_type = sequence_mapping_layer_type
20
- self.student_fmap_dim = student_fmap_dim
21
- self.student_embedding_dim = student_embedding_dim
22
- self.teacher_fmap_dim = teacher_fmap_dim
23
- self.teacher_embedding_dim = teacher_embedding_dim
24
- super().__init__(**kwargs)
25
-
26
-
27
- class SwinPamVisionEncoderConfig(PretrainedConfig):
28
- model_type = "swinpam"
29
- sub_configs = {"encoder_config": DonutSwinConfig, "pam_config": PamConfig}
30
-
31
- def __init__(
32
- self,
33
- encoder_config: DonutSwinConfig = None,
34
- pam_config: PamConfig = None,
35
- **kwargs,
36
- ):
37
- self.encoder_config = encoder_config
38
- self.pam_config = pam_config
39
-
40
- if isinstance(self.encoder_config, dict):
41
- encoder_config["model_type"] = (
42
- encoder_config["model_type"]
43
- if "model_type" in encoder_config
44
- else "donut-swin"
45
- )
46
- if encoder_config["model_type"] == "donut-swin":
47
- self.encoder_config = DonutSwinConfig(**encoder_config)
48
- else:
49
- print(f"Encoder type: {encoder_config['model_type']}")
50
- self.encoder_config = CONFIG_MAPPING[encoder_config["model_type"]](
51
- **encoder_config
52
- )
53
-
54
- """
55
- elif encoder_config is None:
56
- print("coucou2")
57
- self.encoder_config = DonutSwinConfig()
58
- """
59
-
60
- if isinstance(self.pam_config, dict):
61
- """
62
- pam_config["model_type"] = (
63
- pam_config["model_type"] if "model_type" in pam_config else "pam"
64
- )
65
- """
66
- if pam_config["model_type"] == "pam":
67
- self.pam_config = PamConfig(**pam_config)
68
- else:
69
- raise ValueError(
70
- f"pam_config['model_type'] should be 'pam', got {pam_config['model_type']}"
71
- )
72
- """
73
- elif pam_config is None:
74
- self.pam_config = PamConfig()
75
- """
76
- super().__init__(**kwargs)
77
-
78
-
79
- class DIVEdocConfig(PretrainedConfig):
80
- keys_to_ignore_at_inference = ["past_key_values"]
81
- sub_configs = {
82
- "vision_config": SwinPamVisionEncoderConfig,
83
- "text_config": GemmaConfig,
84
- }
85
- model_type = "DIVEdoc"
86
-
87
- def __init__(
88
- self,
89
- vision_config=None,
90
- text_config=None,
91
- ignore_index=-100,
92
- image_token_index=256000,
93
- vocab_size=257152,
94
- projection_dim=2048,
95
- hidden_size=2048,
96
- # _attn_implementation_autoset = True,
97
- **kwargs,
98
- ):
99
- self._ignore_index = ignore_index
100
- self.image_token_index = image_token_index
101
- self._vocab_size = vocab_size
102
- self.projection_dim = projection_dim
103
- self.hidden_size = hidden_size
104
- self.vision_config = vision_config
105
- self.is_encoder_decoder = False
106
- # self._attn_implementation_autoset = _attn_implementation_autoset
107
-
108
- if isinstance(self.vision_config, dict):
109
- vision_config["model_type"] = (
110
- vision_config["model_type"]
111
- if "model_type" in vision_config
112
- else "swinpam"
113
- )
114
- if vision_config["model_type"] == "swinpam":
115
- self.vision_config = SwinPamVisionEncoderConfig(
116
- encoder_config=vision_config["encoder_config"],
117
- pam_config=vision_config["pam_config"],
118
- )
119
- else:
120
- self.vision_config = CONFIG_MAPPING[vision_config["model_type"]](
121
- **vision_config
122
- )
123
- elif vision_config is None:
124
- self.vision_config = get_vision_config("swinpam")
125
-
126
- self.text_config = text_config
127
- if isinstance(self.text_config, dict):
128
- text_config["model_type"] = (
129
- text_config["model_type"] if "model_type" in text_config else "gemma"
130
- )
131
- self.text_config = CONFIG_MAPPING[text_config["model_type"]](**text_config)
132
- elif text_config is None:
133
- self.text_config = CONFIG_MAPPING["gemma"](
134
- hidden_size=2048,
135
- num_hidden_layers=18,
136
- intermediate_size=16384,
137
- num_attention_heads=8,
138
- num_key_value_heads=1,
139
- is_encoder_decoder=False,
140
- vocab_size=vocab_size,
141
- )
142
-
143
- self.text_config.num_image_tokens = (
144
- self.vision_config.pam_config.teacher_fmap_dim[0]
145
- * self.vision_config.pam_config.teacher_fmap_dim[1]
146
- )
147
- self.vision_config.projection_dim = projection_dim
148
- super().__init__(**kwargs)
149
-
150
- def to_dict(self):
151
- output = super().to_dict()
152
- output.pop("_ignore_index", None)
153
- return output
154
-
155
-
156
- def get_swin_vision_config(image_size=[2560, 1920], hidden_size=1024):
157
- encoder_config = DonutSwinConfig(
158
- attention_probs_dropout_prob=0.0,
159
- depths=[2, 2, 14, 2],
160
- drop_path_rate=0.1,
161
- embed_dim=128,
162
- hidden_act="gelu",
163
- hidden_dropout_prob=0.0,
164
- hidden_size=hidden_size,
165
- image_size=image_size,
166
- initializer_range=0.02,
167
- layer_norm_eps=1e-05,
168
- mlp_ratio=4.0,
169
- model_type="donut-swin",
170
- num_channels=3,
171
- num_heads=[4, 8, 16, 32],
172
- num_layers=4,
173
- patch_size=4,
174
- path_norm=True,
175
- qkv_bias=True,
176
- use_absolute_embeddings=False,
177
- window_size=10,
178
- )
179
- return encoder_config
180
-
181
-
182
- def get_vision_config(
183
- visual_encoder_type: Literal["swinpam", "siglip80m"],
184
- image_size=[2560, 1920],
185
- sequence_mapping_layer_type="bilinear",
186
- student_fmap_dim=(80, 60),
187
- student_embedding_dim=1024,
188
- teacher_fmap_dim=(64, 64),
189
- teacher_embedding_dim=1152,
190
- ):
191
- pam_config = PamConfig(
192
- sequence_mapping_layer_type=sequence_mapping_layer_type,
193
- student_fmap_dim=student_fmap_dim,
194
- student_embedding_dim=student_embedding_dim,
195
- teacher_fmap_dim=teacher_fmap_dim,
196
- teacher_embedding_dim=teacher_embedding_dim,
197
- )
198
-
199
- if visual_encoder_type == "swinpam":
200
- encoder_config = get_swin_vision_config(
201
- image_size=image_size, hidden_size=student_embedding_dim
202
- )
203
- ve_config = SwinPamVisionEncoderConfig(
204
- encoder_config=encoder_config, pam_config=pam_config
205
- )
206
- return ve_config
207
-
208
- else:
209
- raise ValueError(
210
- f"Unknown visual encoder type, need 'swinpam', got {visual_encoder_type}."
211
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/evaluation.py DELETED
@@ -1,104 +0,0 @@
1
- # file and os lib managements
2
- import json
3
- import os
4
- import tqdm
5
-
6
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
7
- # Change the path of some HF environment variables to store the download data (model and dataset) from the hub to a choosen location
8
- os.environ["HF_HOME"] = "../.cache"
9
- os.environ["HF_HUB_CACHE"] = "../.cache"
10
- os.environ["HF_DATASETS_CACHE"] = "../.cache"
11
-
12
- # ML libraries
13
- from accelerate import infer_auto_device_map, dispatch_model
14
- from datasets import load_dataset
15
- import torch
16
-
17
- from modeling_divedoc import get_model
18
- from processing_divedoc import get_processor
19
-
20
-
21
- def test_results_generation(path):
22
- # create a new folder to save the results
23
- results_path = "{}/results".format(path)
24
- if "results" not in os.listdir(path):
25
- os.mkdir(results_path)
26
-
27
- hf_token = os.getenv("HF_TOKEN")
28
-
29
- if not hf_token:
30
- raise ValueError("Error: HF_TOKEN not found!")
31
- """
32
-
33
- STUDENT LOADING
34
-
35
- """
36
-
37
- model = get_model()
38
- processor = get_processor(
39
- hf_token, img_height=2048, img_width=2048, img_lm_input_seq_length=4096
40
- )
41
-
42
- """
43
-
44
- Evaluation
45
-
46
-
47
- """
48
-
49
- test_dataset = load_dataset(
50
- "pixparse/docvqa-single-page-questions",
51
- split="test",
52
- streaming=True,
53
- revision="33136ef456fa5a3fe68568d6e31dda4eeff95b9b",
54
- )
55
- batch_dataset = test_dataset.batch(2)
56
-
57
- device_map = infer_auto_device_map(
58
- model,
59
- max_memory={d: "5GiB" for d in range(torch.cuda.device_count())},
60
- no_split_module_classes=["DonutSwinStage", "GemmaDecoderLayer"],
61
- )
62
- model = dispatch_model(model, device_map)
63
- pred_list = []
64
-
65
- print("[INFO] Generate answers on the test set [INFO]")
66
- with torch.inference_mode():
67
- for batch in tqdm.tqdm(batch_dataset):
68
- # preprocessing
69
- imgs = []
70
- for i in batch["image"]:
71
- imgs.append(i.convert("RGB"))
72
- txt = batch["question"]
73
- model_inputs = processor(
74
- text=txt, images=imgs, return_tensors="pt", padding=True
75
- )
76
- input_len = model_inputs["input_ids"].shape[-1]
77
-
78
- # processing
79
- model_inputs = model_inputs.to(model.device)
80
- generation = model.generate(
81
- **model_inputs, max_new_tokens=100, do_sample=False
82
- )
83
-
84
- # postprocessing
85
- for i in range(len(generation)):
86
- pred = generation[i][input_len:]
87
- decoded = processor.tokenizer.decode(pred, skip_special_tokens=True)
88
- pred_list.append(
89
- {"answer": decoded, "questionId": batch["question_id"][i]}
90
- )
91
- print(
92
- "QuestionId : {}, Question : {}, Reponse : {}".format(
93
- batch["question_id"][i], batch["question"][i], decoded
94
- )
95
- )
96
-
97
- results_file = "model_docvqa_test_results.json"
98
- with open("{}/{}".format(results_path, results_file), "w") as f:
99
- json.dump(pred_list, f)
100
-
101
-
102
- if __name__ == "__main__":
103
- default_path = "./"
104
- test_results_generation(default_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/main.py DELETED
@@ -1,116 +0,0 @@
1
- import os
2
- import io
3
- import torch
4
- import uvicorn
5
- from contextlib import asynccontextmanager
6
- from fastapi import FastAPI, UploadFile, File, Form, HTTPException
7
- from fastapi.concurrency import run_in_threadpool
8
- import asyncio
9
- from PIL import Image
10
-
11
- from src.modeling_divedoc import get_model
12
- from src.processing_divedoc import get_processor
13
-
14
- constants = {}
15
- model_lock = asyncio.Lock()
16
-
17
-
18
- @asynccontextmanager
19
- async def lifespan(app: FastAPI):
20
- """
21
- Init & Load model/processor
22
- """
23
- hf_token = os.getenv("HF_TOKEN")
24
-
25
- if not hf_token:
26
- print("WARNING: HF_TOKEN not found!")
27
-
28
- try:
29
- constants["processor"] = get_processor(
30
- hf_token, img_height=2048, img_width=2048, img_lm_input_seq_length=4096
31
- )
32
-
33
- constants["model"] = get_model()
34
-
35
- constants["device"] = constants["model"].device
36
-
37
- print("[INFO] Model & Processor loaded. [INFO]")
38
-
39
- except Exception as e:
40
- print(f"Error Message : {e}")
41
- raise e
42
-
43
- yield # API running
44
-
45
- # when API is stopped
46
- constants.clear()
47
- print("[INFO] API stopped. [INFO]")
48
-
49
-
50
- # --- Start the API ---
51
- app = FastAPI(
52
- title="DIVE-Doc API",
53
- description="OCR-Free Document VQA API",
54
- version="1.0.0",
55
- lifespan=lifespan,
56
- )
57
-
58
- # --- ENDPOINTS ---
59
-
60
-
61
- @app.get("/")
62
- def health_check():
63
- return {"status": "ok", "model_loaded": "model" in constants}
64
-
65
-
66
- @app.post("/ask")
67
- async def ask_question(question: str = Form(...), file: UploadFile = File(...)):
68
- if "model" not in constants:
69
- raise HTTPException(status_code=503, detail="Model not found.")
70
-
71
- if "processor" not in constants:
72
- raise HTTPException(status_code=503, detail="Processor not found.")
73
-
74
- if "device" not in constants:
75
- raise HTTPException(status_code=503, detail="Device not found.")
76
-
77
- if file.content_type not in ["image/jpeg", "image/png", "image/webp"]:
78
- raise HTTPException(
79
- status_code=400, detail="Unsupported format, require JPG or PNG."
80
- )
81
-
82
- try:
83
- contents = await file.read()
84
- image = Image.open(io.BytesIO(contents)).convert("RGB")
85
-
86
- model = constants["model"]
87
- processor = constants["processor"]
88
- device = constants["device"]
89
-
90
- inputs = processor(
91
- text=question, images=image, return_tensors="pt", padding=True
92
- ).to(device)
93
- input_length = inputs["input_ids"].shape[-1]
94
-
95
- # authorize on thread at a time
96
- async with model_lock:
97
-
98
- def generate_answer():
99
- with torch.inference_mode():
100
- return model.generate(**inputs, max_new_tokens=100, do_sample=False)
101
-
102
- output_ids = await run_in_threadpool(generate_answer)
103
-
104
- generated_ids = output_ids[0][input_length:]
105
- answer = processor.decode(generated_ids, skip_special_tokens=True)
106
-
107
- return {"question": question, "answer": answer, "filename": file.filename}
108
-
109
- except Exception as e:
110
- print(f"Error during model prediction: {e}")
111
- raise HTTPException(status_code=500, detail=str(e))
112
-
113
-
114
- # To start the server using python main.py
115
- if __name__ == "__main__":
116
- uvicorn.run("src.main:app", host="0.0.0.0", port=8000, reload=True) # nosec B104 (to ignore the bandit alert)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/modeling_divedoc.py DELETED
@@ -1,640 +0,0 @@
1
- import torch
2
- import torch.nn as nn
3
- import torch.utils.checkpoint
4
- import torch.nn.functional as F
5
- from torch import Tensor
6
-
7
- from transformers import Cache, HybridCache, StaticCache
8
- from transformers.modeling_outputs import BaseModelOutput
9
- from transformers.utils import (
10
- ModelOutput,
11
- is_torchdynamo_compiling,
12
- replace_return_docstrings,
13
- )
14
- from transformers.utils.deprecation import deprecate_kwarg
15
- from transformers import (
16
- PreTrainedModel,
17
- AutoConfig,
18
- PaliGemmaPreTrainedModel,
19
- AutoModelForCausalLM,
20
- GenerationMixin,
21
- )
22
- from transformers.models.paligemma.modeling_paligemma import (
23
- PaliGemmaCausalLMOutputWithPast,
24
- )
25
- from transformers.models.paligemma.configuration_paligemma import PaliGemmaConfig
26
- from transformers.models.donut.modeling_donut_swin import DonutSwinModel
27
- from transformers.utils import logging
28
-
29
-
30
- from .configuration_divedoc import SwinPamVisionEncoderConfig, DIVEdocConfig
31
- from typing import List, Optional, Tuple, Union, Literal
32
- from dataclasses import dataclass
33
-
34
-
35
- logger = logging.get_logger(__name__)
36
-
37
-
38
- class PAM(nn.Module):
39
- def __init__(
40
- self,
41
- sequence_mapping_layer_type: Literal[
42
- "linear_projection", "bilinear", "bicubic", "nearest-exact"
43
- ] = "bilinear",
44
- student_fmap_dim: Tuple[int, int] = (80, 60),
45
- student_embedding_dim: int = 1024,
46
- teacher_fmap_dim: Tuple[int, int] = (64, 64),
47
- teacher_embedding_dim: int = 1152,
48
- ):
49
- super().__init__()
50
- self.sequence_mapping_layer_type = sequence_mapping_layer_type
51
- self.sequence_mapping_layer = (
52
- nn.Linear(
53
- student_fmap_dim[0] * student_fmap_dim[1],
54
- teacher_fmap_dim[0] * teacher_fmap_dim[1],
55
- )
56
- if sequence_mapping_layer_type == "linear_projection"
57
- else None
58
- )
59
- self.embedding_projection_layer = nn.Sequential(
60
- nn.Linear(student_embedding_dim, teacher_embedding_dim),
61
- nn.LayerNorm((teacher_embedding_dim,), eps=1e-06),
62
- )
63
-
64
- self.student_fmap_dim = student_fmap_dim
65
- self.student_embedding_dim = student_embedding_dim
66
- self.teacher_fmap_dim = teacher_fmap_dim
67
- self.teacher_embedding_dim = teacher_embedding_dim
68
-
69
- print(self.student_fmap_dim)
70
-
71
- # take input x of shape (Batch, Nb_token, Dim_embedding)
72
- def forward(self, x: Tensor) -> Tensor:
73
- #
74
- """
75
- if x.shape[1] != self.student_fmap_dim[0] * self.student_fmap_dim[1] or x.shape[2] != self.student_embedding_dim:
76
- raise ValueError(f"Expected input shape (*, {self.student_fmap_dim[0] * self.student_fmap_dim[1],self.student_embedding_dim}), "
77
- f"but got {x.shape}")
78
- """
79
-
80
- if x.shape[1] != (self.teacher_fmap_dim[0] * self.teacher_fmap_dim[1]):
81
- print(x.shape[1])
82
- print(self.teacher_fmap_dim[0] * self.teacher_fmap_dim[1])
83
- print("Resizing")
84
- if self.sequence_mapping_layer_type == "linear_projection":
85
- x = torch.permute(x, (0, 2, 1))
86
- x = self.sequence_mapping_layer(x)
87
- x = torch.permute(x, (0, 2, 1))
88
-
89
- elif self.sequence_mapping_layer_type in [
90
- "bilinear",
91
- "bicubic",
92
- "nearest-exact",
93
- ]:
94
- batch_size, _, embedding_size = x.size()
95
- x = x.view(
96
- batch_size,
97
- self.student_fmap_dim[0],
98
- self.student_fmap_dim[1],
99
- embedding_size,
100
- ).permute(0, 3, 1, 2)
101
- x = F.interpolate(
102
- x, size=self.teacher_fmap_dim, mode=self.sequence_mapping_layer_type
103
- ) # Shape: (1, D, target_height, target_width)
104
- x = x.permute(0, 2, 3, 1).reshape(batch_size, -1, embedding_size)
105
-
106
- else:
107
- raise ValueError(
108
- "Need a sequence mapping type in [linear_projection, bilinear",
109
- "bicubic",
110
- "nearest-exact], got {sequence_mapping_layer_type}",
111
- )
112
-
113
- x = self.embedding_projection_layer(x)
114
- print(x.shape)
115
- return x
116
-
117
-
118
- class SwinPam(nn.Module):
119
- def __init__(
120
- self,
121
- encoder_config: AutoConfig,
122
- pam_sequence_mapping_layer_type: Literal[
123
- "linear_projection", "bilinear", "bicubic", "nearest-exact"
124
- ] = "bilinear",
125
- pam_student_fmap_dim: Tuple[int, int] = (80, 60),
126
- pam_student_embedding_dim: int = 1024,
127
- pam_teacher_fmap_dim: Tuple[int, int] = (64, 64),
128
- pam_teacher_embedding_dim: int = 1152,
129
- ):
130
- super().__init__()
131
- self.encoder_model = DonutSwinModel(encoder_config)
132
- print(pam_student_fmap_dim)
133
- self.pam = PAM(
134
- sequence_mapping_layer_type=pam_sequence_mapping_layer_type,
135
- student_fmap_dim=pam_student_fmap_dim,
136
- student_embedding_dim=pam_student_embedding_dim,
137
- teacher_fmap_dim=pam_teacher_fmap_dim,
138
- teacher_embedding_dim=pam_teacher_embedding_dim,
139
- )
140
-
141
- def forward(self, x):
142
- x = self.encoder_model(x).last_hidden_state
143
- x = self.pam(x)
144
- return x
145
-
146
-
147
- @dataclass
148
- class SwinPamVisionEncoderOutput(ModelOutput):
149
- """
150
- Base class for PaliGemmacausal language model (or autoregressive) outputs.
151
- Args:
152
- last_hidden_states (`torch.FloatTensor`, *optional*):
153
- A `torch.FloatTensor` of size `(batch_size, sequence_length, hidden_size)`.
154
- image_hidden_states of the model produced by the vision encoder after projecting last hidden state.
155
- """
156
-
157
- last_hidden_states: Optional[torch.FloatTensor] = None
158
-
159
-
160
- class SwinPamVisionEncoder(PreTrainedModel):
161
- config_class = SwinPamVisionEncoderConfig
162
- keys_to_ignore_at_inference = ["past_key_values"]
163
-
164
- def __init__(self, config):
165
- super().__init__(config)
166
- self.model = SwinPam(
167
- config.encoder_config,
168
- config.pam_config.sequence_mapping_layer_type,
169
- config.pam_config.student_fmap_dim,
170
- config.pam_config.student_embedding_dim,
171
- config.pam_config.teacher_fmap_dim,
172
- config.pam_config.teacher_embedding_dim,
173
- )
174
-
175
- def forward(self, x):
176
- x = self.model(x)
177
- return BaseModelOutput(last_hidden_state=x)
178
-
179
-
180
- # Copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/paligemma/modeling_paligemma.py
181
- class PaliGemmaMultiModalProjector(nn.Module):
182
- def __init__(self, config: PaliGemmaConfig):
183
- super().__init__()
184
- self.linear = nn.Linear(
185
- config.vision_config.pam_config.teacher_embedding_dim,
186
- config.vision_config.projection_dim,
187
- bias=True,
188
- )
189
-
190
- def forward(self, image_features):
191
- hidden_states = self.linear(image_features)
192
-
193
- return hidden_states
194
-
195
-
196
- # Copied & Adapted from https://github.com/huggingface/transformers/blob/main/src/transformers/models/paligemma/modeling_paligemma.py
197
- _CONFIG_FOR_DOC = "DIVEdocConfig"
198
-
199
-
200
- class DIVEdoc(PaliGemmaPreTrainedModel, GenerationMixin):
201
- config_class = DIVEdocConfig
202
-
203
- def __init__(self, config: DIVEdocConfig):
204
- super().__init__(config)
205
-
206
- print(f"Vision config in end-to-end model: {config.vision_config.model_type}")
207
- if config.vision_config.model_type == "swinpam":
208
- self.vision_tower = SwinPamVisionEncoder(config=config.vision_config)
209
-
210
- else:
211
- raise ValueError("Unknown model_type in vision_config")
212
-
213
- self.multi_modal_projector = PaliGemmaMultiModalProjector(config)
214
- self.vocab_size = config.text_config.vocab_size
215
-
216
- language_model = AutoModelForCausalLM.from_config(config=config.text_config)
217
-
218
- if language_model._tied_weights_keys is not None:
219
- self._tied_weights_keys = [
220
- f"language_model.{k}" for k in language_model._tied_weights_keys
221
- ]
222
- self.language_model = language_model
223
-
224
- self.pad_token_id = (
225
- self.config.pad_token_id if self.config.pad_token_id is not None else -1
226
- )
227
- self.post_init()
228
-
229
- # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_input_embeddings with Llava->PaliGemma
230
- def get_input_embeddings(self):
231
- return self.language_model.get_input_embeddings()
232
-
233
- # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_input_embeddings with Llava->PaliGemma
234
- def set_input_embeddings(self, value):
235
- self.language_model.set_input_embeddings(value)
236
-
237
- # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_output_embeddings with Llava->PaliGemma
238
- def get_output_embeddings(self):
239
- return self.language_model.get_output_embeddings()
240
-
241
- # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_output_embeddings with Llava->PaliGemma
242
- def set_output_embeddings(self, new_embeddings):
243
- self.language_model.set_output_embeddings(new_embeddings)
244
-
245
- # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.set_decoder with Llava->PaliGemma
246
- def set_decoder(self, decoder):
247
- self.language_model.set_decoder(decoder)
248
-
249
- # Copied from transformers.models.llava.modeling_llava.LlavaForConditionalGeneration.get_decoder with Llava->PaliGemma
250
- def get_decoder(self):
251
- return self.language_model.get_decoder()
252
-
253
- def get_dtype(self):
254
- return self.dtype
255
-
256
- def _update_causal_mask(
257
- self,
258
- attention_mask,
259
- token_type_ids=None,
260
- past_key_values=None,
261
- cache_position=None,
262
- input_tensor=None,
263
- is_training: bool = None,
264
- dtype=None, # to handle quantized finetuning issue when model switch between 4 or 8bit and float
265
- ):
266
- if self.config.text_config._attn_implementation == "flash_attention_2":
267
- if attention_mask is not None and 0.0 in attention_mask:
268
- return attention_mask
269
- return None
270
- is_training = is_training if is_training is not None else self.training
271
- using_static_cache = isinstance(past_key_values, StaticCache)
272
-
273
- # Handle the case when the model is quantized in 4 or 8 bit
274
-
275
- if dtype is not None:
276
- min_dtype = torch.finfo(dtype).min
277
- else:
278
- min_dtype = torch.finfo(self.get_dtype()).min
279
-
280
- if input_tensor is None:
281
- input_tensor = attention_mask
282
-
283
- inputs_lead_dim, sequence_length = input_tensor.shape[:2]
284
- if using_static_cache:
285
- target_length = past_key_values.get_max_cache_shape()
286
- elif isinstance(past_key_values, HybridCache):
287
- target_length = past_key_values.get_max_cache_shape()
288
- else:
289
- target_length = (
290
- attention_mask.shape[-1]
291
- if isinstance(attention_mask, torch.Tensor)
292
- else cache_position[0] + sequence_length + 1
293
- )
294
-
295
- if attention_mask is not None and attention_mask.dim() == 4:
296
- # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
297
- return attention_mask
298
- """ initial line but changed for quantization processing
299
- causal_mask = torch.full(
300
- (sequence_length, target_length), fill_value=min_dtype, dtype=self.dtype, device=cache_position.device
301
- )
302
- """
303
- causal_mask = torch.full(
304
- (sequence_length, target_length),
305
- fill_value=min_dtype,
306
- dtype=dtype,
307
- device=cache_position.device,
308
- )
309
- # Causal diagonal mask only if training, otherwise attend to the whole prefix. Training-specific attn for prefix is handled below
310
- if sequence_length != 1:
311
- if is_training:
312
- causal_mask = torch.triu(causal_mask, diagonal=1)
313
- else:
314
- causal_mask[:, :sequence_length] = 0.0
315
-
316
- causal_mask *= torch.arange(
317
- target_length, device=cache_position.device
318
- ) > cache_position.reshape(-1, 1)
319
- causal_mask = causal_mask[None, None, :, :].expand(inputs_lead_dim, 1, -1, -1)
320
- if attention_mask is not None:
321
- causal_mask = (
322
- causal_mask.clone()
323
- ) # copy to contiguous memory for in-place edit
324
- mask_length = attention_mask.shape[-1]
325
-
326
- # First unmask prefix tokens during training
327
- if is_training:
328
- if token_type_ids is None:
329
- raise ValueError("Token type ids must be provided during training")
330
- causal_mask[:, :, :, :mask_length] = causal_mask[
331
- :, :, :, :mask_length
332
- ].masked_fill(
333
- token_type_ids[:, None, None, :].to(causal_mask.device) == 0, 0
334
- )
335
-
336
- # Then apply padding mask (will mask pad tokens)
337
- padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[
338
- :, None, None, :
339
- ].to(causal_mask.device)
340
- padding_mask = padding_mask == 0
341
- causal_mask[:, :, :, :mask_length] = causal_mask[
342
- :, :, :, :mask_length
343
- ].masked_fill(padding_mask, min_dtype)
344
-
345
- return causal_mask
346
-
347
- def get_image_features(self, pixel_values: torch.FloatTensor):
348
- """
349
- Obtains image last hidden states from the vision tower and apply multimodal projection.
350
- Args:
351
- pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`)
352
- The tensors corresponding to the input images.
353
- Returns:
354
- image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
355
- """
356
- image_outputs = self.vision_tower(pixel_values)
357
- selected_image_feature = image_outputs.last_hidden_state
358
- image_features = self.multi_modal_projector(selected_image_feature)
359
- image_features = image_features / (self.config.text_config.hidden_size**0.5)
360
- return image_features
361
-
362
- @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
363
- @replace_return_docstrings(
364
- output_type=PaliGemmaCausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
365
- )
366
- def forward(
367
- self,
368
- input_ids: torch.LongTensor = None,
369
- pixel_values: torch.FloatTensor = None,
370
- attention_mask: Optional[torch.Tensor] = None,
371
- position_ids: Optional[torch.LongTensor] = None,
372
- past_key_values: Optional[Union[List[torch.FloatTensor], Cache]] = None,
373
- token_type_ids: Optional[torch.LongTensor] = None,
374
- cache_position: Optional[torch.LongTensor] = None,
375
- inputs_embeds: Optional[torch.FloatTensor] = None,
376
- labels: Optional[torch.LongTensor] = None,
377
- use_cache: Optional[bool] = None,
378
- output_attentions: Optional[bool] = None,
379
- output_hidden_states: Optional[bool] = None,
380
- return_dict: Optional[bool] = None,
381
- logits_to_keep: Union[int, torch.Tensor] = 0,
382
- **lm_kwargs,
383
- ) -> Union[Tuple, PaliGemmaCausalLMOutputWithPast]:
384
- r"""
385
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
386
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
387
- config.text_config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
388
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.text_config.vocab_size]`.
389
- logits_to_keep (`int` or `torch.Tensor`, *optional*):
390
- If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
391
- `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
392
- token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
393
- If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
394
- This is useful when using packed tensor format (single dimension for batch and sequence length).
395
- Returns:
396
- Example:
397
- ```python
398
- >>> from PIL import Image
399
- >>> import requests
400
- >>> from transformers import AutoProcessor, PaliGemmaForConditionalGeneration
401
- >>> model = PaliGemmaForConditionalGeneration.from_pretrained("google/paligemma2-3b-mix-224")
402
- >>> processor = AutoProcessor.from_pretrained("google/paligemma2-3b-mix-224")
403
- >>> prompt = "Where is the cat standing?"
404
- >>> url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/pipeline-cat-chonk.jpeg"
405
- >>> image = Image.open(requests.get(url, stream=True).raw)
406
- >>> inputs = processor(images=image, text=prompt, return_tensors="pt")
407
- >>> # Generate
408
- >>> generate_ids = model.generate(**inputs,)
409
- >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
410
- "Where is the cat standing?\nsnow"
411
- ```"""
412
- # save the original dtype before switching to 4bit when quantization
413
- dtype = self.get_dtype()
414
-
415
- if (input_ids is None) ^ (inputs_embeds is not None):
416
- raise ValueError(
417
- "You must specify exactly one of input_ids or inputs_embeds"
418
- )
419
-
420
- output_attentions = (
421
- output_attentions
422
- if output_attentions is not None
423
- else self.config.output_attentions
424
- )
425
- output_hidden_states = (
426
- output_hidden_states
427
- if output_hidden_states is not None
428
- else self.config.output_hidden_states
429
- )
430
- return_dict = (
431
- return_dict if return_dict is not None else self.config.use_return_dict
432
- )
433
-
434
- is_training = token_type_ids is not None and labels is not None
435
-
436
- # Replace image id woth PAD if the image token if OOV, to avoid index-errors
437
- if input_ids is not None and self.config.image_token_index >= self.vocab_size:
438
- special_image_mask = input_ids == self.config.image_token_index
439
- llm_input_ids = input_ids.clone()
440
- llm_input_ids[special_image_mask] = 0
441
- else:
442
- llm_input_ids = input_ids
443
-
444
- if inputs_embeds is None:
445
- inputs_embeds = self.get_input_embeddings()(llm_input_ids)
446
-
447
- if cache_position is None:
448
- past_seen_tokens = (
449
- past_key_values.get_seq_length() if past_key_values is not None else 0
450
- )
451
- cache_position = torch.arange(
452
- past_seen_tokens,
453
- past_seen_tokens + inputs_embeds.shape[1],
454
- device=inputs_embeds.device,
455
- )
456
-
457
- if position_ids is None:
458
- position_ids = (
459
- cache_position.unsqueeze(0) + 1
460
- ) # Paligemma positions are 1-indexed
461
-
462
- # Merge text and images
463
- if pixel_values is not None:
464
- image_features = self.get_image_features(pixel_values)
465
-
466
- if input_ids is None:
467
- special_image_mask = inputs_embeds == self.get_input_embeddings()(
468
- torch.tensor(
469
- self.config.image_token_index,
470
- dtype=torch.long,
471
- device=inputs_embeds.device,
472
- )
473
- )
474
- else:
475
- special_image_mask = (
476
- input_ids == self.config.image_token_index
477
- ).unsqueeze(-1)
478
- special_image_mask = special_image_mask.expand_as(inputs_embeds).to(
479
- inputs_embeds.device
480
- )
481
-
482
- if (
483
- not is_torchdynamo_compiling()
484
- and inputs_embeds[special_image_mask].numel() != image_features.numel()
485
- ):
486
- image_tokens_in_text = (special_image_mask).sum(dim=1).sum(dim=0)[0]
487
- raise ValueError(
488
- f"Number of images does not match number of special image tokens in the input text. "
489
- f"Got {image_tokens_in_text} image tokens in the text but {image_features.shape[0] * image_features.shape[1]} "
490
- "tokens from image embeddings."
491
- )
492
- image_features = image_features.to(
493
- inputs_embeds.device, inputs_embeds.dtype
494
- )
495
- inputs_embeds = inputs_embeds.masked_scatter(
496
- special_image_mask, image_features
497
- )
498
-
499
- # mask out pad-token-ids in labels for BC
500
- if labels is not None and self.pad_token_id in labels:
501
- logger.warning_once(
502
- "`labels` contains `pad_token_id` which will be masked with `config.ignore_index`. "
503
- "You have to mask out `pad_token_id` when preparing `labels`, this behavior will be removed in v.4.46.",
504
- )
505
- labels = torch.where(
506
- input_ids == self.pad_token_id, self.config.ignore_index, labels
507
- )
508
-
509
- causal_mask = self._update_causal_mask(
510
- attention_mask,
511
- token_type_ids,
512
- past_key_values,
513
- cache_position,
514
- inputs_embeds,
515
- is_training,
516
- dtype=dtype,
517
- )
518
- outputs = self.language_model(
519
- attention_mask=causal_mask,
520
- position_ids=position_ids,
521
- past_key_values=past_key_values,
522
- inputs_embeds=inputs_embeds,
523
- use_cache=use_cache,
524
- output_attentions=output_attentions,
525
- output_hidden_states=output_hidden_states,
526
- return_dict=return_dict,
527
- cache_position=cache_position,
528
- logits_to_keep=logits_to_keep,
529
- **lm_kwargs,
530
- )
531
-
532
- logits = outputs[0]
533
- loss = None
534
- if labels is not None:
535
- # Upcast to float if we need to compute the loss to avoid potential precision issues
536
- shift_logits = logits[..., :-1, :]
537
- shift_labels = labels[..., 1:]
538
-
539
- if attention_mask is not None:
540
- # we use the input attention mask to shift the logits and labels, because it is 2D.
541
- # we also crop attn mask in case it is longer, which happens in PrefixTuning with peft
542
- shift_attention_mask = attention_mask[:, -shift_logits.shape[1] :].to(
543
- logits.device
544
- )
545
- shift_logits = shift_logits[
546
- shift_attention_mask.to(logits.device) != 0
547
- ].contiguous()
548
- shift_labels = shift_labels[
549
- shift_attention_mask.to(shift_labels.device) != 0
550
- ].contiguous()
551
- else:
552
- shift_logits = shift_logits.contiguous()
553
- shift_labels = shift_labels.contiguous()
554
- # Flatten the tokens
555
- loss_fct = nn.CrossEntropyLoss()
556
-
557
- flat_logits = shift_logits.view(-1, self.config.text_config.vocab_size)
558
- flat_labels = shift_labels.view(-1).to(shift_logits.device)
559
-
560
- valid_mask = flat_labels != -100
561
-
562
- flat_labels = flat_labels[valid_mask]
563
- flat_logits = flat_logits[valid_mask]
564
-
565
- loss = loss_fct(flat_logits, flat_labels)
566
- if not return_dict:
567
- output = (logits,) + outputs[1:]
568
- return (loss,) + output if loss is not None else output
569
-
570
- return PaliGemmaCausalLMOutputWithPast(
571
- loss=loss,
572
- logits=logits,
573
- past_key_values=outputs.past_key_values,
574
- hidden_states=outputs.hidden_states,
575
- attentions=outputs.attentions,
576
- image_hidden_states=image_features if pixel_values is not None else None,
577
- )
578
-
579
- def prepare_inputs_for_generation(
580
- self,
581
- input_ids,
582
- past_key_values=None,
583
- inputs_embeds=None,
584
- cache_position=None,
585
- position_ids=None,
586
- pixel_values=None,
587
- attention_mask=None,
588
- token_type_ids=None,
589
- use_cache=True,
590
- logits_to_keep=None,
591
- labels=None,
592
- **kwargs,
593
- ):
594
- # Overwritten -- custom `position_ids` and `pixel_values` handling
595
- model_inputs = self.language_model.prepare_inputs_for_generation(
596
- input_ids,
597
- past_key_values=past_key_values,
598
- inputs_embeds=inputs_embeds,
599
- attention_mask=attention_mask,
600
- position_ids=position_ids,
601
- cache_position=cache_position,
602
- use_cache=use_cache,
603
- logits_to_keep=logits_to_keep,
604
- token_type_ids=token_type_ids,
605
- **kwargs,
606
- )
607
-
608
- # position_ids in Paligemma are 1-indexed
609
- if model_inputs.get("position_ids") is not None:
610
- model_inputs["position_ids"] += 1
611
- # If we're in cached decoding stage, pixel values should be None because input ids do not contain special image token anymore
612
- # Otherwise we need pixel values to be passed to model. NOTE: use_cache=False needs pixel_values always
613
- if cache_position[0] == 0:
614
- model_inputs["pixel_values"] = pixel_values
615
- is_training = token_type_ids is not None and labels is not None
616
- if cache_position[0] == 0 and isinstance(past_key_values, HybridCache):
617
- input_tensor = inputs_embeds if inputs_embeds is not None else input_ids
618
- causal_mask = self._update_causal_mask(
619
- attention_mask,
620
- token_type_ids,
621
- past_key_values,
622
- cache_position,
623
- input_tensor,
624
- is_training,
625
- )
626
- model_inputs["attention_mask"] = causal_mask
627
-
628
- return model_inputs
629
-
630
-
631
- def get_model():
632
- model = DIVEdoc.from_pretrained(
633
- "JayRay5/DIVE-Doc-FRD",
634
- trust_remote_code=True,
635
- revision="37d4cc1859b1cb6691930fe573e33b0a88928c59",
636
- ).eval()
637
- for param in model.parameters():
638
- param.requires_grad = False
639
-
640
- return model
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/processing_divedoc.py DELETED
@@ -1,372 +0,0 @@
1
- from typing import Optional, Union
2
-
3
- import numpy as np
4
-
5
- from transformers import AutoTokenizer, DonutImageProcessor
6
- from transformers.feature_extraction_utils import BatchFeature
7
- from transformers.image_utils import ImageInput, is_valid_image
8
- from transformers.processing_utils import (
9
- MultiModalData,
10
- ProcessingKwargs,
11
- ProcessorMixin,
12
- TextKwargs,
13
- Unpack,
14
- )
15
- from transformers.tokenization_utils_base import (
16
- AddedToken,
17
- PreTokenizedInput,
18
- TextInput,
19
- )
20
- from transformers.utils import logging
21
-
22
-
23
- logger = logging.get_logger(__name__)
24
-
25
- IMAGE_TOKEN = "<image>"
26
- EXTRA_TOKENS = [f"<loc{i:0>4}>" for i in range(1024)] + [
27
- f"<seg{i:0>3}>" for i in range(128)
28
- ]
29
-
30
-
31
- # Copied from https://github.com/huggingface/transformers/blob/main/src/transformers/processing_utils.py
32
- class PaliGemmaTextKwargs(TextKwargs):
33
- suffix: Optional[
34
- Union[TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]]
35
- ]
36
-
37
-
38
- class PaliGemmaProcessorKwargs(ProcessingKwargs, total=False):
39
- text_kwargs: PaliGemmaTextKwargs
40
- _defaults = {
41
- "text_kwargs": {
42
- "padding": False,
43
- "return_mm_token_type_ids": False,
44
- },
45
- "images_kwargs": {
46
- "data_format": "channels_first",
47
- },
48
- }
49
-
50
-
51
- # Copied from transformers.models.idefics2.processing_idefics2.is_url
52
- def is_url(val) -> bool:
53
- return isinstance(val, str) and val.startswith("http")
54
-
55
-
56
- # Copied from transformers.models.idefics2.processing_idefics2.is_image_or_image_url
57
- def is_image_or_image_url(elem):
58
- return is_url(elem) or is_valid_image(elem)
59
-
60
-
61
- def _is_str_or_image(elem):
62
- return isinstance(elem, (str)) or is_image_or_image_url(elem)
63
-
64
-
65
- def build_string_from_input(prompt, bos_token, image_seq_len, image_token, num_images):
66
- """
67
- Builds a string from the input prompt and image tokens.
68
- For example, for the call:
69
- build_string_from_input(
70
- prompt="Prefix str"
71
- bos_token="<s>",
72
- image_seq_len=3,
73
- image_token="<im>",
74
- )
75
- The output will be:
76
- "<im><im><im><s>Initial str"
77
- Args:
78
- prompt (`list[Union[str, ImageInput]]`): The input prompt.
79
- bos_token (`str`): The beginning of sentence token.
80
- image_seq_len (`int`): The length of the image sequence.
81
- image_token (`str`): The image token.
82
- num_images (`int`): Number of images in the prompt.
83
- """
84
- return f"{image_token * image_seq_len * num_images}{bos_token}{prompt}\n"
85
-
86
-
87
- # Copied and adapted from https://github.com/huggingface/transformers/blob/main/src/transformers/models/paligemma/processing_paligemma.py
88
- class PaliGemmaProcessor(ProcessorMixin):
89
- attributes = ["image_processor", "tokenizer"]
90
- image_processor_class = "DonutImageProcessor" # change from the original SigLipImageProcessor to DonutImageProcessor
91
- tokenizer_class = "GemmaTokenizerFast"
92
- r"""
93
- Constructs a PaliGemma processor which wraps a PaliGemma image processor and a PaliGemma tokenizer into a single processor.
94
-
95
- [`PaliGemmaProcessor`] offers all the functionalities of [`SiglipImageProcessor`] and [`GemmaTokenizerFast`]. See the
96
- [`~PaliGemmaProcessor.__call__`] and [`~PaliGemmaProcessor.decode`] for more information.
97
-
98
- Args:
99
- image_processor ([`SiglipImageProcessor`], *optional*):
100
- The image processor is a required input.
101
- tokenizer ([`GemmaTokenizerFast`], *optional*):
102
- The tokenizer is a required input.
103
- chat_template (`str`, *optional*): A Jinja template which will be used to convert lists of messages
104
- in a chat into a tokenizable string.
105
- """
106
-
107
- def __init__(
108
- self,
109
- image_processor=None,
110
- tokenizer=None,
111
- chat_template=None,
112
- **kwargs,
113
- ):
114
- if not hasattr(image_processor, "image_seq_length"):
115
- raise ValueError(
116
- "Image processor is missing an `image_seq_length` attribute."
117
- )
118
-
119
- self.image_seq_length = image_processor.image_seq_length
120
-
121
- if not hasattr(tokenizer, "image_token"):
122
- image_token = AddedToken(IMAGE_TOKEN, normalized=False, special=True)
123
- tokens_to_add = {"additional_special_tokens": [image_token]}
124
- tokenizer.add_special_tokens(tokens_to_add)
125
- self.image_token_id = tokenizer.convert_tokens_to_ids(IMAGE_TOKEN)
126
- self.image_token = IMAGE_TOKEN
127
- else:
128
- self.image_token_id = tokenizer.image_token_id
129
- self.image_token = tokenizer.image_token
130
-
131
- tokenizer.add_tokens(EXTRA_TOKENS)
132
- tokenizer.add_bos_token = False
133
- tokenizer.add_eos_token = False
134
-
135
- super().__init__(image_processor, tokenizer, chat_template=chat_template)
136
-
137
- def __call__(
138
- self,
139
- images: Optional[ImageInput] = None,
140
- text: Union[
141
- TextInput, PreTokenizedInput, list[TextInput], list[PreTokenizedInput]
142
- ] = None,
143
- **kwargs: Unpack[PaliGemmaProcessorKwargs],
144
- ) -> BatchFeature:
145
- """
146
- Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
147
- and `kwargs` arguments to GemmaTokenizerFast's [`~GemmaTokenizerFast.__call__`] if `text` is not `None` to encode
148
- the text. To prepare the image(s), this method forwards the `images` and `kwargs` arguments to
149
- SiglipImageProcessor's [`~SiglipImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring
150
- of the above two methods for more information.
151
-
152
- The usage for PaliGemma fine-tuning preparation is slightly different than usual. suffix passed are suffixes to
153
- the prompt in `text`, and will be placed after the prompt. This is because attention is handled differently for
154
- the prefix and the suffix. For instance,
155
- ```python
156
- image = PIL_cow_image
157
- prompt = "answer en Where is the cow standing?"
158
- suffix = "on the beach"
159
- inputs = processor(text=prompt, images=image, suffix=suffix)
160
- ```
161
- Here `inputs` will contain the `input_ids` and `token_type_ids` that follow
162
- ```python
163
- inputs["input_ids"][:, 256:]
164
- # tensor([[ 2, 6006, 603, 573, 13910, 9980, 235336, 108, 477, 573, 8318]])
165
- inputs["token_type_ids"][:, 256:]
166
- tensor([[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]])
167
- ```
168
- Meaning the last three tokens are of "label" ("suffix") type while the other ones are of "prefix" type.
169
-
170
-
171
- Args:
172
- images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `list[PIL.Image.Image]`, `list[np.ndarray]`, `list[torch.Tensor]`):
173
- The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
174
- tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape (C, H, W), where C is a
175
- number of channels, H and W are image height and width.
176
- text (`str`, `list[str]`, `list[list[str]]`):
177
- The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
178
- (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
179
- `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
180
- return_tensors (`str` or [`~utils.TensorType`], *optional*):
181
- If set, will return tensors of a particular framework. Acceptable values are:
182
-
183
- - `'pt'`: Return PyTorch `torch.Tensor` objects.
184
- - `'np'`: Return NumPy `np.ndarray` objects.
185
- suffix (`str`, `list[str]`, `list[list[str]]`):
186
- The suffixes or batch of suffixes to be encoded. Only necessary for finetuning. See https://github.com/google-research/big_vision/blob/main/big_vision/configs/proj/paligemma/README.md
187
- for more information. If your prompt is "<image> What is on the image", the suffix corresponds to the expected prediction "a cow sitting on a bench".
188
-
189
- Returns:
190
- [`BatchFeature`]: A [`BatchFeature`] with the following fields:
191
-
192
- - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`. If `suffix`
193
- is provided, the `input_ids` will also contain the suffix input ids.
194
- - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
195
- `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
196
- `None`).
197
- - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
198
- - **labels** -- Labels compatible with training if `suffix` is not None
199
- """
200
-
201
- output_kwargs = self._merge_kwargs(
202
- PaliGemmaProcessorKwargs,
203
- tokenizer_init_kwargs=self.tokenizer.init_kwargs,
204
- **kwargs,
205
- )
206
- suffix = output_kwargs["text_kwargs"].pop("suffix", None)
207
-
208
- return_token_type_ids = True
209
-
210
- if images is None:
211
- raise ValueError(
212
- "`images` are expected as arguments to a `PaliGemmaProcessor` instance."
213
- )
214
- if text is None:
215
- logger.warning_once(
216
- "You are using PaliGemma without a text prefix. It will perform as a picture-captioning model."
217
- )
218
- text = ""
219
-
220
- if _is_str_or_image(text):
221
- text = [text]
222
- elif isinstance(text, list) and _is_str_or_image(text[0]):
223
- pass
224
-
225
- if text is not None and images is not None:
226
- if not any(IMAGE_TOKEN in sample for sample in text):
227
- logger.warning(
228
- "You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special "
229
- "image tokens in the text, as many tokens as there are images per each text. It is recommended to "
230
- "add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images "
231
- "each text has and add special tokens."
232
- )
233
-
234
- if isinstance(text, list) and isinstance(images, list):
235
- if len(images) != len(text):
236
- raise ValueError(
237
- f"Received {len(images)} images for {len(text)} prompts. Each prompt should be associated with an image or list of images."
238
- )
239
-
240
- # make a nested list of lists to be able to iterate over the images and text below
241
-
242
- if is_valid_image(images):
243
- images = [images]
244
- elif isinstance(images, (list, tuple)) and is_valid_image(images[0]):
245
- images = [image for image in images]
246
- elif not (
247
- isinstance(images, (list, tuple))
248
- # and isinstance(images[0], (list, tuple))
249
- and is_valid_image(images[0])
250
- ):
251
- raise ValueError(
252
- "images must be an image, list of images or list of list of images"
253
- )
254
-
255
- input_strings = [
256
- build_string_from_input(
257
- prompt=prompt,
258
- bos_token=self.tokenizer.bos_token,
259
- image_seq_len=self.image_seq_length,
260
- image_token=IMAGE_TOKEN,
261
- num_images=len(image_list)
262
- if isinstance(image_list, list)
263
- else 1,
264
- )
265
- for prompt, image_list in zip(text, images)
266
- ]
267
- else:
268
- expanded_samples = []
269
- for sample in text:
270
- expanded_sample = sample.replace(
271
- IMAGE_TOKEN, IMAGE_TOKEN * self.image_seq_length
272
- )
273
- bos_rfind_index = expanded_sample.rfind(IMAGE_TOKEN)
274
- bos_index = (
275
- bos_rfind_index + len(IMAGE_TOKEN)
276
- if bos_rfind_index != -1
277
- else 0
278
- )
279
- expanded_sample = (
280
- expanded_sample[:bos_index]
281
- + self.tokenizer.bos_token
282
- + expanded_sample[bos_index:]
283
- )
284
- expanded_samples.append(expanded_sample)
285
- input_strings = [f"{sample}\n" for sample in expanded_samples]
286
-
287
- if suffix is not None and _is_str_or_image(suffix):
288
- suffix = [suffix]
289
- if suffix is not None:
290
- suffix = [sfx + self.tokenizer.eos_token for sfx in suffix]
291
- pixel_values = self.image_processor(images, **output_kwargs["images_kwargs"])[
292
- "pixel_values"
293
- ]
294
-
295
- return_tensors = output_kwargs["text_kwargs"].pop("return_tensors", None)
296
- return_mm_token_type_ids = output_kwargs["text_kwargs"].pop(
297
- "return_mm_token_type_ids", None
298
- )
299
- inputs = self.tokenizer(
300
- input_strings,
301
- text_pair=suffix,
302
- return_token_type_ids=return_token_type_ids,
303
- **output_kwargs["text_kwargs"],
304
- )
305
- # self._check_special_mm_tokens(input_strings, inputs, modalities=["image"])
306
-
307
- return_data = {**inputs, "pixel_values": pixel_values}
308
-
309
- # TODO: ideally we would control label generation separately, now that we always return token_type_ids.
310
- if return_token_type_ids:
311
- labels = np.array(inputs["input_ids"])
312
- labels[np.array(inputs["token_type_ids"]) == 0] = -100
313
- return_data.update({"labels": labels})
314
-
315
- if return_mm_token_type_ids:
316
- array_ids = np.array(return_data["input_ids"])
317
- mm_token_type_ids = np.zeros_like(return_data["input_ids"])
318
- mm_token_type_ids[array_ids == self.image_token_id] = 1
319
- return_data["mm_token_type_ids"] = mm_token_type_ids.tolist()
320
-
321
- return BatchFeature(data=return_data, tensor_type=return_tensors)
322
-
323
- def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
324
- """
325
- Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
326
-
327
- Args:
328
- image_sizes (list[list[str]], *optional*):
329
- The input sizes formatted as (height, width) per each image.
330
- Returns:
331
- `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
332
- input modalities, along with other useful data.
333
- """
334
- vision_data = {}
335
- if image_sizes is not None:
336
- num_image_tokens = [self.image_seq_length] * len(image_sizes)
337
- num_image_patches = [1] * len(image_sizes)
338
- vision_data.update(
339
- {
340
- "num_image_tokens": num_image_tokens,
341
- "num_image_patches": num_image_patches,
342
- }
343
- )
344
- return MultiModalData(**vision_data)
345
-
346
- @property
347
- def model_input_names(self):
348
- tokenizer_input_names = self.tokenizer.model_input_names + [
349
- "token_type_ids",
350
- "labels",
351
- ]
352
- image_processor_input_names = self.image_processor.model_input_names
353
- return list(tokenizer_input_names + image_processor_input_names)
354
-
355
-
356
- def get_processor(hf_token, img_height, img_width, img_lm_input_seq_length):
357
- tokenizer = AutoTokenizer.from_pretrained(
358
- "google/paligemma-3b-ft-docvqa-896",
359
- token=hf_token,
360
- revision="acbe61b1b8507f7c7af03a0d42e9908e7b6d4d5d",
361
- )
362
- image_processor = DonutImageProcessor.from_pretrained(
363
- "naver-clova-ix/donut-base-finetuned-docvqa",
364
- revision="b19d2e332684b0e2d35d9144ce34047767335cf8",
365
- )
366
- image_processor.image_seq_length = img_lm_input_seq_length
367
- image_processor.size["height"], image_processor.size["width"] = (
368
- img_height,
369
- img_width,
370
- )
371
- processor = PaliGemmaProcessor(tokenizer=tokenizer, image_processor=image_processor)
372
- return processor
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/quantization_test.ipynb DELETED
@@ -1,664 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "code",
5
- "execution_count": 1,
6
- "id": "767721e7",
7
- "metadata": {},
8
- "outputs": [
9
- {
10
- "name": "stderr",
11
- "output_type": "stream",
12
- "text": [
13
- "d:\\miniconda3\\envs\\divedoc-platform-env\\Lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
14
- " from .autonotebook import tqdm as notebook_tqdm\n"
15
- ]
16
- }
17
- ],
18
- "source": [
19
- "import os\n",
20
- "\n",
21
- "os.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n",
22
- "# Change the path of some HF environment variables to store the download data (model and dataset) from the hub to a choosen location\n",
23
- "os.environ[\"HF_HOME\"] = \"../.cache\"\n",
24
- "os.environ[\"HF_HUB_CACHE\"] = \"../.cache\"\n",
25
- "os.environ[\"HF_DATASETS_CACHE\"] = \"../.cache\"\n",
26
- "from transformers import AutoTokenizer, DonutImageProcessor\n",
27
- "from modeling_divedoc import DIVEdoc\n",
28
- "from processing_divedoc import get_processor\n",
29
- "from datasets import load_dataset\n",
30
- "import torch"
31
- ]
32
- },
33
- {
34
- "cell_type": "code",
35
- "execution_count": 2,
36
- "id": "24d917a4",
37
- "metadata": {},
38
- "outputs": [],
39
- "source": [
40
- "hf_token = os.getenv(\"HF_TOKEN\")"
41
- ]
42
- },
43
- {
44
- "cell_type": "code",
45
- "execution_count": 3,
46
- "id": "dea772a2",
47
- "metadata": {},
48
- "outputs": [
49
- {
50
- "name": "stdout",
51
- "output_type": "stream",
52
- "text": [
53
- "cc\n"
54
- ]
55
- }
56
- ],
57
- "source": [
58
- "if hf_token:\n",
59
- " print(\"cc\")"
60
- ]
61
- },
62
- {
63
- "cell_type": "code",
64
- "execution_count": 4,
65
- "id": "dab560d7",
66
- "metadata": {},
67
- "outputs": [],
68
- "source": [
69
- "safe_cache_dir = \"../../models_cache\"\n",
70
- "os.makedirs(safe_cache_dir, exist_ok=True)"
71
- ]
72
- },
73
- {
74
- "cell_type": "code",
75
- "execution_count": 5,
76
- "id": "3952e1b6",
77
- "metadata": {},
78
- "outputs": [
79
- {
80
- "name": "stdout",
81
- "output_type": "stream",
82
- "text": [
83
- "Vision config in end-to-end model: swinpam\n",
84
- "[64, 64]\n",
85
- "[64, 64]\n"
86
- ]
87
- },
88
- {
89
- "name": "stderr",
90
- "output_type": "stream",
91
- "text": [
92
- "Loading checkpoint shards: 0%| | 0/3 [00:00<?, ?it/s]"
93
- ]
94
- },
95
- {
96
- "ename": "",
97
- "evalue": "",
98
- "output_type": "error",
99
- "traceback": [
100
- "\u001b[1;31mThe Kernel crashed while executing code in the current cell or a previous cell. \n",
101
- "\u001b[1;31mPlease review the code in the cell(s) to identify a possible cause of the failure. \n",
102
- "\u001b[1;31mClick <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info. \n",
103
- "\u001b[1;31mView Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details."
104
- ]
105
- }
106
- ],
107
- "source": [
108
- "model = DIVEdoc.from_pretrained(\"JayRay5/DIVE-Doc-FRD\",dtype=torch.float16, trust_remote_code=True,offload_folder=safe_cache_dir)"
109
- ]
110
- },
111
- {
112
- "cell_type": "code",
113
- "execution_count": null,
114
- "id": "8329270e",
115
- "metadata": {},
116
- "outputs": [],
117
- "source": [
118
- "assert all(not p.requires_grad for p in model.parameters())"
119
- ]
120
- },
121
- {
122
- "cell_type": "code",
123
- "execution_count": null,
124
- "id": "81f16574",
125
- "metadata": {},
126
- "outputs": [
127
- {
128
- "name": "stderr",
129
- "output_type": "stream",
130
- "text": [
131
- "d:\\miniconda3\\envs\\divedoc-platform-env\\Lib\\site-packages\\huggingface_hub\\file_download.py:143: UserWarning: `huggingface_hub` cache-system uses symlinks by default to efficiently store duplicated files but your machine does not support them in D:\\informatique\\projets\\python\\MLOps\\DIVE_Doc_plateform\\.cache\\models--google--paligemma-3b-ft-docvqa-896. Caching files will still work but in a degraded version that might require more space on your disk. This warning can be disabled by setting the `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For more details, see https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations.\n",
132
- "To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator. In order to activate developer mode, see this article: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development\n",
133
- " warnings.warn(message)\n",
134
- "Xet Storage is enabled for this repo, but the 'hf_xet' package is not installed. Falling back to regular HTTP download. For better performance, install the package with: `pip install huggingface_hub[hf_xet]` or `pip install hf_xet`\n",
135
- "Xet Storage is enabled for this repo, but the 'hf_xet' package is not installed. Falling back to regular HTTP download. For better performance, install the package with: `pip install huggingface_hub[hf_xet]` or `pip install hf_xet`\n",
136
- "d:\\miniconda3\\envs\\divedoc-platform-env\\Lib\\site-packages\\huggingface_hub\\file_download.py:143: UserWarning: `huggingface_hub` cache-system uses symlinks by default to efficiently store duplicated files but your machine does not support them in D:\\informatique\\projets\\python\\MLOps\\DIVE_Doc_plateform\\.cache\\models--naver-clova-ix--donut-base-finetuned-docvqa. Caching files will still work but in a degraded version that might require more space on your disk. This warning can be disabled by setting the `HF_HUB_DISABLE_SYMLINKS_WARNING` environment variable. For more details, see https://huggingface.co/docs/huggingface_hub/how-to-cache#limitations.\n",
137
- "To support symlinks on Windows, you either need to activate Developer Mode or to run Python as an administrator. In order to activate developer mode, see this article: https://docs.microsoft.com/en-us/windows/apps/get-started/enable-your-device-for-development\n",
138
- " warnings.warn(message)\n"
139
- ]
140
- },
141
- {
142
- "ename": "NameError",
143
- "evalue": "name 'model' is not defined",
144
- "output_type": "error",
145
- "traceback": [
146
- "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
147
- "\u001b[31mNameError\u001b[39m Traceback (most recent call last)",
148
- "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[4]\u001b[39m\u001b[32m, line 9\u001b[39m\n\u001b[32m 4\u001b[39m image_processor = DonutImageProcessor.from_pretrained(\n\u001b[32m 5\u001b[39m \u001b[33m\"\u001b[39m\u001b[33mnaver-clova-ix/donut-base-finetuned-docvqa\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m 6\u001b[39m )\n\u001b[32m 7\u001b[39m image_processor.image_seq_length = \u001b[32m4096\u001b[39m\n\u001b[32m 8\u001b[39m image_processor.size[\u001b[33m\"\u001b[39m\u001b[33mheight\u001b[39m\u001b[33m\"\u001b[39m], image_processor.size[\u001b[33m\"\u001b[39m\u001b[33mwidth\u001b[39m\u001b[33m\"\u001b[39m] = (\n\u001b[32m----> \u001b[39m\u001b[32m9\u001b[39m \u001b[43mmodel\u001b[49m.config.vision_config.encoder_config.image_size[\u001b[32m0\u001b[39m],\n\u001b[32m 10\u001b[39m model.config.vision_config.encoder_config.image_size[\u001b[32m1\u001b[39m],\n\u001b[32m 11\u001b[39m )\n",
149
- "\u001b[31mNameError\u001b[39m: name 'model' is not defined"
150
- ]
151
- }
152
- ],
153
- "source": [
154
- "tokenizer = AutoTokenizer.from_pretrained(\n",
155
- " \"google/paligemma-3b-ft-docvqa-896\", token=hf_token\n",
156
- ")\n",
157
- "image_processor = DonutImageProcessor.from_pretrained(\n",
158
- " \"naver-clova-ix/donut-base-finetuned-docvqa\"\n",
159
- ")\n",
160
- "image_processor.image_seq_length = 4096\n",
161
- "image_processor.size[\"height\"], image_processor.size[\"width\"] = (\n",
162
- " model.config.vision_config.encoder_config.image_size[0],\n",
163
- " model.config.vision_config.encoder_config.image_size[1],\n",
164
- ")"
165
- ]
166
- },
167
- {
168
- "cell_type": "code",
169
- "execution_count": null,
170
- "id": "cb1ff2d6",
171
- "metadata": {},
172
- "outputs": [],
173
- "source": [
174
- "# processor = PaliGemmaProcessor(tokenizer=tokenizer, image_processor=image_processor)\n",
175
- "processor = get_processor(hf_token, 2048, 2048, 4096)"
176
- ]
177
- },
178
- {
179
- "cell_type": "code",
180
- "execution_count": null,
181
- "id": "025fe5c3",
182
- "metadata": {},
183
- "outputs": [
184
- {
185
- "ename": "KeyboardInterrupt",
186
- "evalue": "",
187
- "output_type": "error",
188
- "traceback": [
189
- "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
190
- "\u001b[31mKeyboardInterrupt\u001b[39m Traceback (most recent call last)",
191
- "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[6]\u001b[39m\u001b[32m, line 4\u001b[39m\n\u001b[32m 2\u001b[39m batch_dataset = test_dataset.batch(\u001b[32m2\u001b[39m) \n\u001b[32m 3\u001b[39m iterative_dataset = \u001b[38;5;28miter\u001b[39m(batch_dataset)\n\u001b[32m----> \u001b[39m\u001b[32m4\u001b[39m batch = \u001b[38;5;28;43mnext\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43miterative_dataset\u001b[49m\u001b[43m)\u001b[49m\n",
192
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/datasets/iterable_dataset.py:2538\u001b[39m, in \u001b[36mIterableDataset.__iter__\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m 2535\u001b[39m \u001b[38;5;28;01myield\u001b[39;00m formatter.format_row(pa_table)\n\u001b[32m 2536\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m\n\u001b[32m-> \u001b[39m\u001b[32m2538\u001b[39m \u001b[43m\u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mexample\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mex_iterable\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m 2539\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# no need to format thanks to FormattedExamplesIterable\u001b[39;49;00m\n\u001b[32m 2540\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01myield\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mexample\u001b[49m\n",
193
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/datasets/iterable_dataset.py:1252\u001b[39m, in \u001b[36mMappedExamplesIterable.__iter__\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m 1250\u001b[39m \u001b[38;5;28;01myield\u001b[39;00m key, formatter.format_row(pa_table)\n\u001b[32m 1251\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m1252\u001b[39m \u001b[38;5;28;01myield from\u001b[39;00m \u001b[38;5;28mself\u001b[39m._iter()\n",
194
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/datasets/iterable_dataset.py:1431\u001b[39m, in \u001b[36mMappedExamplesIterable._iter\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m 1425\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m.batched:\n\u001b[32m 1426\u001b[39m outputs = (\n\u001b[32m 1427\u001b[39m (key, transformed_example)\n\u001b[32m 1428\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m key, transformed_batch \u001b[38;5;129;01min\u001b[39;00m outputs\n\u001b[32m 1429\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m transformed_example \u001b[38;5;129;01min\u001b[39;00m _batch_to_examples(transformed_batch)\n\u001b[32m 1430\u001b[39m )\n\u001b[32m-> \u001b[39m\u001b[32m1431\u001b[39m \u001b[43m\u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtransformed_example\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43moutputs\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m 1432\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_state_dict\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01mand\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_state_dict\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mprevious_state\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01mis\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;129;43;01mnot\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m:\u001b[49m\n\u001b[32m 1433\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_state_dict\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mnum_examples_since_previous_state\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m \u001b[49m\u001b[43m+\u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m1\u001b[39;49m\n",
195
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/datasets/iterable_dataset.py:1428\u001b[39m, in \u001b[36m<genexpr>\u001b[39m\u001b[34m(.0)\u001b[39m\n\u001b[32m 1424\u001b[39m outputs = iter_outputs()\n\u001b[32m 1425\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m.batched:\n\u001b[32m 1426\u001b[39m outputs = \u001b[43m(\u001b[49m\n\u001b[32m 1427\u001b[39m \u001b[43m \u001b[49m\u001b[43m(\u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtransformed_example\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m-> \u001b[39m\u001b[32m1428\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mtransformed_batch\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43moutputs\u001b[49m\n\u001b[32m 1429\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mtransformed_example\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43m_batch_to_examples\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtransformed_batch\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 1430\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 1431\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m key, transformed_example \u001b[38;5;129;01min\u001b[39;00m outputs:\n\u001b[32m 1432\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m._state_dict \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;28mself\u001b[39m._state_dict[\u001b[33m\"\u001b[39m\u001b[33mprevious_state\u001b[39m\u001b[33m\"\u001b[39m] \u001b[38;5;129;01mis\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m:\n",
196
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/datasets/iterable_dataset.py:1412\u001b[39m, in \u001b[36mMappedExamplesIterable._iter.<locals>.iter_outputs\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m 1410\u001b[39m \u001b[38;5;28mself\u001b[39m._state_dict[\u001b[33m\"\u001b[39m\u001b[33mnum_examples_since_previous_state\u001b[39m\u001b[33m\"\u001b[39m] = \u001b[32m0\u001b[39m\n\u001b[32m 1411\u001b[39m \u001b[38;5;28mself\u001b[39m._state_dict[\u001b[33m\"\u001b[39m\u001b[33mprevious_state_example_idx\u001b[39m\u001b[33m\"\u001b[39m] = current_idx\n\u001b[32m-> \u001b[39m\u001b[32m1412\u001b[39m \u001b[43m\u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mi\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mkey_example\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43minputs_iterator\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m 1413\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_state_dict\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m 1414\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;129;43;01mnot\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mbatched\u001b[49m\u001b[43m:\u001b[49m\n",
197
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/datasets/iterable_dataset.py:1274\u001b[39m, in \u001b[36mMappedExamplesIterable._iter.<locals>.iter_batched_inputs\u001b[39m\u001b[34m()\u001b[39m\n\u001b[32m 1272\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34miter_batched_inputs\u001b[39m():\n\u001b[32m 1273\u001b[39m \u001b[38;5;28;01mnonlocal\u001b[39;00m current_idx\n\u001b[32m-> \u001b[39m\u001b[32m1274\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mexample\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43miterator\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m 1275\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# If `batched`, first build the batch, if `batch_size` is None or <=0, then the batch is the whole dataset\u001b[39;49;00m\n\u001b[32m 1276\u001b[39m \u001b[43m \u001b[49m\u001b[43miterator_batch\u001b[49m\u001b[43m \u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 1277\u001b[39m \u001b[43m \u001b[49m\u001b[43miterator\u001b[49m\n\u001b[32m 1278\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mbatch_size\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01mis\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mNone\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;129;43;01mor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mbatch_size\u001b[49m\u001b[43m \u001b[49m\u001b[43m<\u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m0\u001b[39;49m\n\u001b[32m 1279\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01melse\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mislice\u001b[49m\u001b[43m(\u001b[49m\u001b[43miterator\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mbatch_size\u001b[49m\u001b[43m \u001b[49m\u001b[43m-\u001b[49m\u001b[43m \u001b[49m\u001b[32;43m1\u001b[39;49m\u001b[43m)\u001b[49m\n\u001b[32m 1280\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 1281\u001b[39m \u001b[43m \u001b[49m\u001b[43mkey_examples_list\u001b[49m\u001b[43m \u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[43m[\u001b[49m\u001b[43m(\u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mexample\u001b[49m\u001b[43m)\u001b[49m\u001b[43m]\u001b[49m\u001b[43m \u001b[49m\u001b[43m+\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mlist\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43miterator_batch\u001b[49m\u001b[43m)\u001b[49m\n",
198
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/datasets/iterable_dataset.py:2055\u001b[39m, in \u001b[36mFormattedExamplesIterable.__iter__\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m 2048\u001b[39m formatter = get_formatter(\n\u001b[32m 2049\u001b[39m \u001b[38;5;28mself\u001b[39m.formatting.format_type,\n\u001b[32m 2050\u001b[39m features=\u001b[38;5;28mself\u001b[39m._features \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28mself\u001b[39m.ex_iterable.is_typed \u001b[38;5;28;01melse\u001b[39;00m \u001b[38;5;28;01mNone\u001b[39;00m,\n\u001b[32m 2051\u001b[39m token_per_repo_id=\u001b[38;5;28mself\u001b[39m.token_per_repo_id,\n\u001b[32m 2052\u001b[39m )\n\u001b[32m 2053\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m.ex_iterable.iter_arrow:\n\u001b[32m 2054\u001b[39m \u001b[38;5;66;03m# feature casting (inc column addition) handled within self._iter_arrow()\u001b[39;00m\n\u001b[32m-> \u001b[39m\u001b[32m2055\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mpa_table\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43m_iter_arrow\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m 2056\u001b[39m \u001b[43m \u001b[49m\u001b[43mbatch\u001b[49m\u001b[43m \u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[43mformatter\u001b[49m\u001b[43m.\u001b[49m\u001b[43mformat_batch\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpa_table\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 2057\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mexample\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43m_batch_to_examples\u001b[49m\u001b[43m(\u001b[49m\u001b[43mbatch\u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n",
199
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/datasets/iterable_dataset.py:2078\u001b[39m, in \u001b[36mFormattedExamplesIterable._iter_arrow\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m 2076\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;129;01mnot\u001b[39;00m \u001b[38;5;28mself\u001b[39m.features:\n\u001b[32m 2077\u001b[39m \u001b[38;5;28;01myield from\u001b[39;00m \u001b[38;5;28mself\u001b[39m.ex_iterable._iter_arrow()\n\u001b[32m-> \u001b[39m\u001b[32m2078\u001b[39m \u001b[43m\u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mpa_table\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mex_iterable\u001b[49m\u001b[43m.\u001b[49m\u001b[43m_iter_arrow\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m 2079\u001b[39m \u001b[43m \u001b[49m\u001b[43mcolumns\u001b[49m\u001b[43m \u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mset\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mpa_table\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcolumn_names\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 2080\u001b[39m \u001b[43m \u001b[49m\u001b[43mschema\u001b[49m\u001b[43m \u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mfeatures\u001b[49m\u001b[43m.\u001b[49m\u001b[43marrow_schema\u001b[49m\n",
200
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/datasets/iterable_dataset.py:378\u001b[39m, in \u001b[36mArrowExamplesIterable._iter_arrow\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m 376\u001b[39m shard_example_idx_start = \u001b[38;5;28mself\u001b[39m._state_dict[\u001b[33m\"\u001b[39m\u001b[33mshard_example_idx\u001b[39m\u001b[33m\"\u001b[39m] \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m._state_dict \u001b[38;5;28;01melse\u001b[39;00m \u001b[32m0\u001b[39m\n\u001b[32m 377\u001b[39m shard_example_idx = \u001b[32m0\u001b[39m\n\u001b[32m--> \u001b[39m\u001b[32m378\u001b[39m \u001b[43m\u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mkey\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mpa_table\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mgenerate_tables_fn\u001b[49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mgen_kwags\u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m 379\u001b[39m \u001b[43m \u001b[49m\u001b[43mshard_example_idx\u001b[49m\u001b[43m \u001b[49m\u001b[43m+\u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43mlen\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43mpa_table\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 380\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mshard_example_idx\u001b[49m\u001b[43m \u001b[49m\u001b[43m<\u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[43mshard_example_idx_start\u001b[49m\u001b[43m:\u001b[49m\n",
201
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/datasets/packaged_modules/parquet/parquet.py:168\u001b[39m, in \u001b[36mParquet._generate_tables\u001b[39m\u001b[34m(self, files)\u001b[39m\n\u001b[32m 166\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m parquet_fragment.row_groups:\n\u001b[32m 167\u001b[39m batch_size = \u001b[38;5;28mself\u001b[39m.config.batch_size \u001b[38;5;129;01mor\u001b[39;00m parquet_fragment.row_groups[\u001b[32m0\u001b[39m].num_rows\n\u001b[32m--> \u001b[39m\u001b[32m168\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mbatch_idx\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mrecord_batch\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;28;43menumerate\u001b[39;49m\u001b[43m(\u001b[49m\n\u001b[32m 169\u001b[39m \u001b[43m \u001b[49m\u001b[43mparquet_fragment\u001b[49m\u001b[43m.\u001b[49m\u001b[43mto_batches\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m 170\u001b[39m \u001b[43m \u001b[49m\u001b[43mbatch_size\u001b[49m\u001b[43m=\u001b[49m\u001b[43mbatch_size\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 171\u001b[39m \u001b[43m \u001b[49m\u001b[43mcolumns\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m.\u001b[49m\u001b[43mcolumns\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 172\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;28;43mfilter\u001b[39;49m\u001b[43m=\u001b[49m\u001b[43mfilter_expr\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m 173\u001b[39m \u001b[43m \u001b[49m\u001b[43mbatch_readahead\u001b[49m\u001b[43m=\u001b[49m\u001b[32;43m0\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[32m 174\u001b[39m \u001b[43m \u001b[49m\u001b[43mfragment_readahead\u001b[49m\u001b[43m=\u001b[49m\u001b[32;43m0\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[32m 175\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 176\u001b[39m \u001b[43m \u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m 177\u001b[39m \u001b[43m \u001b[49m\u001b[43mpa_table\u001b[49m\u001b[43m \u001b[49m\u001b[43m=\u001b[49m\u001b[43m \u001b[49m\u001b[43mpa\u001b[49m\u001b[43m.\u001b[49m\u001b[43mTable\u001b[49m\u001b[43m.\u001b[49m\u001b[43mfrom_batches\u001b[49m\u001b[43m(\u001b[49m\u001b[43m[\u001b[49m\u001b[43mrecord_batch\u001b[49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 178\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# Uncomment for debugging (will print the Arrow table size and elements)\u001b[39;49;00m\n\u001b[32m 179\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# logger.warning(f\"pa_table: {pa_table} num rows: {pa_table.num_rows}\")\u001b[39;49;00m\n\u001b[32m 180\u001b[39m \u001b[43m \u001b[49m\u001b[38;5;66;43;03m# logger.warning('\\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))\u001b[39;49;00m\n",
202
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/pyarrow/_dataset.pyx:3934\u001b[39m, in \u001b[36m_iterator\u001b[39m\u001b[34m()\u001b[39m\n",
203
- "\u001b[36mFile \u001b[39m\u001b[32m~/miniconda3/envs/divedoc-plateform-env/lib/python3.12/site-packages/pyarrow/_dataset.pyx:3527\u001b[39m, in \u001b[36mpyarrow._dataset.TaggedRecordBatchIterator.__next__\u001b[39m\u001b[34m()\u001b[39m\n",
204
- "\u001b[36mFile \u001b[39m\u001b[32m<string>:1\u001b[39m, in \u001b[36m<lambda>\u001b[39m\u001b[34m(_cls, record_batch, fragment)\u001b[39m\n",
205
- "\u001b[31mKeyboardInterrupt\u001b[39m: "
206
- ]
207
- }
208
- ],
209
- "source": [
210
- "test_dataset = load_dataset(\n",
211
- " \"pixparse/docvqa-single-page-questions\", split=\"test\", streaming=True\n",
212
- ")\n",
213
- "batch_dataset = test_dataset.batch(2)\n",
214
- "iterative_dataset = iter(batch_dataset)\n",
215
- "batch = next(iterative_dataset)"
216
- ]
217
- },
218
- {
219
- "cell_type": "code",
220
- "execution_count": null,
221
- "id": "69181548",
222
- "metadata": {},
223
- "outputs": [
224
- {
225
- "name": "stderr",
226
- "output_type": "stream",
227
- "text": [
228
- "You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `<image>` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens.\n"
229
- ]
230
- }
231
- ],
232
- "source": [
233
- "# preprocessing\n",
234
- "imgs = []\n",
235
- "for i in batch[\"image\"]:\n",
236
- " imgs.append(i.convert(\"RGB\"))\n",
237
- "txt = batch[\"question\"]\n",
238
- "model_inputs = processor(text=txt, images=imgs, return_tensors=\"pt\", padding=True)\n",
239
- "input_len = model_inputs[\"input_ids\"].shape[-1]"
240
- ]
241
- },
242
- {
243
- "cell_type": "code",
244
- "execution_count": null,
245
- "id": "14c88fc6",
246
- "metadata": {},
247
- "outputs": [
248
- {
249
- "name": "stdout",
250
- "output_type": "stream",
251
- "text": [
252
- "DIVE-Doc is a 2.5B end-to-end VLM!\n"
253
- ]
254
- }
255
- ],
256
- "source": [
257
- "original_text = \"DIVE-Doc is a 2.5B end-to-end VLM!\"\n",
258
- "\n",
259
- "encoded = processor.tokenizer(original_text, return_tensors=\"pt\", padding=True)\n",
260
- "input_ids = encoded[\"input_ids\"][0]\n",
261
- "\n",
262
- "decoded_text = processor.decode(input_ids, skip_special_tokens=True)\n",
263
- "\n",
264
- "print(decoded_text)"
265
- ]
266
- },
267
- {
268
- "cell_type": "code",
269
- "execution_count": null,
270
- "id": "e4ecd864",
271
- "metadata": {},
272
- "outputs": [
273
- {
274
- "data": {
275
- "text/plain": [
276
- "torch.Size([2, 4103])"
277
- ]
278
- },
279
- "execution_count": 11,
280
- "metadata": {},
281
- "output_type": "execute_result"
282
- }
283
- ],
284
- "source": [
285
- "model_inputs[\"attention_mask\"].shape"
286
- ]
287
- },
288
- {
289
- "cell_type": "code",
290
- "execution_count": null,
291
- "id": "30695c75",
292
- "metadata": {},
293
- "outputs": [],
294
- "source": [
295
- "import torch\n",
296
- "\n",
297
- "assert isinstance(model_inputs[\"input_ids\"], torch.Tensor)"
298
- ]
299
- },
300
- {
301
- "cell_type": "code",
302
- "execution_count": null,
303
- "id": "3fae4d87",
304
- "metadata": {},
305
- "outputs": [],
306
- "source": [
307
- "from transformers import BatchFeature\n",
308
- "\n",
309
- "assert isinstance(model_inputs, (dict, BatchFeature))"
310
- ]
311
- },
312
- {
313
- "cell_type": "code",
314
- "execution_count": null,
315
- "id": "f77a98c1",
316
- "metadata": {},
317
- "outputs": [
318
- {
319
- "data": {
320
- "text/plain": [
321
- "2048"
322
- ]
323
- },
324
- "execution_count": 14,
325
- "metadata": {},
326
- "output_type": "execute_result"
327
- }
328
- ],
329
- "source": [
330
- "processor.image_processor.size[\"height\"]"
331
- ]
332
- },
333
- {
334
- "cell_type": "code",
335
- "execution_count": null,
336
- "id": "31f67274",
337
- "metadata": {},
338
- "outputs": [
339
- {
340
- "data": {
341
- "text/plain": [
342
- "'<unused62>[@BOS@]<unused4><unused12><unused20><unused20><unused2><unused36><unused68><unused70>'"
343
- ]
344
- },
345
- "execution_count": 33,
346
- "metadata": {},
347
- "output_type": "execute_result"
348
- }
349
- ],
350
- "source": [
351
- "import random\n",
352
- "\n",
353
- "random_list = [random.randint(1, 100) for _ in range(10)]\n",
354
- "processor.decode(random_list, skip_special_tokens=True)"
355
- ]
356
- },
357
- {
358
- "cell_type": "code",
359
- "execution_count": null,
360
- "id": "cfb8c719",
361
- "metadata": {},
362
- "outputs": [
363
- {
364
- "data": {
365
- "text/plain": [
366
- "{'pixel_values': [array([[[-1., -1., -1., ..., -1., -1., -1.],\n",
367
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
368
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
369
- " ...,\n",
370
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
371
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
372
- " [-1., -1., -1., ..., -1., -1., -1.]],\n",
373
- "\n",
374
- " [[-1., -1., -1., ..., -1., -1., -1.],\n",
375
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
376
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
377
- " ...,\n",
378
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
379
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
380
- " [-1., -1., -1., ..., -1., -1., -1.]],\n",
381
- "\n",
382
- " [[-1., -1., -1., ..., -1., -1., -1.],\n",
383
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
384
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
385
- " ...,\n",
386
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
387
- " [-1., -1., -1., ..., -1., -1., -1.],\n",
388
- " [-1., -1., -1., ..., -1., -1., -1.]]],\n",
389
- " shape=(3, 2560, 1920), dtype=float32)]}"
390
- ]
391
- },
392
- "execution_count": 7,
393
- "metadata": {},
394
- "output_type": "execute_result"
395
- }
396
- ],
397
- "source": [
398
- "imgs = []\n",
399
- "for i in batch[\"image\"]:\n",
400
- " imgs.append(i.convert(\"RGB\"))\n",
401
- "processor.image_processor(images=imgs[0])"
402
- ]
403
- },
404
- {
405
- "cell_type": "code",
406
- "execution_count": null,
407
- "id": "c23a5794",
408
- "metadata": {},
409
- "outputs": [
410
- {
411
- "data": {
412
- "text/plain": [
413
- "DIVEdocConfig {\n",
414
- " \"_attn_implementation_autoset\": true,\n",
415
- " \"_vocab_size\": 257152,\n",
416
- " \"architectures\": [\n",
417
- " \"DIVEdoc\"\n",
418
- " ],\n",
419
- " \"auto_map\": {\n",
420
- " \"AutoConfig\": \"JayRay5/DIVE-Doc-FRD--configuration_divedoc.DIVEdocConfig\",\n",
421
- " \"AutoModelForCausalLM\": \"JayRay5/DIVE-Doc-FRD--modeling_divedoc.DIVEdoc\"\n",
422
- " },\n",
423
- " \"bos_token_id\": 2,\n",
424
- " \"eos_token_id\": 1,\n",
425
- " \"hidden_size\": 2048,\n",
426
- " \"image_token_index\": 257152,\n",
427
- " \"model_type\": \"DIVEdoc\",\n",
428
- " \"pad_token_id\": 0,\n",
429
- " \"projection_dim\": 2048,\n",
430
- " \"text_config\": {\n",
431
- " \"attention_bias\": false,\n",
432
- " \"attention_dropout\": 0.0,\n",
433
- " \"head_dim\": 256,\n",
434
- " \"hidden_act\": \"gelu_pytorch_tanh\",\n",
435
- " \"hidden_activation\": null,\n",
436
- " \"hidden_size\": 2048,\n",
437
- " \"initializer_range\": 0.02,\n",
438
- " \"intermediate_size\": 16384,\n",
439
- " \"max_position_embeddings\": 8192,\n",
440
- " \"model_type\": \"gemma\",\n",
441
- " \"num_attention_heads\": 8,\n",
442
- " \"num_hidden_layers\": 18,\n",
443
- " \"num_image_tokens\": 4096,\n",
444
- " \"num_key_value_heads\": 1,\n",
445
- " \"rms_norm_eps\": 1e-06,\n",
446
- " \"rope_theta\": 10000.0,\n",
447
- " \"torch_dtype\": \"float32\",\n",
448
- " \"use_cache\": true,\n",
449
- " \"vocab_size\": 257216\n",
450
- " },\n",
451
- " \"torch_dtype\": \"float32\",\n",
452
- " \"transformers_version\": \"4.51.0\",\n",
453
- " \"vision_config\": {\n",
454
- " \"_attn_implementation_autoset\": true,\n",
455
- " \"encoder_config\": {\n",
456
- " \"_attn_implementation_autoset\": true,\n",
457
- " \"_name_or_path\": \"\",\n",
458
- " \"add_cross_attention\": false,\n",
459
- " \"architectures\": null,\n",
460
- " \"attention_probs_dropout_prob\": 0.0,\n",
461
- " \"bad_words_ids\": null,\n",
462
- " \"begin_suppress_tokens\": null,\n",
463
- " \"bos_token_id\": null,\n",
464
- " \"chunk_size_feed_forward\": 0,\n",
465
- " \"cross_attention_hidden_size\": null,\n",
466
- " \"decoder_start_token_id\": null,\n",
467
- " \"depths\": [\n",
468
- " 2,\n",
469
- " 2,\n",
470
- " 14,\n",
471
- " 2\n",
472
- " ],\n",
473
- " \"diversity_penalty\": 0.0,\n",
474
- " \"do_sample\": false,\n",
475
- " \"drop_path_rate\": 0.1,\n",
476
- " \"early_stopping\": false,\n",
477
- " \"embed_dim\": 128,\n",
478
- " \"encoder_no_repeat_ngram_size\": 0,\n",
479
- " \"eos_token_id\": null,\n",
480
- " \"exponential_decay_length_penalty\": null,\n",
481
- " \"finetuning_task\": null,\n",
482
- " \"forced_bos_token_id\": null,\n",
483
- " \"forced_eos_token_id\": null,\n",
484
- " \"hidden_act\": \"gelu\",\n",
485
- " \"hidden_dropout_prob\": 0.0,\n",
486
- " \"hidden_size\": 1024,\n",
487
- " \"id2label\": {\n",
488
- " \"0\": \"LABEL_0\",\n",
489
- " \"1\": \"LABEL_1\"\n",
490
- " },\n",
491
- " \"image_size\": [\n",
492
- " 2048,\n",
493
- " 2048\n",
494
- " ],\n",
495
- " \"initializer_range\": 0.02,\n",
496
- " \"is_decoder\": false,\n",
497
- " \"is_encoder_decoder\": false,\n",
498
- " \"label2id\": {\n",
499
- " \"LABEL_0\": 0,\n",
500
- " \"LABEL_1\": 1\n",
501
- " },\n",
502
- " \"layer_norm_eps\": 1e-05,\n",
503
- " \"length_penalty\": 1.0,\n",
504
- " \"max_length\": 20,\n",
505
- " \"min_length\": 0,\n",
506
- " \"mlp_ratio\": 4.0,\n",
507
- " \"model_type\": \"donut-swin\",\n",
508
- " \"no_repeat_ngram_size\": 0,\n",
509
- " \"num_beam_groups\": 1,\n",
510
- " \"num_beams\": 1,\n",
511
- " \"num_channels\": 3,\n",
512
- " \"num_heads\": [\n",
513
- " 4,\n",
514
- " 8,\n",
515
- " 16,\n",
516
- " 32\n",
517
- " ],\n",
518
- " \"num_layers\": 4,\n",
519
- " \"num_return_sequences\": 1,\n",
520
- " \"output_attentions\": false,\n",
521
- " \"output_hidden_states\": false,\n",
522
- " \"output_scores\": false,\n",
523
- " \"pad_token_id\": null,\n",
524
- " \"patch_size\": 4,\n",
525
- " \"path_norm\": true,\n",
526
- " \"prefix\": null,\n",
527
- " \"problem_type\": null,\n",
528
- " \"pruned_heads\": {},\n",
529
- " \"qkv_bias\": true,\n",
530
- " \"remove_invalid_values\": false,\n",
531
- " \"repetition_penalty\": 1.0,\n",
532
- " \"return_dict\": true,\n",
533
- " \"return_dict_in_generate\": false,\n",
534
- " \"sep_token_id\": null,\n",
535
- " \"suppress_tokens\": null,\n",
536
- " \"task_specific_params\": null,\n",
537
- " \"temperature\": 1.0,\n",
538
- " \"tf_legacy_loss\": false,\n",
539
- " \"tie_encoder_decoder\": false,\n",
540
- " \"tie_word_embeddings\": true,\n",
541
- " \"tokenizer_class\": null,\n",
542
- " \"top_k\": 50,\n",
543
- " \"top_p\": 1.0,\n",
544
- " \"torch_dtype\": null,\n",
545
- " \"torchscript\": false,\n",
546
- " \"typical_p\": 1.0,\n",
547
- " \"use_absolute_embeddings\": false,\n",
548
- " \"use_bfloat16\": false,\n",
549
- " \"window_size\": 10\n",
550
- " },\n",
551
- " \"model_type\": \"swinpam\",\n",
552
- " \"pam_config\": {\n",
553
- " \"_attn_implementation_autoset\": false,\n",
554
- " \"_name_or_path\": \"\",\n",
555
- " \"add_cross_attention\": false,\n",
556
- " \"architectures\": null,\n",
557
- " \"bad_words_ids\": null,\n",
558
- " \"begin_suppress_tokens\": null,\n",
559
- " \"bos_token_id\": null,\n",
560
- " \"chunk_size_feed_forward\": 0,\n",
561
- " \"cross_attention_hidden_size\": null,\n",
562
- " \"decoder_start_token_id\": null,\n",
563
- " \"diversity_penalty\": 0.0,\n",
564
- " \"do_sample\": false,\n",
565
- " \"early_stopping\": false,\n",
566
- " \"encoder_no_repeat_ngram_size\": 0,\n",
567
- " \"eos_token_id\": null,\n",
568
- " \"exponential_decay_length_penalty\": null,\n",
569
- " \"finetuning_task\": null,\n",
570
- " \"forced_bos_token_id\": null,\n",
571
- " \"forced_eos_token_id\": null,\n",
572
- " \"id2label\": {\n",
573
- " \"0\": \"LABEL_0\",\n",
574
- " \"1\": \"LABEL_1\"\n",
575
- " },\n",
576
- " \"is_decoder\": false,\n",
577
- " \"is_encoder_decoder\": false,\n",
578
- " \"label2id\": {\n",
579
- " \"LABEL_0\": 0,\n",
580
- " \"LABEL_1\": 1\n",
581
- " },\n",
582
- " \"length_penalty\": 1.0,\n",
583
- " \"max_length\": 20,\n",
584
- " \"min_length\": 0,\n",
585
- " \"model_type\": \"pam\",\n",
586
- " \"no_repeat_ngram_size\": 0,\n",
587
- " \"num_beam_groups\": 1,\n",
588
- " \"num_beams\": 1,\n",
589
- " \"num_return_sequences\": 1,\n",
590
- " \"output_attentions\": false,\n",
591
- " \"output_hidden_states\": false,\n",
592
- " \"output_scores\": false,\n",
593
- " \"pad_token_id\": null,\n",
594
- " \"prefix\": null,\n",
595
- " \"problem_type\": null,\n",
596
- " \"pruned_heads\": {},\n",
597
- " \"remove_invalid_values\": false,\n",
598
- " \"repetition_penalty\": 1.0,\n",
599
- " \"return_dict\": true,\n",
600
- " \"return_dict_in_generate\": false,\n",
601
- " \"sep_token_id\": null,\n",
602
- " \"sequence_mapping_layer_type\": null,\n",
603
- " \"student_embedding_dim\": 1024,\n",
604
- " \"student_fmap_dim\": [\n",
605
- " 64,\n",
606
- " 64\n",
607
- " ],\n",
608
- " \"suppress_tokens\": null,\n",
609
- " \"task_specific_params\": null,\n",
610
- " \"teacher_embedding_dim\": 1152,\n",
611
- " \"teacher_fmap_dim\": [\n",
612
- " 64,\n",
613
- " 64\n",
614
- " ],\n",
615
- " \"temperature\": 1.0,\n",
616
- " \"tf_legacy_loss\": false,\n",
617
- " \"tie_encoder_decoder\": false,\n",
618
- " \"tie_word_embeddings\": true,\n",
619
- " \"tokenizer_class\": null,\n",
620
- " \"top_k\": 50,\n",
621
- " \"top_p\": 1.0,\n",
622
- " \"torch_dtype\": null,\n",
623
- " \"torchscript\": false,\n",
624
- " \"typical_p\": 1.0,\n",
625
- " \"use_bfloat16\": false\n",
626
- " },\n",
627
- " \"projection_dim\": 2048,\n",
628
- " \"torch_dtype\": \"float32\"\n",
629
- " }\n",
630
- "}"
631
- ]
632
- },
633
- "execution_count": 19,
634
- "metadata": {},
635
- "output_type": "execute_result"
636
- }
637
- ],
638
- "source": [
639
- "model.config"
640
- ]
641
- }
642
- ],
643
- "metadata": {
644
- "kernelspec": {
645
- "display_name": "divedoc-platform-env",
646
- "language": "python",
647
- "name": "python3"
648
- },
649
- "language_info": {
650
- "codemirror_mode": {
651
- "name": "ipython",
652
- "version": 3
653
- },
654
- "file_extension": ".py",
655
- "mimetype": "text/x-python",
656
- "name": "python",
657
- "nbconvert_exporter": "python",
658
- "pygments_lexer": "ipython3",
659
- "version": "3.12.12"
660
- }
661
- },
662
- "nbformat": 4,
663
- "nbformat_minor": 5
664
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/results/model_docvqa_test_results.json DELETED
The diff for this file is too large to render. See raw diff