Commit
·
d721e7b
1
Parent(s):
57d06c0
Create caption.py
Browse files- caption.py +111 -0
caption.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import jsonlines
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import time
|
| 5 |
+
from vllm import LLM, SamplingParams
|
| 6 |
+
from huggingface_hub import HfApi, Repository
|
| 7 |
+
import torch
|
| 8 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 9 |
+
|
| 10 |
+
def generate_responses(llm, batch_texts, sampling_params):
|
| 11 |
+
print("Generating responses for the current batch...")
|
| 12 |
+
appended_prompts = [
|
| 13 |
+
f"you are a captioner, you only generate 3 single sentence long captions as though the text were an image, and return the captions in an enumerated list with each being one sentence long and in quotes, and each a description of a hypothetical image inspired by [{prompt}]"
|
| 14 |
+
for prompt in batch_texts
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
outputs = llm.generate(appended_prompts, sampling_params)
|
| 18 |
+
|
| 19 |
+
responses = [[output.outputs[k].text.strip() for k in range(len(output.outputs))] for output in outputs]
|
| 20 |
+
return responses
|
| 21 |
+
|
| 22 |
+
def process_file(llm, filepath, sampling_params):
|
| 23 |
+
print(f"Processing file: {filepath}")
|
| 24 |
+
BATCH_SIZE = 128
|
| 25 |
+
BATCH_INCREMENT = 32
|
| 26 |
+
prev_eps = 0
|
| 27 |
+
batch_texts = []
|
| 28 |
+
df = pd.DataFrame()
|
| 29 |
+
|
| 30 |
+
if filepath.endswith('.parquet'):
|
| 31 |
+
print("Reading from a parquet file...")
|
| 32 |
+
df = pd.read_parquet(filepath)
|
| 33 |
+
batch_texts = df['TEXT'].tolist()
|
| 34 |
+
|
| 35 |
+
total_prompts = len(batch_texts)
|
| 36 |
+
print(f"Total prompts found: {total_prompts}")
|
| 37 |
+
|
| 38 |
+
i = 0
|
| 39 |
+
new_filepath = filepath.replace('.parquet', '_processed.jsonl')
|
| 40 |
+
print(f"Data will be saved to: {new_filepath}")
|
| 41 |
+
|
| 42 |
+
with jsonlines.open(new_filepath, 'w') as writer:
|
| 43 |
+
with ThreadPoolExecutor() as executor:
|
| 44 |
+
while i < total_prompts:
|
| 45 |
+
batch = batch_texts[i:i+BATCH_SIZE]
|
| 46 |
+
|
| 47 |
+
start_time = time.time()
|
| 48 |
+
batch_responses = generate_responses(llm, batch, sampling_params)
|
| 49 |
+
end_time = time.time()
|
| 50 |
+
|
| 51 |
+
duration = end_time - start_time
|
| 52 |
+
eps = len(batch) / duration
|
| 53 |
+
|
| 54 |
+
# Adjust batch size based on examples per second
|
| 55 |
+
if eps > prev_eps and BATCH_SIZE + BATCH_INCREMENT <= total_prompts - i:
|
| 56 |
+
BATCH_SIZE += BATCH_INCREMENT
|
| 57 |
+
print(f"Increasing batch size to: {BATCH_SIZE}")
|
| 58 |
+
elif eps < prev_eps and BATCH_SIZE - BATCH_INCREMENT > 0:
|
| 59 |
+
BATCH_SIZE -= BATCH_INCREMENT
|
| 60 |
+
print(f"Decreasing batch size to: {BATCH_SIZE}")
|
| 61 |
+
|
| 62 |
+
prev_eps = eps
|
| 63 |
+
|
| 64 |
+
# Print progress and write to file after every batch.
|
| 65 |
+
print(f"Processed: {min(i + BATCH_SIZE, total_prompts)}/{total_prompts}, Batch Size: {BATCH_SIZE}, EPS: {eps:.2f}")
|
| 66 |
+
print("Writing to the new jsonl file...")
|
| 67 |
+
for idx, text in enumerate(batch):
|
| 68 |
+
writer.write({'TEXT': text, 'RESPONSE': batch_responses[idx][0]})
|
| 69 |
+
|
| 70 |
+
# Delete the processed rows from the original parquet file
|
| 71 |
+
if not df.empty:
|
| 72 |
+
df = df.iloc[i + BATCH_SIZE:]
|
| 73 |
+
executor.submit(df.to_parquet, filepath)
|
| 74 |
+
|
| 75 |
+
i += BATCH_SIZE
|
| 76 |
+
|
| 77 |
+
# Delete the original parquet file if it is empty
|
| 78 |
+
if df.empty:
|
| 79 |
+
os.remove(filepath)
|
| 80 |
+
print(f"Deleted the original file: {filepath}")
|
| 81 |
+
|
| 82 |
+
# Initialize the HuggingFace API
|
| 83 |
+
api = HfApi()
|
| 84 |
+
|
| 85 |
+
# Upload the processed file to the repository
|
| 86 |
+
try:
|
| 87 |
+
api.upload_file(
|
| 88 |
+
path_or_fileobj=new_filepath,
|
| 89 |
+
path_in_repo=new_filepath,
|
| 90 |
+
repo_id="AlignmentLab-AI/caption_creation_0.8",
|
| 91 |
+
repo_type="dataset",
|
| 92 |
+
)
|
| 93 |
+
print(f"Uploaded {new_filepath} to AlignmentLab-AI/caption_creation_0.8 repository.")
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"Error uploading file: {e}")
|
| 96 |
+
|
| 97 |
+
def main():
|
| 98 |
+
folder_name = 'captionate'
|
| 99 |
+
sampling_params = SamplingParams(temperature=0.7, top_p=0.95, max_tokens=100)
|
| 100 |
+
|
| 101 |
+
print("Initializing the LLM model...")
|
| 102 |
+
llm = LLM("Open-Orca/Mistral-7B-OpenOrca")
|
| 103 |
+
|
| 104 |
+
print("Iterating through the files in the folder...")
|
| 105 |
+
for filename in os.listdir(folder_name):
|
| 106 |
+
if filename.endswith(".parquet"):
|
| 107 |
+
process_file(llm, os.path.join(folder_name, filename), sampling_params)
|
| 108 |
+
|
| 109 |
+
if __name__ == "__main__":
|
| 110 |
+
main()
|
| 111 |
+
|