TienAnh commited on
Commit
0d6eca3
·
verified ·
1 Parent(s): d31f0c5

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +143 -0
README.md ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - vi
5
+ base_model:
6
+ - 5CD-AI/Vintern-1B-v3_5
7
+ - OpenGVLab/InternVL3-1B
8
+ pipeline_tag: image-text-to-text
9
+ library_name: transformers
10
+ tags:
11
+ - generated_from_trainer
12
+ ---
13
+ ### Training hyperparameters
14
+
15
+ The following hyperparameters were used during training:
16
+ - learning_rate: 4e-05
17
+ - train_batch_size: 8
18
+ - eval_batch_size: 8
19
+ - seed: 42
20
+ - distributed_type: multi-GPU
21
+ - num_devices: 4
22
+ - gradient_accumulation_steps: 2
23
+ - total_train_batch_size: 64
24
+ - total_eval_batch_size: 32
25
+ - optimizer: Use OptimizerNames.ADAMW_TORCH with betas=(0.9,0.999) and epsilon=1e-08 and optimizer_args=No additional optimizer arguments
26
+ - lr_scheduler_type: cosine
27
+ - lr_scheduler_warmup_ratio: 0.03
28
+ - num_epochs: 1.0
29
+
30
+ ### Framework versions
31
+
32
+ - Transformers 4.47.0
33
+ - Pytorch 2.5.1+cu124
34
+ - Datasets 3.5.0
35
+ - Tokenizers 0.21.0
36
+
37
+ ```python
38
+ import numpy as np
39
+ import torch
40
+ import torchvision.transforms as T
41
+ # from decord import VideoReader, cpu
42
+ from PIL import Image
43
+ from torchvision.transforms.functional import InterpolationMode
44
+ from transformers import AutoModel, AutoTokenizer
45
+
46
+ IMAGENET_MEAN = (0.485, 0.456, 0.406)
47
+ IMAGENET_STD = (0.229, 0.224, 0.225)
48
+
49
+ def build_transform(input_size):
50
+ MEAN, STD = IMAGENET_MEAN, IMAGENET_STD
51
+ transform = T.Compose([
52
+ T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img),
53
+ T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC),
54
+ T.ToTensor(),
55
+ T.Normalize(mean=MEAN, std=STD)
56
+ ])
57
+ return transform
58
+
59
+ def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size):
60
+ best_ratio_diff = float('inf')
61
+ best_ratio = (1, 1)
62
+ area = width * height
63
+ for ratio in target_ratios:
64
+ target_aspect_ratio = ratio[0] / ratio[1]
65
+ ratio_diff = abs(aspect_ratio - target_aspect_ratio)
66
+ if ratio_diff < best_ratio_diff:
67
+ best_ratio_diff = ratio_diff
68
+ best_ratio = ratio
69
+ elif ratio_diff == best_ratio_diff:
70
+ if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]:
71
+ best_ratio = ratio
72
+ return best_ratio
73
+
74
+ def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False):
75
+ orig_width, orig_height = image.size
76
+ aspect_ratio = orig_width / orig_height
77
+
78
+ # calculate the existing image aspect ratio
79
+ target_ratios = set(
80
+ (i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) for j in range(1, n + 1) if
81
+ i * j <= max_num and i * j >= min_num)
82
+ target_ratios = sorted(target_ratios, key=lambda x: x[0] * x[1])
83
+
84
+ # find the closest aspect ratio to the target
85
+ target_aspect_ratio = find_closest_aspect_ratio(
86
+ aspect_ratio, target_ratios, orig_width, orig_height, image_size)
87
+
88
+ # calculate the target width and height
89
+ target_width = image_size * target_aspect_ratio[0]
90
+ target_height = image_size * target_aspect_ratio[1]
91
+ blocks = target_aspect_ratio[0] * target_aspect_ratio[1]
92
+
93
+ # resize the image
94
+ resized_img = image.resize((target_width, target_height))
95
+ processed_images = []
96
+ for i in range(blocks):
97
+ box = (
98
+ (i % (target_width // image_size)) * image_size,
99
+ (i // (target_width // image_size)) * image_size,
100
+ ((i % (target_width // image_size)) + 1) * image_size,
101
+ ((i // (target_width // image_size)) + 1) * image_size
102
+ )
103
+ # split the image
104
+ split_img = resized_img.crop(box)
105
+ processed_images.append(split_img)
106
+ assert len(processed_images) == blocks
107
+ if use_thumbnail and len(processed_images) != 1:
108
+ thumbnail_img = image.resize((image_size, image_size))
109
+ processed_images.append(thumbnail_img)
110
+ return processed_images
111
+
112
+ def load_image(image_file, input_size=448, max_num=12):
113
+ image = Image.open(image_file).convert('RGB')
114
+ transform = build_transform(input_size=input_size)
115
+ images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num)
116
+ pixel_values = [transform(image) for image in images]
117
+ pixel_values = torch.stack(pixel_values)
118
+ return pixel_values
119
+
120
+ model = AutoModel.from_pretrained(
121
+ "TienAnh/Finetune_OCR_1B",
122
+ torch_dtype=torch.bfloat16,
123
+ low_cpu_mem_usage=True,
124
+ trust_remote_code=True,
125
+ use_flash_attn=False,
126
+ ).eval().cuda()
127
+
128
+ tokenizer = AutoTokenizer.from_pretrained("TienAnh/Finetune_OCR_1B", trust_remote_code=True, use_fast=False)
129
+
130
+ test_image = 'test-image.jpg'
131
+
132
+ pixel_values = load_image(test_image, max_num=6).to(torch.bfloat16).cuda()
133
+ generation_config = dict(max_new_tokens= 1024, do_sample=False, num_beams = 3, repetition_penalty=2.5)
134
+
135
+ question = '<image>\nTrích xuất thông tin chính trong ảnh và trả về dạng markdown.'
136
+
137
+ response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=None, return_history=True)
138
+ print(f'User: {question}\nAssistant: {response}')
139
+
140
+ #question = "Câu hỏi khác ......"
141
+ #response, history = model.chat(tokenizer, pixel_values, question, generation_config, history=history, return_history=True)
142
+ #print(f'User: {question}\nAssistant: {response}')
143
+ ```