How to run the following code in a multiprocess way? I want to synchrosize data_dict among processes so there are no repeat.
code
with open("/ssddata/jhzhang/videoeval/LLaVA-OV/sample_video_conv_0.json", "r") as file:
data_dict = json.load(file)
video_folder = "/ssddata/jhzhang/caoruili/youtube_api-1/stage4/downloaded_videos/sports/"
for i in range(len(data_dict)):
video_file = data_dict[i]["video"]
video_file = os.path.join(video_folder, video_file)
video = process_video_with_decord(video_file)
# frames x [ width * height * 3 ] 360 * 640 * 3
image = preprocess(video, return_tensors="pt")["pixel_values"]
# image = [(image, video[0].size, "video")]
# print("image", len(image),image[0][0].shape,image[0][1],)
# #image 1 torch.Size([14, 3, 384, 384]) 691200
vid = video_file.split("/")[-1].split(".")[0]
save_file = os.path.join(save_folder, f'{vid}.h5')
with h5py.File(save_file, 'w') as f:
f.create_dataset(f'{vid}', data=image.numpy(), compression='gzip', compression_opts=9)
Assistant
To run your code in a multiprocess way and ensure that each item in data_dict is processed only once without repeats, you can use Python's multiprocessing module. Specifically, you can utilize multiprocessing.Pool to distribute the workload across multiple processes.
Here's how you can modify your code:
Define a Worker Function: Create a function that processes a single item from data_dict. This function will be called by each process.
Use multiprocessing.Pool: Initialize a pool of worker processes and use pool.map() to distribute the items in data_dict to the worker function.
Here's the modified code:
python
import os
import json
import h5py
from multiprocessing import Pool
# Define your video_folder and save_folder
video_folder = "/ssddata/jhzhang/caoruili/youtube_api-1/stage4/downloaded_videos/sports/"
save_folder = "/path/to/save_folder" # Replace with your actual save folder path
# Define the worker function
def process_item(item):
video_file = item["video"]
video_file = os.path.join(video_folder, video_file)
video = process_video_with_decord(video_file)
image = preprocess(video, return_tensors="pt")["pixel_values"]
vid = video_file.split("/")[-1].split(".")[0]
save_file = os.path.join(save_folder, f'{vid}.h5')
with h5py.File(save_file, 'w') as f:
f.create_dataset(f'{vid}', data=image.numpy(), compression='gzip', compression_opts=9)
if __name__ == '__main__':
# Load the data_dict
with open("/ssddata/jhzhang/videoeval/LLaVA-OV/sample_video_conv_0.json", "r") as file:
data_dict = json.load(file)
# Set the number of processes (adjust based on your system's capabilities)
num_processes = 4 # You can set this to os.cpu_count() or any other number
# Create a pool of worker processes
with Pool(processes=num_processes) as pool:
# Use pool.map to distribute the data_dict items to the worker function
pool.map(process_item, data_dict)
Explanation:
Worker Function (process_item): This function processes a single item from data_dict. It reads the video file, processes it, and saves the result.
Multiprocessing Pool:
Pool(processes=num_processes): Initializes a pool with the specified number of processes.
pool.map(process_item, data_dict): Distributes the items in data_dict to the worker processes. Each process calls process_item with a different item.
Benefits:
No Repeats: Since pool.map() ensures that each item in data_dict is sent to the worker function exactly once, there will be no repeats.
Synchronized Access: The pool takes care of distributing the tasks, so you don't need to manually synchronize access to data_dict.
Notes:
Shared Variables: Ensure that variables like video_folder and save_folder are accessible within the worker function. If they are defined outside the function, as in the code above, they will be available to each subprocess.
Picklable Data: The items in data_dict must be picklable since they need to be serialized and sent to the worker processes. Typically, lists and dictionaries containing basic data types are picklable.
Process-Safe Operations: Since each process works on its own data and writes to separate files, there are no shared resources that could cause conflicts. This eliminates the need for locks or other synchronization mechanisms.
Adjusting Number of Processes: You can adjust num_processes based on the number of CPU cores on your machine or the desired level of parallelism.
Example with Progress Bar (Optional):
If you want to monitor the progress of the multiprocessing tasks, you can use the tqdm library:
python
from multiprocessing import Pool
from tqdm import tqdm
def process_item(item):
# ... (same as before)
if __name__ == '__main__':
with open("/ssddata/jhzhang/videoeval/LLaVA-OV/sample_video_conv_0.json", "r") as file:
data_dict = json.load(file)
num_processes = 4
with Pool(processes=num_processes) as pool:
for _ in tqdm(pool.imap_unordered(process_item, data_dict), total=len(data_dict)):
pass
In this example, tqdm provides a progress bar, and pool.imap_unordered() is used instead of pool.map() to allow the progress bar to update as tasks complete.
Summary:
By defining a worker function and using multiprocessing.Pool, you can efficiently run your code in a multiprocess way while ensuring that each item in data_dict is processed exactly once without repeats.