To ensure that the saving process does not interfere with the GPT request times, you can implement a producer-consumer pattern using Python's multiprocessing or threading modules. This approach allows the main process (producer) to handle GPT requests and enqueue the results, while a separate process or thread (consumer) handles writing to the file.
Below, I'll provide a solution using the multiprocessing module with a Queue. This method is suitable for CPU-bound tasks and ensures that both the GPT requests and the saving process run in parallel without blocking each other.
Step-by-Step Solution
-
Import Necessary Modules:
multiprocessing: To create separate processes.
queue: To handle the case where the queue might become full or empty.
signal and sys: For graceful shutdowns.
-
Create a Separate Saving Process:
- This process will continuously listen for new items in the queue and write them to the JSON Lines (
jsonl) file.
- Implement a sentinel value to signal the saving process to terminate gracefully once all data has been processed.
-
Modify the Main Process:
- Instead of appending to
all_output and writing periodically, enqueue each result to the queue.
- This ensures that the main process doesn't wait for the saving process to complete.
-
Handle Graceful Shutdowns:
- Ensure that all processes terminate correctly, especially when the script is interrupted.
Updated Code with Saving in a Separate Process
from openai import OpenAI
import base64
import jsonlines
from tqdm import tqdm
from itertools import islice
import multiprocessing
import signal
import sys
# Function to handle graceful shutdown
def init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
def save_worker(queue, output_path):
with jsonlines.open(output_path, 'w') as writer:
while True:
item = queue.get()
if item == "STOP":
break
writer.write(item)
def main():
KEY = open("private_api.key").read().strip()
URL = open("private_url.key").read().strip()
MODEL = "gpt-4o"
client = OpenAI(
base_url=URL,
api_key=KEY,
)
def request_text(text, timeout=60):
response = client.chat.completions.create(
model=MODEL,
messages=[
{
"role": "user",
"content": text,
}
],
max_tokens=2000,
timeout=timeout,
)
return response.choices[0].message.content
template = """
The whole caption of the video is:
_WHOLE_CAPTION_
Five captions at different frames:
_FIVE_CAPTIONS_
Return your message directly in the frame number I provide (45, 135, 225, 315, 405). DO NOT add other sentences.
"""
format_text = lambda x,y: template.replace('_WHOLE_CAPTION_', x).replace('_FIVE_CAPTIONS_', y)
input_path = "/cpfs/data/user/yanxin/data/very_longvideos/ytb_jsonl/ytb_100k_yi6b_filter_450f_psnr0.5_ssim0.5_flow0.2_lpips_all.jsonl"
output_temp_path = "/cpfs/data/user/yanxin/data/very_longvideos/ytb_jsonl/ytb_100k_yi6b_filter_450f_psnr0.5_ssim0.5_flow0.2_lpips_all.gpt4o_temp.jsonl"
output_final_path = "/cpfs/data/user/yanxin/data/very_longvideos/ytb_jsonl/ytb_100k_yi6b_filter_450f_psnr0.5_ssim0.5_flow0.2_lpips_all_gpt4o.jsonl"
iter = jsonlines.open(input_path)
total_items = 25000 # Update this if necessary
# Create a multiprocessing Queue
manager = multiprocessing.Manager()
queue = manager.Queue(maxsize=1000) # Adjust maxsize based on memory constraints
# Start the saving process
saver = multiprocessing.Process(target=save_worker, args=(queue, output_temp_path))
saver.start()
all_output = []
try:
for i, obj in enumerate(tqdm(iter, total=total_items)):
clip_id = obj['clip_id']
whole_caption = obj['yi6b_0910_video']
five_captions_dict = obj['yi6b_0910_images']
five_captions = "\n".join([f"{k}: {v}" for k, v in five_captions_dict.items()])
text = format_text(whole_caption, five_captions)
try:
response = request_text(text)
output_item = {
"clip_id": clip_id,
"response": response
}
# Enqueue the output
queue.put(output_item)
except Exception as e:
print(f"Error processing clip_id {clip_id}: {e}")
continue
if (i + 1) % 100 == 0:
print(f"Processed {i + 1} items...")
except KeyboardInterrupt:
print("Interrupted by user. Shutting down...")
finally:
# Signal the saver process to stop
queue.put("STOP")
saver.join()
# Optionally, merge temp and final output if needed
# For simplicity, assuming temp output is the final output
# If additional processing is needed, implement it here
# You can copy or rename the temp file to final if required
import shutil
shutil.copy(output_temp_path, output_final_path)
print(f"Saved all outputs to {output_final_path}")
if __name__ == "__main__":
main()
Explanation of the Changes
-
Multiprocessing Setup:
- Queue: A
multiprocessing.Manager().Queue() is created to facilitate communication between the main process and the saving process. The maxsize parameter helps prevent excessive memory usage.
- Saver Process: A separate process (
save_worker) is started to handle writing to the temporary JSONL file. This process listens for items on the queue and writes them as they arrive.
- Graceful Termination: A sentinel value (
"STOP") is placed on the queue to signal the saver process to terminate once all data has been processed.
-
Main Processing Loop:
- Instead of appending results to
all_output, each output_item is enqueued using queue.put(output_item).
- The periodic saving (
if i % 100 == 0) is removed since the saver process handles writing in real-time.
- Progress messages are retained to monitor processing.
-
Graceful Shutdown Handling:
- The
try-except-finally block ensures that if the script is interrupted (e.g., via Ctrl+C), the saver process is signaled to stop, and the script exits cleanly.
- After processing, the temporary output file is copied to the final output path. You can modify this behavior based on your specific requirements.
-
Additional Considerations:
- Error Handling: Errors during GPT requests are logged with the corresponding
clip_id, and processing continues.
- Performance Tuning: Adjust the
maxsize of the queue based on your system's memory and performance characteristics. A larger queue can help keep both processes busy but consumes more memory.
Alternative Approach Using Threading
If you prefer to use threading instead of multiprocessing (which is generally more lightweight and sufficient for I/O-bound tasks like file writing), you can use Python's threading module along with queue.Queue. Here's how you can modify the saving process using threading:
import threading
import queue
def save_worker_thread(q, output_path):
with jsonlines.open(output_path, 'w') as writer:
while True:
item = q.get()
if item == "STOP":
break
writer.write(item)
q.task_done()
def main_threading():
# ... [Initialize variables as before]
q = queue.Queue(maxsize=1000)
saver = threading.Thread(target=save_worker_thread, args=(q, output_temp_path), daemon=True)
saver.start()
try:
for i, obj in enumerate(tqdm(iter, total=total_items)):
# ... [Process each obj as before]
try:
response = request_text(text)
output_item = {
"clip_id": clip_id,
"response": response
}
q.put(output_item)
except Exception as e:
print(f"Error processing clip_id {clip_id}: {e}")
continue
if (i + 1) % 100 == 0:
print(f"Processed {i + 1} items...")
except KeyboardInterrupt:
print("Interrupted by user. Shutting down...")
finally:
q.put("STOP")
saver.join()
shutil.copy(output_temp_path, output_final_path)
print(f"Saved all outputs to {output_final_path}")
Notes on the Threading Approach:
- Daemon Threads: Setting
daemon=True ensures that the thread will exit when the main program does, even if it's still running.
- Thread Safety: Python's
queue.Queue is thread-safe, making it suitable for producer-consumer patterns with threads.
- Performance: Threading is generally more efficient for I/O-bound tasks like file writing but may not offer the same performance benefits for CPU-bound tasks due to the Global Interpreter Lock (GIL).
Final Recommendations
By implementing the above changes, you can ensure that the saving process runs concurrently with the GPT requests, thereby improving the overall efficiency and performance of your script.