pdich2085 commited on
Commit
feb5784
·
1 Parent(s): 750f7de

Upload 8 files

Browse files
README.md CHANGED
@@ -1,3 +1,94 @@
1
  ---
2
- license: apache-2.0
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ tags:
3
+ - image-to-text
4
+ - image-captioning
5
+ - endpoints-template
6
+ license: bsd-3-clause
7
+ library_name: generic
8
  ---
9
+
10
+ # Fork of [Salesforce/blip-image-captioning-large](https://huggingface.co/Salesforce/blip-image-captioning-large) for a `image-captioning` task on 🤗Inference endpoint.
11
+
12
+ This repository implements a `custom` task for `image-captioning` for 🤗 Inference Endpoints. The code for the customized pipeline is in the [pipeline.py](https://huggingface.co/florentgbelidji/blip_captioning/blob/main/pipeline.py).
13
+ To use deploy this model a an Inference Endpoint you have to select `Custom` as task to use the `pipeline.py` file. -> _double check if it is selected_
14
+ ### expected Request payload
15
+ ```json
16
+ {
17
+ "image": "/9j/4AAQSkZJRgA.....", #encoded image
18
+ "text": "a photography of a"
19
+ }
20
+ ```
21
+ below is an example on how to run a request using Python and `requests`.
22
+ ## Run Request
23
+ 1. Use any online image.
24
+ ```bash
25
+ !wget https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg
26
+ ```
27
+ 2.run request
28
+
29
+ ```python
30
+ import json
31
+ from typing import List
32
+ import requests as r
33
+ import base64
34
+
35
+ with open("/content/demo.jpg", "rb") as image_file:
36
+ encoded_string = base64.b64encode(image_file.read()).decode()
37
+
38
+ ENDPOINT_URL = ""
39
+ HF_TOKEN = ""
40
+
41
+ def query(payload):
42
+ response = requests.post(API_URL, headers=headers, json=payload)
43
+ return response.json()
44
+
45
+
46
+ output = query({
47
+ "inputs": {
48
+ "images": [encoded_string], # using the base64 encoded string
49
+ "texts": ["a photography of"] # Optional, based on your current class logic
50
+ }
51
+ })
52
+ print(output)
53
+ ```
54
+
55
+ Example parameters depending on the decoding strategy:
56
+
57
+ 1. Beam search
58
+
59
+ ```
60
+ "parameters": {
61
+ "num_beams":5,
62
+ "max_length":20
63
+ }
64
+ ```
65
+
66
+ 2. Nucleus sampling
67
+
68
+ ```
69
+ "parameters": {
70
+ "num_beams":1,
71
+ "max_length":20,
72
+ "do_sample": True,
73
+ "top_k":50,
74
+ "top_p":0.95
75
+ }
76
+ ```
77
+
78
+ 3. Contrastive search
79
+
80
+ ```
81
+ "parameters": {
82
+ "penalty_alpha":0.6,
83
+ "top_k":4
84
+ "max_length":512
85
+ }
86
+ ```
87
+
88
+ See [generate()](https://huggingface.co/docs/transformers/v4.25.1/en/main_classes/text_generation#transformers.GenerationMixin.generate) doc for additional detail
89
+
90
+
91
+ expected output
92
+ ```python
93
+ {'captions': ['a photography of a woman and her dog on the beach']}
94
+ ```
config.json ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_commit_hash": null,
3
+ "architectures": [
4
+ "BlipForConditionalGeneration"
5
+ ],
6
+ "image_text_hidden_size": 256,
7
+ "initializer_factor": 1.0,
8
+ "logit_scale_init_value": 2.6592,
9
+ "model_type": "blip",
10
+ "projection_dim": 512,
11
+ "text_config": {
12
+ "_name_or_path": "",
13
+ "add_cross_attention": false,
14
+ "architectures": null,
15
+ "attention_probs_dropout_prob": 0.0,
16
+ "bad_words_ids": null,
17
+ "begin_suppress_tokens": null,
18
+ "bos_token_id": 30522,
19
+ "chunk_size_feed_forward": 0,
20
+ "cross_attention_hidden_size": null,
21
+ "decoder_start_token_id": null,
22
+ "diversity_penalty": 0.0,
23
+ "do_sample": false,
24
+ "early_stopping": false,
25
+ "encoder_hidden_size": 1024,
26
+ "encoder_no_repeat_ngram_size": 0,
27
+ "eos_token_id": 2,
28
+ "exponential_decay_length_penalty": null,
29
+ "finetuning_task": null,
30
+ "forced_bos_token_id": null,
31
+ "forced_eos_token_id": null,
32
+ "hidden_act": "gelu",
33
+ "hidden_dropout_prob": 0.0,
34
+ "hidden_size": 768,
35
+ "id2label": {
36
+ "0": "LABEL_0",
37
+ "1": "LABEL_1"
38
+ },
39
+ "initializer_factor": 1.0,
40
+ "initializer_range": 0.02,
41
+ "intermediate_size": 3072,
42
+ "is_decoder": true,
43
+ "is_encoder_decoder": false,
44
+ "label2id": {
45
+ "LABEL_0": 0,
46
+ "LABEL_1": 1
47
+ },
48
+ "layer_norm_eps": 1e-12,
49
+ "length_penalty": 1.0,
50
+ "max_length": 20,
51
+ "max_position_embeddings": 512,
52
+ "min_length": 0,
53
+ "model_type": "blip_text_model",
54
+ "no_repeat_ngram_size": 0,
55
+ "num_attention_heads": 12,
56
+ "num_beam_groups": 1,
57
+ "num_beams": 1,
58
+ "num_hidden_layers": 12,
59
+ "num_return_sequences": 1,
60
+ "output_attentions": false,
61
+ "output_hidden_states": false,
62
+ "output_scores": false,
63
+ "pad_token_id": 0,
64
+ "prefix": null,
65
+ "problem_type": null,
66
+ "projection_dim": 768,
67
+ "pruned_heads": {},
68
+ "remove_invalid_values": false,
69
+ "repetition_penalty": 1.0,
70
+ "return_dict": true,
71
+ "return_dict_in_generate": false,
72
+ "sep_token_id": 102,
73
+ "suppress_tokens": null,
74
+ "task_specific_params": null,
75
+ "temperature": 1.0,
76
+ "tf_legacy_loss": false,
77
+ "tie_encoder_decoder": false,
78
+ "tie_word_embeddings": true,
79
+ "tokenizer_class": null,
80
+ "top_k": 50,
81
+ "top_p": 1.0,
82
+ "torch_dtype": null,
83
+ "torchscript": false,
84
+ "transformers_version": "4.26.0.dev0",
85
+ "typical_p": 1.0,
86
+ "use_bfloat16": false,
87
+ "use_cache": true,
88
+ "vocab_size": 30524
89
+ },
90
+ "torch_dtype": "float32",
91
+ "transformers_version": null,
92
+ "vision_config": {
93
+ "_name_or_path": "",
94
+ "add_cross_attention": false,
95
+ "architectures": null,
96
+ "attention_dropout": 0.0,
97
+ "bad_words_ids": null,
98
+ "begin_suppress_tokens": null,
99
+ "bos_token_id": null,
100
+ "chunk_size_feed_forward": 0,
101
+ "cross_attention_hidden_size": null,
102
+ "decoder_start_token_id": null,
103
+ "diversity_penalty": 0.0,
104
+ "do_sample": false,
105
+ "dropout": 0.0,
106
+ "early_stopping": false,
107
+ "encoder_no_repeat_ngram_size": 0,
108
+ "eos_token_id": null,
109
+ "exponential_decay_length_penalty": null,
110
+ "finetuning_task": null,
111
+ "forced_bos_token_id": null,
112
+ "forced_eos_token_id": null,
113
+ "hidden_act": "gelu",
114
+ "hidden_size": 1024,
115
+ "id2label": {
116
+ "0": "LABEL_0",
117
+ "1": "LABEL_1"
118
+ },
119
+ "image_size": 384,
120
+ "initializer_factor": 1.0,
121
+ "initializer_range": 0.02,
122
+ "intermediate_size": 4096,
123
+ "is_decoder": false,
124
+ "is_encoder_decoder": false,
125
+ "label2id": {
126
+ "LABEL_0": 0,
127
+ "LABEL_1": 1
128
+ },
129
+ "layer_norm_eps": 1e-05,
130
+ "length_penalty": 1.0,
131
+ "max_length": 20,
132
+ "min_length": 0,
133
+ "model_type": "blip_vision_model",
134
+ "no_repeat_ngram_size": 0,
135
+ "num_attention_heads": 16,
136
+ "num_beam_groups": 1,
137
+ "num_beams": 1,
138
+ "num_channels": 3,
139
+ "num_hidden_layers": 24,
140
+ "num_return_sequences": 1,
141
+ "output_attentions": false,
142
+ "output_hidden_states": false,
143
+ "output_scores": false,
144
+ "pad_token_id": null,
145
+ "patch_size": 16,
146
+ "prefix": null,
147
+ "problem_type": null,
148
+ "projection_dim": 512,
149
+ "pruned_heads": {},
150
+ "remove_invalid_values": false,
151
+ "repetition_penalty": 1.0,
152
+ "return_dict": true,
153
+ "return_dict_in_generate": false,
154
+ "sep_token_id": null,
155
+ "suppress_tokens": null,
156
+ "task_specific_params": null,
157
+ "temperature": 1.0,
158
+ "tf_legacy_loss": false,
159
+ "tie_encoder_decoder": false,
160
+ "tie_word_embeddings": true,
161
+ "tokenizer_class": null,
162
+ "top_k": 50,
163
+ "top_p": 1.0,
164
+ "torch_dtype": null,
165
+ "torchscript": false,
166
+ "transformers_version": "4.26.0.dev0",
167
+ "typical_p": 1.0,
168
+ "use_bfloat16": false
169
+ }
170
+ }
handler.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any, List
2
+ from PIL import Image
3
+ import torch
4
+ from io import BytesIO
5
+ from transformers import VisionEncoderDecoderModel, ViTImageProcessor, AutoTokenizer
6
+
7
+
8
+ # Source: https://www.philschmid.de/custom-inference-handler
9
+
10
+
11
+ class EndpointHandler:
12
+ def __init__(self, path="nlpconnect/vit-gpt2-image-captioning"):
13
+ self.model = VisionEncoderDecoderModel.from_pretrained(path)
14
+
15
+ # Using ViTImageProcessor instead of ViTFeatureExtractor
16
+ self.feature_extractor = ViTImageProcessor.from_pretrained(path)
17
+
18
+ self.tokenizer = AutoTokenizer.from_pretrained(path)
19
+
20
+ self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
21
+ self.model.to(self.device)
22
+
23
+ self.max_length = 16
24
+ self.num_beams = 4
25
+
26
+ def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:
27
+ """
28
+ Args:
29
+ data (:obj:):
30
+ includes the input image data.
31
+ Return:
32
+ A :obj:`dict` with the caption.
33
+ """
34
+ image_bytes = data.get("inputs", None)
35
+
36
+ # Convert image bytes to PIL Image
37
+ image = Image.open(BytesIO(image_bytes))
38
+ if image.mode != "RGB":
39
+ image = image.convert(mode="RGB")
40
+
41
+ pixel_values = self.feature_extractor(
42
+ images=image, return_tensors="pt"
43
+ ).pixel_values
44
+ pixel_values = pixel_values.to(self.device)
45
+
46
+ gen_kwargs = {"max_length": self.max_length, "num_beams": self.num_beams}
47
+ output_ids = self.model.generate(pixel_values, **gen_kwargs)
48
+
49
+ caption = self.tokenizer.decode(output_ids[0], skip_special_tokens=True).strip()
50
+
51
+ return {"caption": caption}
52
+
53
+
54
+ # from typing import Dict, Any, List
55
+ # from PIL import Image
56
+ # import torch
57
+ # import os
58
+ # from io import BytesIO
59
+ # from transformers import (
60
+ # VisionEncoderDecoderModel,
61
+ # ViTImageProcessor,
62
+ # AutoTokenizer,
63
+ # PreTrainedModel,
64
+ # )
65
+
66
+
67
+ # class EndpointHandler:
68
+ # def __init__(self, model_path="nlpconnect/vit-gpt2-image-captioning"):
69
+ # # Load model and components
70
+ # self.model: PreTrainedModel = VisionEncoderDecoderModel.from_pretrained(
71
+ # model_path
72
+ # )
73
+ # self.processor = ViTImageProcessor.from_pretrained(model_path)
74
+ # self.tokenizer = AutoTokenizer.from_pretrained(model_path)
75
+
76
+ # # Ensure model is on the correct device
77
+ # self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
78
+ # self.model.to(self.device)
79
+
80
+ # # Parameters for generation
81
+ # self.gen_kwargs = {"max_length": 16, "num_beams": 4, "attention_mask": True}
82
+
83
+ # # Save model and configuration to the /repository directory
84
+ # self.model_directory = "/repository"
85
+ # os.makedirs(self.model_directory, exist_ok=True) # Ensure the directory exists
86
+ # self.model.config.save_pretrained(self.model_directory)
87
+ # torch.save(
88
+ # self.model.state_dict(),
89
+ # os.path.join(self.model_directory, "pytorch_model.bin"),
90
+ # )
91
+
92
+ # def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
93
+ # image_bytes = data["image"]
94
+
95
+ # # Open image and ensure it's RGB
96
+ # image = Image.open(BytesIO(image_bytes))
97
+ # if image.mode != "RGB":
98
+ # image = image.convert("RGB")
99
+
100
+ # # Process image and prepare input tensor
101
+ # pixel_values = self.processor(images=image, return_tensors="pt").pixel_values
102
+ # pixel_values = pixel_values.to(self.device)
103
+
104
+ # # Generate captions
105
+ # output_ids = self.model.generate(pixel_values, **self.gen_kwargs)
106
+ # caption = self.tokenizer.decode(output_ids[0], skip_special_tokens=True).strip()
107
+
108
+ # return {"caption": caption}
preprocessor_config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "do_normalize": true,
3
+ "do_pad": true,
4
+ "do_rescale": true,
5
+ "do_resize": true,
6
+ "image_mean": [
7
+ 0.48145466,
8
+ 0.4578275,
9
+ 0.40821073
10
+ ],
11
+ "image_processor_type": "BlipImageProcessor",
12
+ "image_std": [
13
+ 0.26862954,
14
+ 0.26130258,
15
+ 0.27577711
16
+ ],
17
+ "processor_class": "BlipProcessor",
18
+ "resample": 3,
19
+ "rescale_factor": 0.00392156862745098,
20
+ "size": {
21
+ "height": 384,
22
+ "width": 384
23
+ },
24
+ "size_divisor": 32
25
+ }
special_tokens_map.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "mask_token": "[MASK]",
4
+ "pad_token": "[PAD]",
5
+ "sep_token": "[SEP]",
6
+ "unk_token": "[UNK]"
7
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cls_token": "[CLS]",
3
+ "do_basic_tokenize": true,
4
+ "do_lower_case": true,
5
+ "mask_token": "[MASK]",
6
+ "model_max_length": 512,
7
+ "name_or_path": "Salesforce/blip-image-captioning-large",
8
+ "never_split": null,
9
+ "pad_token": "[PAD]",
10
+ "processor_class": "BlipProcessor",
11
+ "sep_token": "[SEP]",
12
+ "special_tokens_map_file": null,
13
+ "strip_accents": null,
14
+ "tokenize_chinese_chars": true,
15
+ "tokenizer_class": "BertTokenizer",
16
+ "unk_token": "[UNK]",
17
+ "model_input_names": [
18
+ "input_ids",
19
+ "attention_mask"
20
+ ]
21
+ }
vocab.txt ADDED
The diff for this file is too large to render. See raw diff