repo
stringlengths 2
99
| file
stringlengths 14
239
| code
stringlengths 20
3.99M
| file_length
int64 20
3.99M
| avg_line_length
float64 9.73
128
| max_line_length
int64 11
86.4k
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
neu-nbv | neu-nbv-main/scripts/planning/simulator_planning.py | import rospy
import os
import sys
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, root_dir)
import yaml
import argparse
from planner import get_planner
from datetime import datetime
def main():
# planning experiment in simulator using a specific planner
args = parse_args()
rospy.init_node(args.planner_type)
# find planner configuration file
experiment_path = os.path.join(
root_dir,
"experiments",
"simulator",
datetime.now().strftime("%d-%m-%Y-%H-%M"),
)
planner_cfg_path = os.path.join(
"planning/config", f"{args.planner_type}_planner.yaml"
)
assert os.path.exists(planner_cfg_path)
with open(planner_cfg_path, "r") as config_file:
planner_cfg = yaml.safe_load(config_file)
planner_cfg.update(args.__dict__)
planner_cfg["planner_type"] = args.planner_type
planner_cfg["experiment_path"] = experiment_path
planner_cfg["experiment_id"] = "record"
nbv_planner = get_planner(planner_cfg)
nbv_planner.start()
def parse_args():
parser = argparse.ArgumentParser()
# mandatory arguments
parser.add_argument(
"--planner_type", "-P", type=str, required=True, help="planner_type"
)
# arguments with default values
parser.add_argument(
"--planning_budget",
"-BG",
type=int,
default=20,
help="maximal measurments for the mission",
)
parser.add_argument(
"--device",
type=str,
default="cuda",
help="config file path",
)
parser.add_argument(
"--gpu_id",
type=str,
default="0",
help="gpu to use, space delimited",
)
parser.add_argument(
"--initial_view",
type=list,
default=[0, 0],
help="prefixed initial camera view angle",
)
parser.add_argument(
"--random_initial",
action="store_true",
help="use random inital camera pose",
)
args = parser.parse_args()
return args
if __name__ == "__main__":
main()
| 2,103 | 22.640449 | 76 | py |
neu-nbv | neu-nbv-main/scripts/planning/dtu_experiment.py | import sys
import os
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, root_dir)
from neural_rendering.evaluation.pretrained_model import PretrainedModel
from neural_rendering.data import get_data
from neural_rendering.utils import parser, util
import yaml
from dotmap import DotMap
import torch
import warnings
import numpy as np
import pandas
import seaborn as sb
import copy
from scipy.spatial import distance
from datetime import datetime
import random
import pickle
from dotmap import DotMap
warnings.filterwarnings("ignore")
# follow pixelnerf setup
candidate_index_list = [
6,
7,
8,
9,
10,
13,
14,
15,
16,
17,
21,
22,
23,
24,
25,
31,
32,
33,
34,
35,
41,
42,
43,
44,
45,
]
def setup_random_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def get_nbv_ref_index(
model, images, poses, focal, c, z_near, z_far, candidate_list, budget, ref_index
):
_, _, H, W = images.shape
for i in range(budget):
remain_candidate_list = list(set(candidate_list) - set(ref_index))
reward_list = []
model.network.encode(
images[ref_index].unsqueeze(0),
poses[ref_index].unsqueeze(0),
focal.unsqueeze(0),
c.unsqueeze(0),
)
for target_view in remain_candidate_list:
novel_pose = poses[target_view]
target_rays = util.gen_rays(
novel_pose.unsqueeze(0), W, H, focal, z_near, z_far, c
)
target_rays = target_rays.reshape(1, H * W, -1)
predict = DotMap(model.renderer_par(target_rays))
uncertainty = predict["uncertainty"][0]
reward = torch.sum(uncertainty**2).cpu().numpy()
reward_list.append(reward)
nbv_index = np.argmax(reward_list)
new_ref_index = remain_candidate_list[nbv_index]
ref_index.append(new_ref_index)
return ref_index
def get_camera_view_direction(poses):
poses = poses.cpu().numpy()
view_direction = -poses[..., :3, 2]
view_direction = view_direction / np.linalg.norm(view_direction)
return view_direction
def get_max_dist_ref_index(poses, ref_index, candidate_list, budget):
view_direction = get_camera_view_direction(poses)
for i in range(budget):
remain_candidate_list = list(set(candidate_list) - set(ref_index))
cos_distance_list = []
for idx in remain_candidate_list:
cos_dist = 0.0
for image_idx in ref_index:
cos_dist += distance.cosine(
view_direction[idx], view_direction[image_idx]
)
cos_distance_list.append(cos_dist)
new_ref_index = remain_candidate_list[np.argmax(cos_distance_list)]
ref_index.append(new_ref_index)
return ref_index
def main():
# planning experiment on DTU using baseline planners and our planner
setup_random_seed(10)
args = parser.parse_args(planning_args)
dtu_nbv_planner = DTUNBVPlanning(args)
experiment_path = args.experiment_path
if args.evaluation_only:
with open(f"{experiment_path}/saved_index_dict.pkl", "rb") as f:
index_record = pickle.load(f)
else:
experiment_path = os.path.join(
root_dir,
"experiments",
"dtu",
datetime.now().strftime("%d-%m-%Y-%H-%M"),
)
os.makedirs(experiment_path)
index_record = dtu_nbv_planner.planning()
with open(f"{experiment_path}/saved_index_dict.pkl", "wb") as f:
pickle.dump(index_record, f)
total_df = dtu_nbv_planner.evaluation(index_record)
total_df.to_csv(f"{experiment_path}/dataframe.csv")
class DTUNBVPlanning:
"""
planning on DTU using different view selection methods: max_view_distance, random, and our uncertainty guided
"""
def __init__(self, args):
log_path = os.path.join(root_dir, "neural_rendering", "logs", args.model_name)
assert os.path.exists(log_path), "experiment does not exist"
with open(f"{log_path}/training_setup.yaml", "r") as config_file:
cfg = yaml.safe_load(config_file)
checkpoint_path = os.path.join(log_path, "checkpoints", "best.ckpt")
assert os.path.exists(checkpoint_path), "checkpoint does not exist"
ckpt_file = torch.load(checkpoint_path)
gpu_id = list(map(int, args.gpu_id.split()))
self.device = util.get_cuda(gpu_id[0])
self.repeat = args.repeat
self.model = PretrainedModel(cfg["model"], ckpt_file, self.device, gpu_id)
cfg["data"]["dataset"]["data_rootdir"] = os.path.join(
root_dir, "neural_rendering/data/dataset/dtu_dataset/rs_dtu_4/DTU"
)
datamodule = get_data(cfg["data"])
self.dataset = datamodule.load_dataset("val")
self.z_near = self.dataset.z_near
self.z_far = self.dataset.z_far
def planning(self):
print(f"---------- planning ---------- \n")
ON = len(self.dataset)
selection_type = ["Max. View Distance", "Random", "Ours"]
nview_list = [2, 3, 4, 5, 6, 7, 8, 9] # maximal budget = 9
scene_index = range(ON)
ref_index_record = {}
with torch.no_grad():
for nviews in nview_list:
ref_index_record[nviews] = {}
print(f"---------- {nviews} views experiment---------- \n")
for i in scene_index:
data_instance = self.dataset.__getitem__(i)
scene_title = data_instance["scan_name"]
ref_index_record[nviews][i] = {}
print(f"test on {scene_title}")
images = data_instance["images"].to(self.device)
focal = data_instance["focal"].to(self.device)
c = data_instance["c"].to(self.device)
poses = data_instance["poses"].to(self.device)
# random initialize first 2 ref images for all methods
for r in range(self.repeat):
ref_index_record[nviews][i][r] = {}
initial_ref_index = list(
np.random.choice(candidate_index_list, 2, replace=False)
)
candidate_list = list(
set(candidate_index_list) - set(initial_ref_index)
)
budget = nviews - 2
for stype in selection_type:
print(f"---------- repeat: {r}, {stype} ---------- \n")
if stype == "Max. View Distance":
ref_index = get_max_dist_ref_index(
poses,
copy.deepcopy(initial_ref_index),
candidate_list,
budget,
)
print(ref_index)
elif stype == "Random":
random_ref_index = list(
np.random.choice(
candidate_index_list, budget, replace=True
)
)
ref_index = initial_ref_index + random_ref_index
print(ref_index)
ref_index = np.unique(ref_index)
elif stype == "Ours":
ref_index = get_nbv_ref_index(
self.model,
images,
poses,
focal,
c,
self.z_near,
self.z_far,
candidate_list,
budget,
copy.deepcopy(initial_ref_index),
)
print(ref_index)
ref_index_record[nviews][i][r][stype] = ref_index
return ref_index_record
def evaluation(self, index_record):
print(f"---------- evaluation ---------- \n")
total_df = pandas.DataFrame(
{
"Planning Type": [],
"Reference Image Number": [],
"PSNR": [],
"SSIM": [],
"Scene": [],
}
)
with torch.no_grad():
for nviews, nviews_dict in index_record.items():
print(f"---------- {nviews} views experiment---------- \n")
for scene_id, scene_dict in nviews_dict.items():
data_instance = self.dataset.__getitem__(scene_id)
scene_title = data_instance["scan_name"]
print(f"test on {scene_title}")
images = data_instance["images"].to(self.device)
images_0to1 = images * 0.5 + 0.5
_, _, H, W = images.shape
focal = data_instance["focal"].to(self.device)
c = data_instance["c"].to(self.device)
poses = data_instance["poses"].to(self.device)
psnr_per_scene = []
ssim_per_scene = []
# random initialize first 2 ref images for all methods
for repeat, repeat_dict in scene_dict.items():
for stype, ref_index in repeat_dict.items():
print(f"---------- repeat: {repeat}, {stype} ---------- \n")
print(ref_index)
self.model.network.encode(
images[ref_index].unsqueeze(0),
poses[ref_index].unsqueeze(0),
focal.unsqueeze(0),
c.unsqueeze(0),
)
test_index = list(
set(candidate_index_list) - set(ref_index)
)
psnr_per_test = []
ssim_per_test = []
for target_view in test_index:
gt = (
images_0to1[target_view]
.permute(1, 2, 0)
.cpu()
.numpy()
)
novel_pose = poses[target_view]
target_rays = util.gen_rays(
novel_pose.unsqueeze(0),
W,
H,
focal,
self.z_near,
self.z_far,
c,
)
target_rays = target_rays.reshape(1, H * W, -1)
predict = DotMap(self.model.renderer_par(target_rays))
metrics_dict = util.calc_metrics(
predict, torch.tensor(gt)
)
psnr_per_test.append(metrics_dict["psnr"])
ssim_per_test.append(metrics_dict["ssim"])
psnr_per_scene = np.mean(psnr_per_test)
ssim_per_scene = np.mean(ssim_per_test)
print(psnr_per_scene, ssim_per_scene)
dataframe = pandas.DataFrame(
{
"Planning Type": stype,
"Reference Image Number": nviews,
"PSNR": psnr_per_scene,
"SSIM": ssim_per_scene,
"Scene": scene_id,
},
index=[repeat],
)
total_df = total_df.append(dataframe)
return total_df
def planning_args(parser):
"""
Parse arguments for evaluation setup.
"""
parser.add_argument(
"--model_name",
"-M",
type=str,
required=True,
help="model name of pretrained model",
)
parser.add_argument(
"--repeat",
"-R",
type=int,
default=5,
help="repeat times for planning experiment",
)
# arguments with default values
parser.add_argument(
"--evaluation_only", action="store_true", help="evaluation mode"
)
parser.add_argument(
"--experiment_path",
type=str,
default="not defined",
help="must be defined in evaluation mode",
)
parser.add_argument(
"--gpu_id", type=str, default="0", help="GPU(s) to use, space delimited"
)
return parser
if __name__ == "__main__":
main()
| 13,632 | 34.046272 | 113 | py |
neu-nbv | neu-nbv-main/scripts/planning/simulator_experiment.py | import rospy
import os
import sys
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, root_dir)
import yaml
import argparse
from planner import get_planner
from planner.utils import uniform_sampling
import numpy as np
import scipy.spatial as spatial
from datetime import datetime
import imageio
import glob
from dotmap import DotMap
import torch
from neural_rendering.utils import util
from neural_rendering.evaluation.pretrained_model import PretrainedModel
import pandas
import torch.nn.functional as F
planner_title = {
"max_distance": "Max. View Distance",
"random": "Random",
"neural_nbv": "Ours",
}
def setup_random_seed(seed):
np.random.seed(seed)
def main():
# planning experiment in simulator using baseline planners and our planner
setup_random_seed(10)
rospy.init_node("simulator_experiment")
args = parse_args()
planner_type_list = ["max_distance", "random", "neural_nbv"]
repeat = args.repeat
experiment_path = args.experiment_path
if not args.evaluation_only:
experiment_path = os.path.join(
root_dir,
"experiments",
"simulator",
datetime.now().strftime("%d-%m-%Y-%H-%M"),
)
os.makedirs(experiment_path, exist_ok=True)
print("---------- planning ----------")
for i in range(repeat):
# initialize planning with 2 same views
random_initial_view = []
for _ in range(2):
random_initial_view.append(
uniform_sampling(radius=2, phi_min=0.15)
) # hard-coded, should be the same for config file
for planner_type in planner_type_list:
# find planner configuration file
print(
f"---------- {planner_type} planner, experiment ID {i} ----------\n"
)
planner_cfg_path = os.path.join(
"planning/config", f"{planner_type}_planner.yaml"
)
assert os.path.exists(planner_cfg_path)
with open(planner_cfg_path, "r") as config_file:
planner_cfg = yaml.safe_load(config_file)
planner_cfg.update(args.__dict__)
planner_cfg["planner_type"] = planner_type
planner_cfg["experiment_path"] = experiment_path
planner_cfg["experiment_id"] = i
nbv_planner = get_planner(planner_cfg)
nbv_planner.start(initial_view=random_initial_view)
print("---------- evaluation ----------")
gpu_id = list(map(int, args.gpu_id.split()))
device = util.get_cuda(gpu_id[0])
log_path = os.path.join(root_dir, "neural_rendering", "logs", args.model_name)
assert os.path.exists(log_path), "experiment does not exist"
with open(f"{log_path}/training_setup.yaml", "r") as config_file:
cfg = yaml.safe_load(config_file)
checkpoint_path = os.path.join(log_path, "checkpoints", "best.ckpt")
assert os.path.exists(checkpoint_path), "checkpoint does not exist"
ckpt_file = torch.load(checkpoint_path)
model = PretrainedModel(cfg["model"], ckpt_file, device, gpu_id)
# load test view data as ground truth
test_rgbs, test_poses, focal, c = get_image_data(
args.test_data_path, "normal", device
)
# configure rendering information
nview = int(args.nviews)
_, _, H, W = test_rgbs.shape
z_near = cfg["data"]["dataset"]["z_near"]
z_far = cfg["data"]["dataset"]["z_far"]
step_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
total_df = pandas.DataFrame(
{
"Planning Type": [],
"Reference Image Num.": [],
"PSNR": [],
"SSIM": [],
}
)
for r in range(repeat):
for planner_type in planner_type_list:
ref_data_path = os.path.join(experiment_path, planner_type, str(r))
ref_rgbs, ref_poses, _, _ = get_image_data(ref_data_path, "normal", device)
for step in step_list:
print(
f"---------- planner:{planner_type}, repeat {r}, step {step} ----------\n"
)
ref_kd_tree = spatial.KDTree(ref_poses[:step, :3, 3].cpu().numpy())
psnr_list = []
ssim_list = []
with torch.no_grad():
for i, rgb in enumerate(test_rgbs):
pose = test_poses[i]
gt = rgb * 0.5 + 0.5
gt = gt.permute(1, 2, 0).cpu().numpy()
_, ref_index = ref_kd_tree.query(
pose[:3, 3].cpu().numpy(), np.minimum(nview, step)
)
model.network.encode(
ref_rgbs[ref_index].unsqueeze(0),
ref_poses[ref_index].unsqueeze(0),
focal.unsqueeze(0),
c.unsqueeze(0),
)
target_rays = util.gen_rays(
pose.unsqueeze(0), W, H, focal, z_near, z_far, c
)
target_rays = target_rays.reshape(1, H * W, -1)
predict = DotMap(model.renderer_par(target_rays))
metrics_dict = util.calc_metrics(predict, torch.tensor(gt))
psnr_list.append(metrics_dict["psnr"])
ssim_list.append(metrics_dict["ssim"])
psnr_mean = np.mean(psnr_list)
ssim_mean = np.mean(ssim_list)
print("psnr:", psnr_mean, "ssim:", ssim_mean)
dataframe = pandas.DataFrame(
{
"Planning Type": planner_title[planner_type],
"Reference Image Num.": step,
"PSNR": psnr_mean,
"SSIM": ssim_mean,
},
index=[r],
)
total_df = total_df.append(dataframe)
total_df.to_csv(f"{experiment_path}/dataframe.csv")
image_to_tensor = util.get_image_to_tensor_balanced()
def get_image_data(data_path, coordinate_format, device, rescale=0.5):
assert os.path.exists(data_path)
rgb_paths = [
x
for x in glob.glob(f"{data_path}/images/*")
if (x.endswith(".jpg") or x.endswith(".png"))
]
rgb_paths = sorted(rgb_paths)
images = []
poses = []
for image_path in rgb_paths:
image = imageio.imread(image_path)[..., :3]
image = image_to_tensor(image)
images.append(image)
pose_list = np.load(f"{data_path}/trajectory.npy")
for pose in pose_list:
pose = util.coordinate_transformation(pose, format=coordinate_format)
poses.append(pose)
with open(f"{data_path}/camera_info.yaml") as file:
intrinsic = yaml.safe_load(file)
images = torch.stack(images).to(device)
poses = torch.stack(poses).to(device)
if rescale != 1:
_, _, H, W = images.shape
H = int(rescale * H)
W = int(rescale * W)
images = F.interpolate(images, size=[W, H], mode="area")
focal = rescale * torch.tensor(intrinsic["focal"], dtype=torch.float32).to(device)
c = rescale * torch.tensor(intrinsic["c"], dtype=torch.float32).to(device)
assert len(images) == len(poses)
return images, poses, focal, c
def test_visualize(results_dict):
import matplotlib.pyplot as plt
H = 400
W = 400
rgb = results_dict.rgb[0].cpu().numpy().reshape(H, W, 3)
depth = results_dict.depth[0].cpu().numpy().reshape(H, W)
uncertainty = results_dict.uncertainty[0].cpu().numpy().reshape(H, W)
fig, axs = plt.subplots(1, 3)
axs[0].imshow(rgb)
axs[1].imshow(uncertainty)
axs[2].imshow(depth)
plt.show()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--model_name",
"-M",
type=str,
required=True,
help="model name of pretrained model",
)
parser.add_argument(
"--test_data_path",
"-TD",
type=str,
required=True,
help="data path",
)
# mandatory arguments
parser.add_argument(
"--repeat",
"-rp",
type=int,
default=10,
help="repeat experiment",
)
# arguments with default values
parser.add_argument(
"--nviews", "-nv", type=int, default=5, help="number of reference views"
)
parser.add_argument(
"--planning_budget",
"-BG",
type=int,
default=20,
help="maximal measurments for the mission",
)
parser.add_argument(
"--device",
type=str,
default="cuda",
help="config file path",
)
parser.add_argument(
"--gpu_id",
type=str,
default="0",
help="gpu to use, space delimited",
)
parser.add_argument(
"--evaluation_only", action="store_true", help="evaluation mode"
)
parser.add_argument(
"--experiment_path",
type=str,
default="not defined",
help="must be defined in evaluation mode",
)
args = parser.parse_args()
return args
if __name__ == "__main__":
main()
| 9,450 | 29.685065 | 94 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/simulator_bridge.py | import rospy
from gazebo_msgs.msg import ModelState
from sensor_msgs.msg import Image, CameraInfo
from cv_bridge import CvBridge
from . import utils
import numpy as np
class SimulatorBridge:
def __init__(self, cfg):
self.cv_bridge = CvBridge()
self.current_rgb = None
self.current_depth = None
self.camera_type = cfg["camera_type"]
self.sensor_noise = cfg["sensor_noise"]
self.get_simulator_camera_info()
self.pose_pub = rospy.Publisher(
"/gazebo/set_model_state", ModelState, queue_size=1, latch=True
)
if self.camera_type == "rgb_camera":
self.rgb_sub = rospy.Subscriber(
"/rgb_camera/rgb_image_raw", Image, self.update_rgb
)
elif self.camera_type == "rgbd_camera":
self.rgb_sub = rospy.Subscriber(
"/rgbd_camera/rgb_image_raw", Image, self.update_rgb
)
self.depth_sub = rospy.Subscriber(
"/rgbd_camera/depth_image_raw", Image, self.update_depth
)
def get_simulator_camera_info(self):
camera_info_raw = rospy.wait_for_message(
f"/{self.camera_type}/camera_info", CameraInfo
)
K = camera_info_raw.K # intrinsic matrix
H = int(camera_info_raw.height) # image height
W = int(camera_info_raw.width) # image width
self.camera_info = {
"image_resolution": [H, W],
"c": [K[2], K[5]],
"focal": [K[0], K[4]],
}
def move_camera(self, pose):
quaternion = utils.rotation_2_quaternion(pose[:3, :3])
translation = pose[:3, -1]
camera_pose_msg = ModelState()
camera_pose_msg.model_name = self.camera_type
camera_pose_msg.pose.position.x = translation[0]
camera_pose_msg.pose.position.y = translation[1]
camera_pose_msg.pose.position.z = translation[2]
camera_pose_msg.pose.orientation.x = quaternion[0]
camera_pose_msg.pose.orientation.y = quaternion[1]
camera_pose_msg.pose.orientation.z = quaternion[2]
camera_pose_msg.pose.orientation.w = quaternion[3]
self.pose_pub.publish(camera_pose_msg)
def update_rgb(self, data):
self.current_rgb = data
def update_depth(self, data):
self.current_depth = data
def get_image(self):
rgb = self.cv_bridge.imgmsg_to_cv2(self.current_rgb, "rgb8")
rgb = np.array(rgb, dtype=float)
if self.sensor_noise != 0:
noise = np.random.normal(0.0, self.sensor_noise, rgb.shape)
rgb += noise
if self.camera_type == "rgb_camera":
depth = None
elif self.camera_type == "rgbd_camera":
depth = self.cv_bridge.imgmsg_to_cv2(self.current_depth, "32FC1")
return np.asarray(rgb), np.asarray(depth)
| 2,869 | 33.166667 | 77 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/utils.py | from scipy.spatial.transform import Rotation as R
import cv2
import numpy as np
import json
# from rembg import remove
import os
import imageio
def get_roi_mask(rgb):
"""binary mask for ROIs using color thresholding"""
hsv = cv2.cvtColor(np.array(rgb, dtype=np.uint8), cv2.COLOR_RGB2HSV)
lower_red = np.array([0, 50, 50])
upper_red = np.array([20, 255, 255])
mask0 = cv2.inRange(hsv, lower_red, upper_red)
lower_red = np.array([160, 50, 50])
upper_red = np.array([180, 255, 255])
mask1 = cv2.inRange(hsv, lower_red, upper_red)
mask = mask0 + mask1
mask = mask + 1e-5
return mask
def get_black_mask(rgb):
"""binary mask for ROIs using color thresholding"""
lower_black = np.array([250, 250, 250])
upper_black = np.array([255, 255, 255])
mask = cv2.inRange(rgb, lower_black, upper_black)
return mask
def visualize_uncertainty(uncertainty):
variance = np.exp(uncertainty)
def rotation_2_quaternion(rotation_matrix):
r = R.from_matrix(rotation_matrix)
return r.as_quat()
def xyz_to_view(xyz, radius):
phi = np.arcsin(xyz[2] / radius) # phi from 0 to 0.5*pi
theta = np.arctan2(xyz[1], xyz[0]) % (2 * np.pi) # theta from 0 to 2*pi
return [phi, theta]
def view_to_pose(view, radius):
phi, theta = view
# phi should be within [min_phi, 0.5*np.pi)
if phi >= 0.5 * np.pi:
phi = np.pi - phi
pose = np.eye(4)
x = radius * np.cos(theta) * np.cos(phi)
y = radius * np.sin(theta) * np.cos(phi)
z = radius * np.sin(phi)
translation = np.array([x, y, z])
rotation = R.from_euler("ZYZ", [theta, -phi, np.pi]).as_matrix()
pose[:3, -1] = translation
pose[:3, :3] = rotation
return pose
def view_to_pose_batch(views, radius):
num = len(views)
phi = views[:, 0]
theta = views[:, 1]
# phi should be within [min_phi, 0.5*np.pi)
index = phi >= 0.5 * np.pi
phi[index] = np.pi - phi[index]
poses = np.broadcast_to(np.identity(4), (num, 4, 4)).copy()
x = radius * np.cos(theta) * np.cos(phi)
y = radius * np.sin(theta) * np.cos(phi)
z = radius * np.sin(phi)
translations = np.stack((x, y, z), axis=-1)
angles = np.stack((theta, -phi, np.pi * np.ones(num)), axis=-1)
rotations = R.from_euler("ZYZ", angles).as_matrix()
poses[:, :3, -1] = translations
poses[:, :3, :3] = rotations
return poses
def random_view(current_xyz, radius, phi_min, min_view_change, max_view_change):
"""
random scatter view direction changes by given current position and view change range.
"""
u = current_xyz / np.linalg.norm(current_xyz)
# pick a random vector:
r = np.random.multivariate_normal(np.zeros_like(u), np.eye(len(u)))
# form a vector perpendicular to u:
uperp = r - r.dot(u) * u
uperp = uperp / np.linalg.norm(uperp)
# random view angle change in radian
random_view_change = np.random.uniform(low=min_view_change, high=max_view_change)
cosine = np.cos(random_view_change)
w = cosine * u + np.sqrt(1 - cosine**2 + 1e-8) * uperp
w = radius * w / np.linalg.norm(w)
view = xyz_to_view(w, radius)
if view[0] < phi_min:
view[0] = phi_min
return view
def uniform_sampling(radius, phi_min):
"""
uniformly generate unit vector on hemisphere.
then calculate corresponding view direction targeting coordinate origin.
"""
xyz = np.array([0.0, 0.0, 0.0])
# avoid numerical error
while np.linalg.norm(xyz) < 0.001:
xyz[0] = np.random.uniform(low=-1.0, high=1.0)
xyz[1] = np.random.uniform(low=-1.0, high=1.0)
xyz[2] = np.random.uniform(low=0.0, high=1.0)
xyz = radius * xyz / np.linalg.norm(xyz)
view = xyz_to_view(xyz, radius)
if view[0] < phi_min:
view[0] = phi_min
return view
def focal_len_to_fov(focal, resolution):
"""
calculate FoV based on given focal length adn image resolution
Args:
focal: [fx, fy]
resolution: [W, H]
Returns:
FoV: [HFoV, VFoV]
"""
focal = np.asarray(focal)
resolution = np.asarray(resolution)
return 2 * np.arctan(0.5 * resolution / focal)
def mask_out_background(image_path):
"""remove background"""
rgb = imageio.imread(image_path)
masked_rgb = remove(rgb)
# H, W, _ = rgb.shape
# masked_rgb = np.ones((H, W, 4)) * 255
# masked_rgb[..., :3] = rgb
# mask_white = rgb >= np.array([254, 254, 254])
# mask_white = np.all(mask_white, axis=-1)
# mask_black = rgb <= np.array([1, 1, 1])
# mask_black = np.all(mask_black, axis=-1)
# masked_rgb[mask_white] = [0, 0, 0, 0]
# masked_rgb[mask_black] = [0, 0, 0, 0]
return masked_rgb
def record_render_data(path, camera_info, trajectory, use_masked_image=False):
transformation = np.array(
[[0, 0, -1, 0], [-1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1]]
) # transform gazebo coordinate to opengl format
opencv_trajectory = np.empty(trajectory.shape)
for i, pose in enumerate(trajectory):
opencv_trajectory[i] = pose @ transformation
resolution = camera_info["image_resolution"]
c = camera_info["c"]
focal = camera_info["focal"]
fov = focal_len_to_fov(focal, resolution)
record_dict = {}
record_dict["camera_angle_x"] = fov[0]
record_dict["camera_angle_y"] = fov[1]
record_dict["fl_x"] = focal[0]
record_dict["fl_y"] = focal[1]
record_dict["k1"] = 0.000001
record_dict["k2"] = 0.000001
record_dict["p1"] = 0.000001
record_dict["p2"] = 0.000001
record_dict["cx"] = c[0]
record_dict["cy"] = c[1]
record_dict["w"] = resolution[0]
record_dict["h"] = resolution[1]
record_dict["frames"] = []
record_dict["scale"] = 1.0
record_dict["aabb_scale"] = 2.0
for i, pose in enumerate(opencv_trajectory):
image_file = f"images/{i+1:04d}.png"
image_path = os.path.join(path, image_file)
if use_masked_image:
masked_image = mask_out_background(image_path)
image_file = f"images/masked_{i+1:04d}.png"
image_path = os.path.join(path, image_file)
imageio.imwrite(image_path, masked_image)
data_frame = {
"file_path": image_file,
# "sharpness": 30.0,
"transform_matrix": pose.tolist(),
}
record_dict["frames"].append(data_frame)
with open(f"{path}/transforms.json", "w") as f:
json.dump(record_dict, f, indent=4)
# for test only
# for i, pose in enumerate(opencv_trajectory[50:]):
# data_frame = {
# "file_path": f"images/{i+51:04d}.jpg",
# "sharpness": 30.0,
# "transform_matrix": pose.tolist(),
# }
# record_dict["frames"].append(data_frame)
# with open(f"{path}/test_transforms.json", "w") as f:
# json.dump(record_dict, f, indent=4)
def test():
view = []
# for i in range(5):
# new_view = uniform_sampling(2, 0.15)
# view.append(new_view)
# print("view:", new_view)
current_xyz = [0, 0, 2]
for i in range(500):
local = random_view(current_xyz, 2, 0.15, 0.2, 1.05)
view.append(local)
xyz_list = view_to_pose_batch(np.array(view), 2)[..., :3, 3]
print(xyz_list)
for xyz in xyz_list:
view = xyz_to_view(xyz, 2)
print(view)
fig = plt.figure()
ax = fig.add_subplot(projection="3d")
ax.scatter(xyz_list[..., 0], xyz_list[..., 1], xyz_list[..., 2])
ax.set_xlabel("X Label")
ax.set_ylabel("Y Label")
ax.set_zlabel("Z Label")
ax.set_zlim(0, 2.5)
ax.set_xlim(-2.5, 2.5)
ax.set_ylim(-2.5, 2.5)
plt.show()
if __name__ == "__main__":
import matplotlib.pyplot as plt
test()
| 7,770 | 26.459364 | 90 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/planner.py | from .simulator_bridge import SimulatorBridge
from . import utils
import time
import os
from datetime import datetime
import numpy as np
import imageio.v2 as imageio
import yaml
class Planner:
def __init__(self, cfg):
self.simulator_bridge = SimulatorBridge(cfg["simulation_bridge"])
self.camera_info = self.simulator_bridge.camera_info
self.record_path = os.path.join(
cfg["experiment_path"], cfg["planner_type"], str(cfg["experiment_id"])
)
self.planning_budget = cfg["planning_budget"]
self.initial_type = cfg["initial_type"]
self.H, self.W = self.camera_info[
"image_resolution"
] # original image resolution from simulator
self.trajectory = np.empty((self.planning_budget, 4, 4))
self.view_trajectory = np.empty((self.planning_budget, 2)) # [phi, theta]
self.rgb_measurements = np.empty((self.planning_budget, self.H, self.W, 3))
self.depth_measurements = np.empty((self.planning_budget, self.H, self.W))
self.step = 0
self.config_actionspace(cfg["action_space"])
def config_actionspace(self, cfg):
"""set hemisphere actionspace parameters"""
self.min_height = cfg["min_height"]
self.radius = cfg["radius"]
self.phi_min = np.arcsin(self.min_height / self.radius)
self.phi_max = 0.5 * np.pi
self.theta_min = 0
self.theta_max = 2 * np.pi
def init_camera_pose(self, initial_view):
print("------ start mission ------ \n")
print("------ initialize camera pose ------ \n")
if initial_view is None:
if self.initial_type == "random":
initial_view = utils.uniform_sampling(self.radius, self.phi_min)
elif self.initial_type == "pre_calculated":
self.get_view_list()
initial_view = next(self.view_list)
self.move_sensor(initial_view)
else:
for view in initial_view:
self.move_sensor(view)
def start(self, initial_view=None):
self.init_camera_pose(initial_view)
while self.step < self.planning_budget:
next_view = self.plan_next_view()
self.move_sensor(next_view)
self.record_experiment()
print("------ complete mission ------\n")
# rospy.signal_shutdown("shut down ros node")
def move_sensor(self, view):
pose = utils.view_to_pose(view, self.radius)
self.simulator_bridge.move_camera(pose)
self.current_view = view
self.current_pose = pose
print(pose)
print(
f"------ reach given pose and take measurement No.{self.step + 1} ------\n"
)
time.sleep(1) # lazy solution to make sure we receive correct images
rgb, depth = self.simulator_bridge.get_image()
self.record_step(view, pose, rgb, depth)
self.step += 1
def plan_next_view(self):
raise NotImplementedError("plan_next_view method is not implemented")
def record_experiment(self):
print("------ record experiment data ------\n")
os.makedirs(self.record_path, exist_ok=True)
images_path = os.path.join(self.record_path, "images")
os.mkdir(images_path)
depths_path = os.path.join(self.record_path, "depths")
os.mkdir(depths_path)
for i, rgb in enumerate(self.rgb_measurements):
imageio.imwrite(
f"{images_path}/{i+1:04d}.png", (rgb * 255).astype(np.uint8)
)
if len(self.depth_measurements) > 0:
for i, depth in enumerate(self.depth_measurements):
with open(f"{depths_path}/depth_{i+1:04d}.npy", "wb") as f:
depth_array = np.array(depth, dtype=np.float32)
np.save(f, depth_array)
with open(f"{self.record_path}/trajectory.npy", "wb") as f:
np.save(f, self.trajectory)
with open(f"{self.record_path}/camera_info.yaml", "w") as f:
yaml.safe_dump(self.camera_info, f)
# record json data required for instant-ngp training
utils.record_render_data(self.record_path, self.camera_info, self.trajectory)
def record_step(self, view, pose, rgb, depth):
self.record_trajectory(view, pose)
self.record_rgb_measurement(rgb)
if depth is not None:
self.record_depth_measurement(depth)
def record_rgb_measurement(self, rgb):
rgb = np.clip(rgb, a_min=0, a_max=255)
rgb = rgb / 255
self.rgb_measurements[self.step] = rgb
def record_depth_measurement(self, depth):
self.depth_measurements[self.step] = depth
def record_trajectory(self, view, pose):
self.view_trajectory[self.step] = view
self.trajectory[self.step] = pose
| 4,844 | 34.364964 | 87 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/neural_nbv/neural_nbv_planner.py | import numpy as np
from scipy.spatial.transform import Rotation as R
from planner.planner import Planner
from planner.utils import view_to_pose_batch, random_view, uniform_sampling
from neural_rendering.evaluation.pretrained_model import PretrainedModel
import torch
from dotmap import DotMap
from neural_rendering.utils import util
import torch.nn.functional as F
import scipy.spatial as spatial
import matplotlib.pyplot as plt
import time
import yaml
import os
class NeuralNBVPlanner(Planner):
def __init__(self, cfg):
super().__init__(cfg)
self.device = cfg["device"]
self.gpu_id = list(map(int, cfg["gpu_id"].split()))
self.init_sensor_model(cfg)
self.image_to_tensor = util.get_image_to_tensor_balanced()
self.num_candidates = cfg["num_candidates"]
self.sample_type = cfg["sample_type"]
self.view_change = cfg["view_change"]
self.local_view_change = cfg["local_view_change"]
self.selection_range = cfg["selection_range"]
self.hierachical_sampling = cfg["use_hierachical_sampling"]
self.sample_ratio = cfg["sample_ratio"]
self.K = cfg["top_k"]
self.max_ref_num = cfg["maximal_ref"]
self.reward_type = cfg["reward_type"]
self.render_batch_size = cfg["render_batch_size"]
self.uncertainty_th = cfg["uncertainty_threshold"]
self.candidate_views = None
self.candidate_poses = None
self.render_pairs = None
self.trajectory_kdtree = None
# self.depth_for_renderer = torch.empty(
# (self.planning_budget, self.H, self.W)
# ).to(self.device)
def init_sensor_model(self, cfg):
assert os.path.exists(cfg["config_path"])
assert os.path.exists(cfg["checkpoint_path"])
with open(cfg["config_path"], "r") as config_file:
model_cfg = yaml.safe_load(config_file)["model"]
ckpt_file = torch.load(cfg["checkpoint_path"])
self.model = PretrainedModel(model_cfg, ckpt_file, self.device, self.gpu_id)
# original image format
H, W = self.camera_info["image_resolution"] # (H, W)
focal = self.camera_info["focal"] # (f_x, f_y)
c = self.camera_info["c"] # (c_x, c_y)
# desired image format for redendering input
render_info = cfg["render_info"]
H_ref, W_ref = render_info["ref_image_resolution"]
ref_focal = [0, 0]
ref_c = [0, 0]
if np.any([H, W] != [H_ref, W_ref]):
scale_h = H_ref / H
scale_w = W_ref / W
ref_focal[0] = scale_w * focal[0]
ref_focal[1] = scale_h * focal[1]
ref_c[0] = scale_w * c[0]
ref_c[1] = scale_h * c[1]
self.ref_focal = torch.tensor(ref_focal, dtype=torch.float32).to(self.device)
self.ref_c = torch.tensor(ref_c, dtype=torch.float32).to(self.device)
self.ref_image_resolution = (H_ref, W_ref)
self.trajectory_for_renderer = torch.empty((self.planning_budget, 4, 4)).to(
self.device
)
self.rgb_for_renderer = torch.empty((self.planning_budget, 3, H_ref, W_ref)).to(
self.device
)
# desired image format for redendering output
render_scale = render_info["render_scale"]
self.H_render = int(render_scale * H_ref)
self.W_render = int(render_scale * W_ref)
render_scale = torch.tensor(
[
self.W_render / W_ref,
self.H_render / H_ref,
]
).to(self.device)
self.render_focal = render_scale * self.ref_focal
self.render_c = render_scale * self.ref_c
self.z_near, self.z_far = render_info["scene_range"]
def render_novel_views(self, candidate_poses):
candidate_num = len(candidate_poses)
reward_list = np.zeros(candidate_num)
distance_all, ref_index_all = self.trajectory_kdtree.query(
candidate_poses[:, :3, 3], np.minimum(self.max_ref_num, self.step)
)
# distance_all = torch.tensor(distance_all)
# ref_index_all = torch.tensor(ref_index_all)
bool_mask = ~np.isinf(distance_all)
novel_poses = util.coordinate_transformation(
candidate_poses, format="normal"
).to(self.device)
# render novel view in batch
split_novel_view = torch.split(
torch.arange(candidate_num), self.render_batch_size, dim=0
)
for i in split_novel_view:
ref_index = torch.tensor(ref_index_all[i] * bool_mask[i])
ref_images = self.rgb_for_renderer[ref_index]
ref_poses = self.trajectory_for_renderer[ref_index]
render_results = self.rendering(ref_images, ref_poses, novel_poses[i])
reward_list[i] = self.cal_reward(render_results)
return reward_list
def rendering(self, ref_images, ref_poses, novel_poses):
NP = len(novel_poses)
with torch.no_grad():
self.model.network.encode(
ref_images,
ref_poses,
self.ref_focal.unsqueeze(0),
self.ref_c.unsqueeze(0),
)
target_rays = util.gen_rays(
novel_poses,
self.W_render,
self.H_render,
self.render_focal,
self.z_near,
self.z_far,
self.render_c,
) # (IN, H, W, 8)
target_rays = target_rays.reshape(NP, self.H_render * self.W_render, -1)
predict = DotMap(self.model.renderer_par(target_rays))
return predict
def cal_reward(self, render_results):
uncertainty = render_results["uncertainty"]
reward = torch.mean(uncertainty**2, dim=-1).cpu().numpy()
reward = np.log10(reward)
return reward
# one stage planning
def start_planning(self):
candidate_views, candidate_poses = self.local_sampling(
self.num_candidates, self.current_pose[:3, 3], view_change=self.view_change
)
reward_list = self.render_novel_views(candidate_poses)
nbv_index = np.argmax(reward_list)
return candidate_views[nbv_index]
def global_sampling(self, num):
view_list = np.empty((num, 2))
for i in range(num):
view_list[i] = uniform_sampling(self.radius, self.phi_min)
pose_list = view_to_pose_batch(view_list, self.radius)
return view_list, pose_list
def local_sampling(self, num, xyz, view_change, min_view_change=0.2):
view_list = np.empty((num, 2))
for i in range(num):
view_list[i] = random_view(
xyz, self.radius, self.phi_min, min_view_change, view_change
)
pose_list = view_to_pose_batch(view_list, self.radius)
return view_list, pose_list
def plan_next_view(self):
import time
if self.step > 1:
t1 = time.time()
nbv = self.start_planning()
t2 = time.time()
print((t2 - t1))
return nbv
# need at least two views to start the planning
else:
random_next_view = random_view(
self.current_pose[:3, 3],
self.radius,
self.phi_min,
self.view_change - 0.1,
self.view_change,
)
return random_next_view
def record_trajectory(self, view, pose):
self.view_trajectory[self.step] = view
self.trajectory[self.step] = pose
# maintain current measurment positions in kd tree
self.trajectory_kdtree = spatial.KDTree(self.trajectory[: self.step + 1, :3, 3])
self.trajectory_for_renderer[self.step] = util.coordinate_transformation(
pose, format="normal"
).to(self.device)
def record_rgb_measurement(self, rgb):
rgb = np.clip(rgb, a_min=0, a_max=255)
rgb = rgb / 255
self.rgb_measurements[self.step] = rgb
ref_image = self.image_to_tensor(rgb).to(self.device)
ref_image = F.interpolate(
ref_image.unsqueeze(0), size=self.ref_image_resolution, mode="area"
).squeeze(0)
self.rgb_for_renderer[self.step] = ref_image
def test_visualize(self, ref_images, results_dict):
import matplotlib.pyplot as plt
H = 60
W = 60
for i in range(self.render_batch_size):
rgb = results_dict.rgb[i].cpu().numpy().reshape(H, W, 3)
depth = results_dict.depth[i].cpu().numpy().reshape(H, W)
uncertainty = results_dict.uncertainty[i].cpu().numpy().reshape(H, W)
fig, axs = plt.subplots(1, 3)
axs[0].imshow(rgb)
axs[1].imshow(uncertainty)
axs[2].imshow(depth)
plt.show()
| 8,864 | 33.901575 | 88 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/baselines/random_planner.py | from planner.planner import Planner
from planner.utils import random_view, uniform_sampling
import numpy as np
class RandomPlanner(Planner):
def __init__(self, cfg):
super().__init__(cfg)
print("initial ")
self.num_candidates = cfg["num_candidates"]
self.view_change = cfg["view_change"]
self.planning_type = cfg["planning_type"]
def plan_next_view(self):
view_list = np.empty((self.num_candidates, 2))
if self.planning_type == "local":
for i in range(self.num_candidates):
view_list[i] = random_view(
self.current_pose[:3, 3],
self.radius,
self.phi_min,
min_view_change=0.2,
max_view_change=self.view_change,
)
elif self.planning_type == "global":
for i in range(self.num_candidates):
view_list[i] = uniform_sampling(self.radius, self.phi_min)
nbv_index = np.random.choice(len(view_list))
nbv = view_list[nbv_index]
return nbv
| 1,101 | 32.393939 | 74 | py |
neu-nbv | neu-nbv-main/scripts/planning/planner/baselines/max_distance_planner.py | from planner.planner import Planner
from planner.utils import view_to_pose_batch, random_view, uniform_sampling
import numpy as np
from scipy.spatial import distance
class MaxDistancePlanner(Planner):
def __init__(self, cfg):
super().__init__(cfg)
self.num_candidates = cfg["num_candidates"]
self.view_change = cfg["view_change"]
self.planning_type = cfg["planning_type"]
def get_camera_view_direction(self, poses):
view_direction = poses[..., :3, 0]
view_direction = view_direction / np.linalg.norm(view_direction)
return view_direction
def plan_next_view(self):
view_list = np.empty((self.num_candidates, 2))
if self.planning_type == "local":
for i in range(self.num_candidates):
view_list[i] = random_view(
self.current_pose[:3, 3],
self.radius,
self.phi_min,
min_view_change=0.2,
max_view_change=self.view_change,
)
elif self.planning_type == "global":
for i in range(self.num_candidates):
view_list[i] = uniform_sampling(self.radius, self.phi_min)
pose_list = view_to_pose_batch(view_list, self.radius)
new_view_list = self.get_camera_view_direction(pose_list)
reference_pose_list = self.trajectory[: self.step]
reference_view_list = self.get_camera_view_direction(reference_pose_list)
dist_list = []
for view in new_view_list:
dist = 0
count = 0
for ref_view in reference_view_list:
# print(view, ref_view)
cos_dist = distance.cosine(view, ref_view)
if cos_dist < 0.6:
dist += cos_dist
count += 1
# print(dist)
dist_list.append(dist / count)
nbv = view_list[np.argmax(dist_list)]
return nbv
| 1,982 | 34.410714 | 81 | py |
neu-nbv | neu-nbv-main/scripts/utils/plot.py | import seaborn as sb
import matplotlib.pyplot as plt
import pandas
import os
import argparse
from matplotlib.ticker import FormatStrFormatter
from matplotlib.ticker import MaxNLocator
from matplotlib import rc
PLOT_FONT_SIZE = 22
PLOT_LEGEND_SIZE = 18
PLOT_TICKS_SIZE = 18
PLOT_LINE_WIDTH = 4
plt.rcParams["figure.figsize"] = [12, 8]
plt.rcParams["figure.autolayout"] = True
sb.set_palette("bright")
def main():
args = plot_args()
dataframe_path = args.dataframe_path
os.path.exists(dataframe_path), "dataframe does not exist!"
plot(dataframe_path)
def plot(dataframe_path):
# DTU experiment plot
save_path = os.path.dirname(dataframe_path)
total_df = pandas.read_csv(dataframe_path)
fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True)
sb.lineplot(
total_df,
x="Reference Image Number",
y="PSNR",
hue="Planning Type",
linewidth=PLOT_LINE_WIDTH,
ax=ax1,
errorbar=("sd", 1),
palette=["C2", "C0", "C3"],
)
ax1.set_ylabel("PSNR", fontsize=PLOT_FONT_SIZE)
ax1.set_xlabel("Number of collected images", fontsize=PLOT_FONT_SIZE)
ax1.yaxis.set_major_formatter(FormatStrFormatter("%.1f"))
ax1.yaxis.set_major_locator(MaxNLocator(nbins=4))
ax1.tick_params(axis="both", labelsize=PLOT_TICKS_SIZE)
handles, labels = ax1.get_legend_handles_labels()
order = [2, 0, 1]
ax1.legend(
[handles[idx] for idx in order],
[labels[idx] for idx in order],
loc="lower right",
fontsize=PLOT_LEGEND_SIZE,
frameon=False,
)
sb.lineplot(
total_df,
x="Reference Image Number",
y="SSIM",
hue="Planning Type",
linewidth=PLOT_LINE_WIDTH,
ax=ax2,
errorbar=("sd", 1),
palette=["C2", "C0", "C3"],
)
ax2.set_xlabel("Number of collected images", fontsize=PLOT_FONT_SIZE)
ax2.set_ylabel("SSIM", fontsize=PLOT_FONT_SIZE)
ax2.yaxis.set_major_formatter(FormatStrFormatter("%.2f"))
ax2.yaxis.set_major_locator(MaxNLocator(nbins=4))
ax2.get_legend().remove()
ax2.tick_params(axis="both", labelsize=PLOT_TICKS_SIZE)
plt.xticks([2, 3, 4, 5, 6, 7, 8, 9])
plt.savefig(f"{save_path}/plot_results.svg", bbox_inches="tight")
plt.clf()
def plot_args():
# mandatory arguments
args = None
parser = argparse.ArgumentParser()
parser.add_argument(
"--dataframe_path",
type=str,
required=True,
help="path to dataframe",
)
args = parser.parse_args()
return args
if __name__ == "__main__":
main()
# # gazebo car experiment plot
# total_df = pandas.read_csv("dataframe/experiment_gazebo_car_0.csv")
# total_df = total_df.append(pandas.read_csv("dataframe/experiment_gazebo_car_1.csv"))
# fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True)
# sb.lineplot(
# total_df,
# x="Reference Image Num.",
# y="PSNR",
# hue="Planning Type",
# linewidth=PLOT_LINE_WIDTH,
# ax=ax1,
# errorbar=("sd", 1),
# palette=["C2", "C0", "C3"],
# )
# ax1.set_xlabel("Number of collected images", fontsize=PLOT_FONT_SIZE)
# ax1.set_ylabel("PSNR", fontsize=PLOT_FONT_SIZE)
# ax1.yaxis.set_major_formatter(FormatStrFormatter("%.1f"))
# ax1.yaxis.set_major_locator(MaxNLocator(nbins=4))
# # ax1.tick_params(labelsize=PLOT_TICKS_SIZE)
# ax1.legend(loc="lower right", fontsize=PLOT_FONT_SIZE)
# ax1.tick_params(axis="both", labelsize=PLOT_TICKS_SIZE)
# handles, labels = ax1.get_legend_handles_labels()
# order = [2, 0, 1]
# ax1.legend(
# [handles[idx] for idx in order],
# [labels[idx] for idx in order],
# loc="lower right",
# fontsize=PLOT_LEGEND_SIZE,
# frameon=False,
# )
# sb.lineplot(
# total_df,
# x="Reference Image Num.",
# y="SSIM",
# hue="Planning Type",
# linewidth=PLOT_LINE_WIDTH,
# ax=ax2,
# errorbar=("sd", 1),
# palette=["C2", "C0", "C3"],
# )
# ax2.set_xlabel("Number of collected images", fontsize=PLOT_FONT_SIZE)
# plt.xticks([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
# ax2.set_ylabel("SSIM", fontsize=PLOT_FONT_SIZE)
# ax2.yaxis.set_major_formatter(FormatStrFormatter("%.2f"))
# ax2.yaxis.set_major_locator(MaxNLocator(nbins=4))
# ax2.get_legend().remove()
# ax2.tick_params(axis="both", labelsize=PLOT_TICKS_SIZE)
# # ax2.tick_params(labelsize=PLOT_TICKS_SIZE)
# # plt.show()
# plt.xticks(fontsize=PLOT_TICKS_SIZE)
# plt.yticks(fontsize=PLOT_TICKS_SIZE)
# plt.savefig("dataframe/gazebo_car.svg", bbox_inches="tight")
# plt.clf()
# # # gazebo indoor experiment plot
# total_df = pandas.read_csv("dataframe/experiment_gazebo_indoor_0.csv")
# total_df = total_df.append(pandas.read_csv("dataframe/experiment_gazebo_indoor_1.csv"))
# fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True)
# sb.lineplot(
# total_df,
# x="Reference Image Num.",
# y="PSNR",
# hue="Planning Type",
# linewidth=PLOT_LINE_WIDTH,
# ax=ax1,
# errorbar=("sd", 1),
# palette=["C2", "C0", "C3"],
# )
# ax1.set_ylabel("PSNR", fontsize=PLOT_FONT_SIZE)
# ax1.set_xlabel("Number of collected images", fontsize=PLOT_FONT_SIZE)
# ax1.yaxis.set_major_formatter(FormatStrFormatter("%.1f"))
# ax1.set_yticks([13.4, 14.6, 15.8, 17.0])
# # ax1.yaxis.set_major_locator(MaxNLocator(nbins=5))
# ax1.tick_params(axis="both", labelsize=PLOT_TICKS_SIZE)
# # ax1.tick_params(labelsize=PLOT_TICKS_SIZE)
# ax1.legend(loc="lower right", fontsize=PLOT_FONT_SIZE)
# handles, labels = ax1.get_legend_handles_labels()
# order = [2, 0, 1]
# ax1.legend(
# [handles[idx] for idx in order],
# [labels[idx] for idx in order],
# loc="lower right",
# fontsize=PLOT_LEGEND_SIZE,
# frameon=False,
# )
# sb.lineplot(
# total_df,
# x="Reference Image Num.",
# y="SSIM",
# hue="Planning Type",
# linewidth=PLOT_LINE_WIDTH,
# ax=ax2,
# errorbar=("sd", 1),
# palette=["C2", "C0", "C3"],
# )
# ax2.set_xlabel("Number of collected images", fontsize=PLOT_FONT_SIZE)
# ax2.set_ylabel("SSIM", fontsize=PLOT_FONT_SIZE)
# ax2.yaxis.set_major_formatter(FormatStrFormatter("%.2f"))
# ax2.yaxis.set_major_locator(MaxNLocator(nbins=4))
# ax2.get_legend().remove()
# ax2.tick_params(axis="both", labelsize=PLOT_TICKS_SIZE)
# # ax2.tick_params(labelsize=PLOT_TICKS_SIZE)
# # plt.show()
# plt.xticks([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
# plt.xticks(fontsize=PLOT_TICKS_SIZE)
# plt.yticks(fontsize=PLOT_TICKS_SIZE)
# plt.savefig("dataframe/gazebo_indoor.svg", bbox_inches="tight")
# plt.clf()
| 6,469 | 29.518868 | 89 | py |
PolSF | PolSF-master/label2dto3d.py | import numpy as np
from skimage import io
from scipy import misc
# SF-ALOS2
# https://www.ietr.fr/polsarpro-bio/san-francisco/dataset/SAN_FRANCISCO_ALOS2.zip
# color = [[0,0,0],[132,112,255],[0,0,255],[0,255,0],[192,0,0],[0,255,255],[255,255,0]]
## 0, unlabel, 1,Montain,2,Water,3,Vegetation,4,High-Density Urban,5,Low-Density Urban,6,Developd
# SF-GF3
# https://www.ietr.fr/polsarpro-bio/san-francisco/dataset/SAN_FRANCISCO_GF3.zip
# color = [[0,0,0],[132,112,255],[0,0,255],[0,255,0],[192,0,0],[0,255,255],[255,255,0]]
## 0, unlabel, 1,Montain,2,Water,3,Vegetation,4,High-Density Urban,5,Low-Density Urban,6,Developd
# SF-RISAT
# https://www.ietr.fr/polsarpro-bio/san-francisco/dataset/SAN_FRANCISCO_RISAT.zip
# color = [[0,0,0],[132,112,255],[0,0,255],[0,255,0],[192,0,0],[0,255,255],[255,255,0]]
## 0, unlabel, 1,Montain,2,Water,3,Vegetation,4,High-Density Urban,5,Low-Density Urban,6,Developd
# SF-RS2
# https://www.ietr.fr/polsarpro-bio/san-francisco/dataset/SAN_FRANCISCO_RS2.zip
# color = [[0,0,0], [0,0,255],[0,255,0],[255,0,0],[255,255,0],[255,0,255]]
## 0, unlabel, 1,Water,2,Vegetation,3,High-Density Urban,4,Low-Density Urban,5,Developd
# SF-AIRSAR
# https://www.ietr.fr/polsarpro-bio/san-francisco/dataset/SAN_FRANCISCO_AIRSAR.zip
color = [[0,0,0], [0,255,255],[255,255,0],[0,0,255],[255,0,0],[0,255,0]]
## 0, unlabel, 1,Montain,2,Water,3,Urban,4,Vegetation ,5, Bare soil
# label_files = '/home/bidlc/labelposar/PolSF/SF-AIRSAR/SF-AIRSAR-label2d.png'
datanameall = ['SF-AIRSAR','SF-AIRSAR','SF-AIRSAR','SF-AIRSAR','SF-AIRSAR']
dataname = datanameall[4]
label_files = './'+dataname+'/'+dataname+'-label2d.png'
label = io.imread(label_files)
mm = label.shape[0]
nn = label.shape[1]
label3d = np.zeros([mm, nn, 3])
for j in range(mm):
for k in range(nn):
print(j,k)
label3d[j][k]=color[int(label[j][k])]
misc.imsave('/home/bidlc/labelposar/PolSF/'+dataname+'/'+dataname+'-label3d-test.png', label3d) | 2,153 | 45.826087 | 97 | py |
MP-FedXGB | MP-FedXGB-main/VerticalXGBoost.py | import numpy as np
import pandas as pd
from mpi4py import MPI
from datetime import *
from SSCalculation import *
from Tree import *
import math
import time
np.random.seed(10)
clientNum = 4
class LeastSquareLoss:
def gradient(self, actual, predicted):
return -(actual - predicted)
def hess(self, actual, predicted):
return np.ones_like(actual)
class LogLoss():
def gradient(self, actual, predicted):
prob = 1.0 / (1.0 + np.exp(-predicted))
return prob - actual
def hess(self, actual, predicted):
prob = 1.0 / (1.0 + np.exp(-predicted))
return prob * (1.0 - prob) # Mind the dimension
class VerticalXGBoostClassifier:
def __init__(self, rank, lossfunc, splitclass, _lambda=1, _gamma=0.5, _epsilon=0.1, n_estimators=3, max_depth=3):
if lossfunc == 'LogLoss':
self.loss = LogLoss()
else:
self.loss = LeastSquareLoss()
self._lambda = _lambda
self._gamma = _gamma
self._epsilon = _epsilon
self.n_estimators = n_estimators # Number of trees
self.max_depth = max_depth # Maximum depth for tree
self.rank = rank
self.trees = []
self.splitclass = splitclass
for _ in range(n_estimators):
tree = VerticalXGBoostTree(rank=self.rank,
lossfunc=self.loss,
splitclass=self.splitclass,
_lambda=self._lambda,
_gamma=self._gamma,
_epsilon=self._epsilon,
_maxdepth=self.max_depth,
clientNum=clientNum)
self.trees.append(tree)
def getQuantile(self, colidx):
split_list = []
if self.rank != 0: # For client nodes
data = self.data.copy()
idx = np.argsort(data[:, colidx], axis=0)
data = data[idx]
value_list = sorted(list(set(list(data[:, colidx])))) # Record all the different value
hess = np.ones_like(data[:, colidx])
data = np.concatenate((data, hess.reshape(-1, 1)), axis=1)
sum_hess = np.sum(hess)
last = value_list[0]
i = 1
if len(value_list) == 1: # For those who has only one value, do such process.
last_cursor = last
else:
last_cursor = value_list[1]
split_list.append((-np.inf, value_list[0]))
# if len(value_list) == 15000:
# print(self.rank, colidx)
# print(value_list)
while i < len(value_list):
cursor = value_list[i]
small_hess = np.sum(data[:, -1][data[:, colidx] <= last]) / sum_hess
big_hess = np.sum(data[:, -1][data[:, colidx] <= cursor]) / sum_hess
# print(colidx, self.rank, np.abs(big_hess - small_hess), last, cursor)
if np.abs(big_hess - small_hess) < self._epsilon:
last_cursor = cursor
else:
judge = value_list.index(cursor) - value_list.index(last)
if judge == 1: # Although it didn't satisfy the criterion, it has no more split, so we must add it.
split_list.append((last, cursor))
last = cursor
else: # Move forward and record the last.
split_list.append((last, last_cursor))
last = last_cursor
last_cursor = cursor
i += 1
if split_list[-1][1] != value_list[-1]:
split_list.append((split_list[-1][1], value_list[-1])) # Add the top value into split_list.
split_list = np.array(split_list)
return split_list
def getAllQuantile(self): # Global quantile, must be calculated before tree building, avoiding recursion.
self_maxlen = 0
if self.rank != 0:
dict = {i:self.getQuantile(i) for i in range(self.data.shape[1])} # record all the split
self_maxlen = max([len(dict[i]) for i in dict.keys()])
else:
dict = {}
recv_maxlen = comm.gather(self_maxlen, root=1)
maxlen = None
if self.rank == 1:
maxlen = max(recv_maxlen)
self.maxSplitNum = comm.bcast(maxlen, root=1)
# print('MaxSplitNum: ', self.maxSplitNum)
self.quantile = dict
def fit(self, X, y):
data_num = X.shape[0]
y = np.reshape(y, (data_num, 1))
y_pred = np.zeros(np.shape(y))
self.data = X.copy()
self.getAllQuantile()
for i in range(self.n_estimators):
# print('In classifier fit, rank: ', self.rank)
tree = self.trees[i]
tree.data, tree.maxSplitNum, tree.quantile = self.data, self.maxSplitNum, self.quantile
y_and_pred = np.concatenate((y, y_pred), axis=1)
tree.fit(y_and_pred, i)
if i == self.n_estimators - 1: # The last tree, no need for prediction update.
continue
else:
update_pred = tree.predict(X)
if self.rank == 1:
# print('test')
update_pred = np.reshape(update_pred, (data_num, 1))
y_pred += update_pred
def predict(self, X):
y_pred = None
data_num = X.shape[0]
# Make predictions
for tree in self.trees:
# Estimate gradient and update prediction
update_pred = tree.predict(X)
if y_pred is None:
y_pred = np.zeros_like(update_pred).reshape(data_num, -1)
if self.rank == 1:
update_pred = np.reshape(update_pred, (data_num, 1))
y_pred += update_pred
return y_pred
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
def main1():
data = pd.read_csv('./iris.csv').values
zero_index = data[:, -1] == 0
one_index = data[:, -1] == 1
zero_data = data[zero_index]
one_data = data[one_index]
train_size_zero = int(zero_data.shape[0] * 0.8)
train_size_one = int(one_data.shape[0] * 0.8)
X_train, X_test = np.concatenate((zero_data[:train_size_zero, :-1], one_data[:train_size_one, :-1]), 0), \
np.concatenate((zero_data[train_size_zero:, :-1], one_data[train_size_one:, :-1]), 0)
y_train, y_test = np.concatenate((zero_data[:train_size_zero, -1].reshape(-1,1), one_data[:train_size_one, -1].reshape(-1, 1)), 0), \
np.concatenate((zero_data[train_size_zero:, -1].reshape(-1, 1), one_data[train_size_one:, -1].reshape(-1, 1)), 0)
X_train_A = X_train[:, 0].reshape(-1, 1)
X_train_B = X_train[:, 2].reshape(-1, 1)
X_train_C = X_train[:, 1].reshape(-1, 1)
X_train_D = X_train[:, 3].reshape(-1, 1)
X_test_A = X_test[:, 0].reshape(-1, 1)
X_test_B = X_test[:, 2].reshape(-1, 1)
X_test_C = X_test[:, 1].reshape(-1, 1)
X_test_D = X_test[:, 3].reshape(-1, 1)
splitclass = SSCalculate()
model = VerticalXGBoostClassifier(rank=rank, lossfunc='LogLoss', splitclass=splitclass)
if rank == 1:
model.fit(X_train_A, y_train)
print('end 1')
elif rank == 2:
model.fit(X_train_B, np.zeros_like(y_train))
print('end 2')
elif rank == 3:
model.fit(X_train_C, np.zeros_like(y_train))
print('end 3')
elif rank == 4:
model.fit(X_train_D, np.zeros_like(y_train))
print('end 4')
else:
model.fit(np.zeros_like(X_train_B), np.zeros_like(y_train))
print('end 0')
if rank == 1:
y_pred = model.predict(X_test_A)
elif rank == 2:
y_pred = model.predict(X_test_B)
elif rank == 3:
y_pred = model.predict(X_test_C)
elif rank == 4:
y_pred = model.predict(X_test_D)
else:
model.predict(np.zeros_like(X_test_A))
if rank == 1:
y_ori = y_pred.copy()
y_pred = 1.0 / (1.0 + np.exp(-y_pred))
y_pred[y_pred > 0.5] = 1
y_pred[y_pred <= 0.5] = 0
result = y_pred - y_test
print(np.sum(result == 0) / y_pred.shape[0])
# for i in range(y_test.shape[0]):
# print(y_test[i], y_pred[i], y_ori[i])
def main2():
data = pd.read_csv('./GiveMeSomeCredit/cs-training.csv')
data.dropna(inplace=True)
data = data[['SeriousDlqin2yrs',
'RevolvingUtilizationOfUnsecuredLines', 'age',
'NumberOfTime30-59DaysPastDueNotWorse', 'DebtRatio', 'MonthlyIncome',
'NumberOfOpenCreditLinesAndLoans', 'NumberOfTimes90DaysLate',
'NumberRealEstateLoansOrLines', 'NumberOfTime60-89DaysPastDueNotWorse',
'NumberOfDependents']].values
ori_data = data.copy()
# Add features
# for i in range(1):
# data = np.concatenate((data, ori_data[:, 1:]), axis=1)
data = data / data.max(axis=0)
ratio = 10000 / data.shape[0]
zero_index = data[:, 0] == 0
one_index = data[:, 0] == 1
zero_data = data[zero_index]
one_data = data[one_index]
zero_ratio = len(zero_data) / data.shape[0]
one_ratio = len(one_data) / data.shape[0]
num = 7500
train_size_zero = int(zero_data.shape[0] * ratio) + 1
train_size_one = int(one_data.shape[0] * ratio)
X_train, X_test = np.concatenate((zero_data[:train_size_zero, 1:], one_data[:train_size_one, 1:]), 0), \
np.concatenate((zero_data[train_size_zero:train_size_zero+int(num * zero_ratio)+1, 1:], one_data[train_size_one:train_size_one+int(num * one_ratio), 1:]), 0)
y_train, y_test = np.concatenate(
(zero_data[:train_size_zero, 0].reshape(-1, 1), one_data[:train_size_one, 0].reshape(-1, 1)), 0), \
np.concatenate((zero_data[train_size_zero:train_size_zero+int(num * zero_ratio)+1, 0].reshape(-1, 1),
one_data[train_size_one:train_size_one+int(num * one_ratio), 0].reshape(-1, 1)), 0)
X_train_A = X_train[:, :2]
X_train_B = X_train[:, 2:4]
X_train_C = X_train[:, 4:7]
X_train_D = X_train[:, 7:]
X_test_A = X_test[:, :2]
X_test_B = X_test[:, 2:4]
X_test_C = X_test[:, 4:7]
X_test_D = X_test[:, 7:]
splitclass = SSCalculate()
model = VerticalXGBoostClassifier(rank=rank, lossfunc='LogLoss', splitclass=splitclass, max_depth=3, n_estimators=3, _epsilon=0.1)
start = datetime.now()
if rank == 1:
model.fit(X_train_A, y_train)
end = datetime.now()
print('In fitting 1: ', end - start)
time = end - start
for i in range(clientNum + 1):
if i == 1:
pass
else:
time += comm.recv(source=i)
print(time / (clientNum + 1))
final_time = time / (clientNum + 1)
print('end 1')
print(final_time)
elif rank == 2:
model.fit(X_train_B, np.zeros_like(y_train))
end = datetime.now()
comm.send(end - start, dest=1)
print('In fitting 2: ', end - start)
print('end 2')
elif rank == 3:
model.fit(X_train_C, np.zeros_like(y_train))
end = datetime.now()
print('In fitting 3: ', end - start)
comm.send(end - start, dest=1)
print('end 3')
elif rank == 4:
model.fit(X_train_D, np.zeros_like(y_train))
end = datetime.now()
print('In fitting 4: ', end - start)
comm.send(end - start, dest=1)
print('end 4')
else:
model.fit(np.zeros_like(X_train_B), np.zeros_like(y_train))
end = datetime.now()
print('In fitting 0: ', end - start)
comm.send(end - start, dest=1)
print('end 0')
if rank == 1:
y_pred = model.predict(X_test_A)
elif rank == 2:
y_pred = model.predict(X_test_B)
elif rank == 3:
y_pred = model.predict(X_test_C)
elif rank == 4:
y_pred = model.predict(X_test_D)
else:
model.predict(np.zeros_like(X_test_A))
if rank == 1:
y_pred = 1.0 / (1.0 + np.exp(-y_pred))
y_pred2 = y_pred.copy()
y_pred2[y_pred2 > 0.5] = 1
y_pred2[y_pred2 <= 0.5] = 0
y_pred2 = y_pred2.reshape(-1,1)
y_test = y_test.reshape(-1,1)
result = y_pred2 - y_test
print(np.sum(result == 0) / y_pred.shape[0])
# for i in range(y_test.shape[0]):
# print(y_test[i], y_pred[i])
def main3():
data = np.load('./adult.npy')
data = data / data.max(axis=0)
ratio = 0.8
zero_index = data[:, 0] == 0
one_index = data[:, 0] == 1
zero_data = data[zero_index]
one_data = data[one_index]
train_size_zero = int(zero_data.shape[0] * ratio) + 1
train_size_one = int(one_data.shape[0] * ratio)
X_train, X_test = np.concatenate((zero_data[:train_size_zero, 1:], one_data[:train_size_one, 1:]), 0), \
np.concatenate((zero_data[train_size_zero:, 1:], one_data[train_size_one:, 1:]), 0)
y_train, y_test = np.concatenate(
(zero_data[:train_size_zero, 0].reshape(-1, 1), one_data[:train_size_one, 0].reshape(-1, 1)), 0), \
np.concatenate((zero_data[train_size_zero:, 0].reshape(-1, 1),
one_data[train_size_one:, 0].reshape(-1, 1)), 0)
segment_A = int(0.2 * (data.shape[1] - 1))
segment_B = segment_A + int(0.2 * (data.shape[1] - 1))
segment_C = segment_B + int(0.3 * (data.shape[1] - 1))
X_train_A = X_train[:, 0:segment_A]
X_train_B = X_train[:, segment_A:segment_B]
X_train_C = X_train[:, segment_B:segment_C]
X_train_D = X_train[:, segment_C:]
X_test_A = X_test[:, :segment_A]
X_test_B = X_test[:, segment_A:segment_B]
X_test_C = X_test[:, segment_B:segment_C]
X_test_D = X_test[:, segment_C:]
splitclass = SSCalculate()
model = VerticalXGBoostClassifier(rank=rank, lossfunc='LogLoss', splitclass=splitclass, max_depth=3, n_estimators=3, _epsilon=0.1)
if rank == 1:
start = datetime.now()
model.fit(X_train_A, y_train)
end = datetime.now()
print('In fitting: ', end - start)
print('end 1')
elif rank == 2:
model.fit(X_train_B, np.zeros_like(y_train))
print('end 2')
elif rank == 3:
model.fit(X_train_C, np.zeros_like(y_train))
print('end 3')
elif rank == 4:
model.fit(X_train_D, np.zeros_like(y_train))
else:
model.fit(np.zeros_like(X_train_B), np.zeros_like(y_train))
print('end 0')
if rank == 1:
y_pred = model.predict(X_test_A)
elif rank == 2:
y_pred = model.predict(X_test_B)
elif rank == 3:
y_pred = model.predict(X_test_C)
elif rank == 4:
y_pred = model.predict(X_test_D)
else:
model.predict(np.zeros_like(X_test_A))
if rank == 1:
y_ori = y_pred.copy()
y_pred = 1.0 / (1.0 + np.exp(-y_pred))
y_pred2 = y_pred.copy()
y_pred2[y_pred2 > 0.5] = 1
y_pred2[y_pred2 <= 0.5] = 0
y_pred2 = y_pred2.reshape(-1,1)
y_test = y_test.reshape(-1,1)
result = y_pred2 - y_test
print(np.sum(result == 0) / y_pred.shape[0])
# for i in range(y_test.shape[0]):
# print(y_test[i], y_pred[i])
if __name__ == '__main__':
main2()
| 15,375 | 37.059406 | 179 | py |
MP-FedXGB | MP-FedXGB-main/XGBoost.py | import numpy as np
import progressbar
import pandas as pd
from datetime import *
np.random.seed(10)
class LeastSquareLoss():
def gradient(self, actual, predicted):
return -(actual - predicted)
def hess(self, actual, predicted):
return np.ones_like(actual)
class LogLoss():
def gradient(self, actual, predicted):
prob = 1.0 / (1.0 + np.exp(-predicted))
return prob - actual
def hess(self, actual, predicted):
prob = 1.0 / (1.0 + np.exp(-predicted))
return prob * (1.0 - prob) # Mind the dimension
class Tree:
def __init__(self, value=None, leftBranch=None, rightBranch=None, col=-1, result=None):
self.value = value
self.leftBranch = leftBranch
self.rightBranch = rightBranch
self.col = col
self.result = result
class XGBoostTree:
def __init__(self, lossfunc, _lambda, _gamma, _max_depth, _epsilon=0.05):
self.loss = lossfunc
self._lambda = _lambda
self._gamma = _gamma
self._epsilon = _epsilon
self._max_depth = _max_depth
def _split(self, y):
y, y_pred = y[:, 0].reshape(-1, 1), y[:, 1].reshape(-1, 1)
return y, y_pred
def _leaf_gain(self, g, h):
nominator = np.power(g, 2)
denominator = h + self._lambda
return nominator / denominator
def _split_criterion(self, left_g, left_h, right_g, right_h):
gain = (self._leaf_gain(left_g, left_h) + self._leaf_gain(right_g, right_h) -
self._leaf_gain(left_g + right_g, left_h + right_h)) * 0.5 - self._gamma
# print('In split criterion')
# print(self._leaf_gain(left_g, left_h))
# print(self._leaf_gain(right_g, right_h))
# print(self._leaf_gain(left_g + right_g, left_h + right_h))
# print('Out split criterion')
return gain
def getQuantile(self, colidx, X, y, y_pred):
split_list = []
data = np.concatenate((X, y, y_pred), axis=1)
data = data.copy()
idx = np.argsort(data[:, colidx], axis=0)
data = data[idx]
value_list = sorted(list(set(list(data[:, colidx])))) # Record all the different value
hess = np.ones_like(data[:, colidx])
data = np.concatenate((data, hess.reshape(-1, 1)), axis=1)
sum_hess = np.sum(hess)
last = value_list[0]
i = 1
if len(value_list) == 1: # For those who has only one value, do such process.
last_cursor = last
else:
last_cursor = value_list[1]
split_list.append((-np.inf, value_list[0]))
while i < len(value_list):
cursor = value_list[i]
small_hess = np.sum(data[:, -1][data[:, colidx] <= last]) / sum_hess
big_hess = np.sum(data[:, -1][data[:, colidx] <= cursor]) / sum_hess
# print(colidx, self.rank, np.abs(big_hess - small_hess), last, cursor)
if np.abs(big_hess - small_hess) < self._epsilon:
last_cursor = cursor
else:
judge = value_list.index(cursor) - value_list.index(last)
if judge == 1: # Although it didn't satisfy the criterion, it has no more split, so we must add it.
split_list.append((last, cursor))
last = cursor
else: # Move forward and record the last.
split_list.append((last, last_cursor))
last = last_cursor
last_cursor = cursor
i += 1
if split_list[-1][1] != value_list[-1]:
split_list.append((split_list[-1][1], value_list[-1])) # Add the top value into split_list.
split_list = np.array(split_list)
return split_list
def getAllQuantile(self, X, y): # Global quantile, must be calculated before tree building, avoiding recursion.
y, y_pred = self._split(y)
column_length = X.shape[1]
dict = {i: self.getQuantile(i, X, y, y_pred) for i in range(column_length)} # record all the split
self.quantile = dict
def buildTree(self, X, y, depth=1):
data = np.concatenate((X, y), axis=1)
y, y_pred = self._split(y)
column_length = X.shape[1]
gradient = self.loss.gradient(y, y_pred) # Calculate the loss at begining, avoiding later calculation.
hessian = self.loss.hess(y, y_pred)
# print('*' * 10, 'Gradient')
# print(np.concatenate([gradient, hessian], axis=1)[:20])
G = np.sum(gradient)
H = np.sum(hessian)
if depth > self._max_depth:
return Tree(result=- G / (H + self._lambda))
bestGain = 0
bestSplit = 0
bestSet = ()
for col in range(column_length):
splitList = self.quantile[col]
GL = 0
HL = 0
for k in range(splitList.shape[0]):
left = splitList[k][0]
right = splitList[k][1]
idx = ((data[:, col] <= right) & (data[:, col] > left))
GL += np.sum(gradient[idx])
HL += np.sum(hessian[idx])
GR = G - GL
HR = H - HL
gain = self._split_criterion(GL, HL, GR, HR)
if gain > bestGain:
bestGain = gain
bestSplit = (col, right)
bestSet = (data[data[:, col] <= right], data[data[:, col] > right])
if bestGain > 0:
# print('Split value: ', bestSplit[1])
# print('Into left')
leftBranch = self.buildTree(bestSet[0][:, :-2], bestSet[0][:, -2:], depth + 1)
# print('Out left')
# print('Into right')
rightBranch = self.buildTree(bestSet[1][:, :-2], bestSet[1][:, -2:], depth + 1)
# print('Out right')
return Tree(value=bestSplit[1], leftBranch=leftBranch, rightBranch=rightBranch, col=bestSplit[0])
else:
# print(-G/(H + self._lambda))
return Tree(result=- G / (H + self._lambda))
def fit(self, X, y):
self.getAllQuantile(X, y)
self.Tree = self.buildTree(X, y)
def classify(self, tree, data):
if tree.result != None:
return tree.result
else:
branch = None
v = data[tree.col]
if isinstance(v, int) or isinstance(v, float):
if v > tree.value:
branch = tree.rightBranch
else:
branch = tree.leftBranch
return self.classify(branch, data)
def predict(self, data):
data_num = data.shape[0]
result = []
for i in range(data_num):
result.append(self.classify(self.Tree, data[i]))
result = np.array(result).reshape((-1, 1))
return result
class XGBoostClassifier:
def __init__(self, lossfunc, _lambda=1, _gamma=0.5, _epsilon=0.1, n_estimators=3, learning_rate=1, min_samples_split=2, max_depth=3):
if lossfunc == 'LogLoss':
self.loss = LogLoss()
else:
self.loss = LeastSquareLoss()
self._lambda = _lambda
self._gamma = _gamma
self._epsilon = _epsilon
self.n_estimators = n_estimators # Number of trees
self.learning_rate = learning_rate # Step size for weight update
self.min_samples_split = min_samples_split # The minimum n of sampels to justify split
self.max_depth = max_depth # Maximum depth for tree
self.bar = progressbar.ProgressBar()
self.trees = []
for _ in range(n_estimators):
tree = XGBoostTree(
lossfunc=self.loss,
_lambda=self._lambda,
_gamma=self._gamma,
_max_depth=self.max_depth,
_epsilon=self._epsilon,)
self.trees.append(tree)
def fit(self, X, y):
data_num = X.shape[0]
y = np.reshape(y, (data_num, 1))
y_pred = np.zeros(np.shape(y))
# y_pred = np.random.rand(y.shape[0]).reshape(-1, 1)
for i in range(self.n_estimators):
tree = self.trees[i]
y_and_pred = np.concatenate((y, y_pred), axis=1)
# print(y_and_pred)
tree.fit(X, y_and_pred)
print('-' * 100)
update_pred = tree.predict(X)
update_pred = np.reshape(update_pred, (data_num, 1))
y_pred += update_pred
def predict(self, X):
y_pred = None
data_num = X.shape[0]
# Make predictions
for tree in self.trees:
# Estimate gradient and update prediction
update_pred = tree.predict(X)
update_pred = np.reshape(update_pred, (data_num, 1))
if y_pred is None:
y_pred = np.zeros_like(update_pred).reshape(data_num, -1)
y_pred += update_pred
return y_pred
def main():
data = pd.read_csv('./filtered_data_median.csv').values
# train_size = int(data.shape[0] * 0.9)
# X_train, X_test = data[:train_size, :-2], data[train_size:, :-2]
# y_train, y_test = data[:train_size, -2].reshape(-1, 1), data[train_size:, -2].reshape(-1, 1)
zero_index = data[:, -2] == 0
one_index = data[:, -2] == 1
zero_data = data[zero_index]
one_data = data[one_index]
train_size_zero = int(zero_data.shape[0] * 0.8)
train_size_one = int(one_data.shape[0] * 0.8)
X_train, X_test = np.concatenate((zero_data[:train_size_zero, :-2], one_data[:train_size_one, :-2]), 0), \
np.concatenate((zero_data[train_size_zero:, :-2], one_data[train_size_one:, :-2]), 0)
y_train, y_test = np.concatenate((zero_data[:train_size_zero, -2].reshape(-1,1), one_data[:train_size_one, -2].reshape(-1, 1)), 0), \
np.concatenate((zero_data[train_size_zero:, -2].reshape(-1, 1), one_data[train_size_one:, -2].reshape(-1, 1)), 0)
model = XGBoostClassifier(lossfunc='LogLoss')
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_ori = y_pred.copy()
y_pred = 1.0 / (1.0 + np.exp(-y_pred))
y_pred[y_pred > 0.5] = 1
y_pred[y_pred <= 0.5] = 0
result = y_pred - y_test
print(np.sum(result == 0) / y_pred.shape[0])
# for i in range(y_test.shape[0]):
# print(y_test[i], y_pred[i], y_ori[i])
def main2():
data = pd.read_csv('./iris.csv').values
zero_index = data[:, -1] == 0
one_index = data[:, -1] == 1
zero_data = data[zero_index]
one_data = data[one_index]
train_size_zero = int(zero_data.shape[0] * 0.8)
train_size_one = int(one_data.shape[0] * 0.8)
X_train, X_test = np.concatenate((zero_data[:train_size_zero, :-1], one_data[:train_size_one, :-1]), 0), \
np.concatenate((zero_data[train_size_zero:, :-1], one_data[train_size_one:, :-1]), 0)
y_train, y_test = np.concatenate((zero_data[:train_size_zero, -1].reshape(-1,1), one_data[:train_size_one, -1].reshape(-1, 1)), 0), \
np.concatenate((zero_data[train_size_zero:, -1].reshape(-1, 1), one_data[train_size_one:, -1].reshape(-1, 1)), 0)
model = XGBoostClassifier(lossfunc='LogLoss', n_estimators=3)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_ori = y_pred.copy()
y_pred = 1.0 / (1.0 + np.exp(-y_pred))
y_pred[y_pred > 0.5] = 1
y_pred[y_pred <= 0.5] = 0
result = y_pred - y_test
print(np.sum(result == 0) / y_pred.shape[0])
for i in range(y_test.shape[0]):
print(y_test[i], y_pred[i], y_ori[i])
def main3():
from sklearn.ensemble import GradientBoostingClassifier
data = pd.read_csv('./iris.csv').values
zero_index = data[:, -1] == 0
one_index = data[:, -1] == 1
zero_data = data[zero_index]
one_data = data[one_index]
train_size_zero = int(zero_data.shape[0] * 0.8)
train_size_one = int(one_data.shape[0] * 0.8)
X_train, X_test = np.concatenate((zero_data[:train_size_zero, :-1], one_data[:train_size_one, :-1]), 0), \
np.concatenate((zero_data[train_size_zero:, :-1], one_data[train_size_one:, :-1]), 0)
y_train, y_test = np.concatenate((zero_data[:train_size_zero, -1].reshape(-1,1), one_data[:train_size_one, -1].reshape(-1, 1)), 0), \
np.concatenate((zero_data[train_size_zero:, -1].reshape(-1, 1), one_data[train_size_one:, -1].reshape(-1, 1)), 0)
model = model = XGBoostClassifier(lossfunc='LogLoss')
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(y_pred)
y_pred[y_pred > 0.5] = 1
y_pred[y_pred <= 0.5] = 0
result = y_pred - y_test
print(np.sum(result == 0) / y_pred.shape[0])
for i in range(y_test.shape[0]):
print(y_test[i], y_pred[i])
def main6():
data_train = pd.read_csv('./GiveMeSomeCredit/cs-training.csv')
data_train = data_train[['SeriousDlqin2yrs',
'RevolvingUtilizationOfUnsecuredLines', 'age',
'NumberOfTime30-59DaysPastDueNotWorse', 'DebtRatio', 'MonthlyIncome',
'NumberOfOpenCreditLinesAndLoans', 'NumberOfTimes90DaysLate',
'NumberRealEstateLoansOrLines', 'NumberOfTime60-89DaysPastDueNotWorse',
'NumberOfDependents']].values
data_train.dtype = 'float16'
data_test = pd.read_csv('./GiveMeSomeCredit/cs-training.csv')
data_test = data_test[['SeriousDlqin2yrs',
'RevolvingUtilizationOfUnsecuredLines', 'age',
'NumberOfTime30-59DaysPastDueNotWorse', 'DebtRatio', 'MonthlyIncome',
'NumberOfOpenCreditLinesAndLoans', 'NumberOfTimes90DaysLate',
'NumberRealEstateLoansOrLines', 'NumberOfTime60-89DaysPastDueNotWorse',
'NumberOfDependents']].values
data_test.dtype = 'float16'
y_train = data_train[:, 0]
X_train = data_train[:, 1:]
X_test = data_test[:, 1:]
model = XGBoostClassifier(lossfunc='LogLoss')
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_ori = y_pred.copy()
y_pred = 1.0 / (1.0 + np.exp(-y_pred))
y_pred2 = y_pred.copy()
y_pred2[y_pred2 > 0.5] = 1
y_pred2[y_pred2 <= 0.5] = 0
print(y_pred)
# result = y_pred2 - y_test
# print(np.sum(result == 0) / y_pred.shape[0])
if __name__ == '__main__':
start = datetime.now()
main3()
end = datetime.now()
print(end - start)
| 14,368 | 39.590395 | 137 | py |
MP-FedXGB | MP-FedXGB-main/data_adult_process.py | import pandas as pd
import numpy as np
training_data = './adult.data'
columns = ['Age','Workclass','fnlwgt','Education','EdNum','MaritalStatus',
'Occupation','Relationship','Race','Sex','CapitalGain',
'CapitalLoss','HoursPerWeek','Country','Income']
income = pd.read_csv(training_data, names=columns)
income.dropna(inplace=True)
income['Income'].replace(' <=50K', 0,inplace=True)
income['Income'].replace(' >50K', 1,inplace=True)
y = income['Income']
temp = income.iloc[:, :-1]
# 将文本转换为数值型用于拟合模型
income_=pd.get_dummies(temp,columns=['Relationship','Sex','MaritalStatus','Workclass',
'Education','Country','Occupation','Race'])
income = np.concatenate([y.values.reshape(-1, 1), income_.values,], axis=1)
print(income.shape)
np.save('adult.npy', income) | 799 | 39 | 86 | py |
fitclip | fitclip-main/util/structured_group_utils.py | """Useful utils when using `DataModuleStructuredGroup`."""
from typing import Any, Mapping, Sequence, Tuple
import torch
from aligner.video_text_module import TYPE_INPUT
from util.tensor_utils import pad
TYPE_MULTI_INPUT = Mapping[str, TYPE_INPUT]
# It's like `default_collate` but instead of a sequence we have a mapping, and we do `cat` instead of `stack`.
# It makes sense to be similar because we're merging multiple batches together.
# Note that using collate from the dataloader side. It's simpler, and more GPU-memory efficient.
def _cat_collate(batch: Sequence[Any]) -> Any:
elem = batch[0]
elem_type = type(batch)
if isinstance(elem, torch.Tensor):
return torch.cat(batch) # noqa
elif isinstance(elem, Mapping):
return {k: _cat_collate([d[k] for d in batch]) for k in elem}
elif isinstance(elem, (float, int, bytes, str)):
return batch
elif isinstance(elem, tuple) and hasattr(elem, '_fields'): # namedtuple
return elem_type(*(_cat_collate(samples) for samples in zip(*batch))) # noqa
elif isinstance(elem, Sequence):
return [x for d in batch for x in d]
else:
raise TypeError(f"Not sure how to collate type {elem_type}")
def _merge_datasets_batch(batches_by_dataset: TYPE_MULTI_INPUT) -> Tuple[TYPE_INPUT, Sequence[int]]:
lengths = [len(batch["video"]) for batch in batches_by_dataset.values()]
max_text_len = max(batch["text"]["input_ids"].shape[-1] for batch in batches_by_dataset.values())
for batch in batches_by_dataset.values():
batch["text"] = {k: pad(v, min_size=max_text_len, dim=-1) for k, v in batch["text"].items()}
batch = _cat_collate(list(batches_by_dataset.values()))
return batch, lengths
| 1,737 | 40.380952 | 110 | py |
fitclip | fitclip-main/util/viz_utils.py | import numpy as np
import torch
import torchvision
from matplotlib import pyplot as plt
from matplotlib.pyplot import subplots_adjust
from torchvision.transforms.functional import to_pil_image
from aligner.encoder.video_text_encoder import VideoTextEncoder
def visualize_images_tensor(images: torch.Tensor) -> plt.Axes:
"""`images` has shape (N, C, H, W)."""
grid = torchvision.utils.make_grid(images)
fig, ax = plt.subplots()
fig.tight_layout()
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
ax.autoscale_view("tight")
ax.imshow(np.asarray(to_pil_image(grid)))
ax.set(xticklabels=[], yticklabels=[], xticks=[], yticks=[])
return ax
def debug_batch(video: torch.Tensor, text: torch.Tensor, encoder: VideoTextEncoder) -> None:
video, text = video.detach().cpu(), text.detach().cpu()
video = encoder.to_bchw(video)
denormalized_images = encoder.denormalize_video_tensor(video).reshape(-1, *video.shape[2:])
visualize_images_tensor(denormalized_images)
plt.show()
for decoded in encoder.decode_text(text):
print(decoded)
| 1,139 | 29 | 95 | py |
fitclip | fitclip-main/util/tensor_utils.py | from typing import Any, Mapping, Optional, Sequence, TypeVar, Union
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
from pytorch_lightning.utilities.apply_func import apply_to_collection
T = TypeVar("T")
def pad(t: torch.Tensor, min_size: int, dim: int = 1, value: Any = 0) -> torch.Tensor:
"""Pads the dim `dim` in `t` with the value `value` so the size is at least `min_size`."""
if dim < 0:
dim += len(t.shape)
if (count := t.shape[dim]) < min_size:
# `pad` keyword arg goes from the last dim to the first one in pairs, where the first value of the pair is
# for left padding and the other one for right padding.
return F.pad(t, pad=(0, 0) * (len(t.shape) - 1 - dim) + (0, min_size - count), value=value)
else:
return t
def split_in_collection(data: T, split_size_or_sections: Union[int, Sequence[int]]) -> Sequence[T]:
"""Applies `split` to the inside tensors of the collections and also generates one collection for each of the
returned elements from `split`."""
type_ = type(data)
if isinstance(data, torch.Tensor):
return data.split(split_size_or_sections)
elif isinstance(data, Mapping):
zipped = zip(*(split_in_collection(v, split_size_or_sections) for v in data.values()))
return [type_((k, v) for k, v in zip(data.keys(), z)) for z in zipped]
elif isinstance(data, Sequence):
return [type_(z) for z in zip(*(split_in_collection(e, split_size_or_sections) for e in data))]
else:
raise ValueError(f"Unsupported type for split: {type_}")
def _first_tensor_in_collection(data: Any) -> torch.Tensor:
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, Mapping):
return _first_tensor_in_collection(data.values())
else:
return _first_tensor_in_collection(next(iter(data)))
def all_gather(lightning_module: pl.LightningModule, data: Any, group: Optional[Any] = None,
sync_grads: bool = False, return_world_size_dim: bool = False) -> Any:
"""Gathers a tensor, or multiple tensors inside a collection, so that the output number of dimensions is the same
regardless of the accelerator.
Note this is different from `pl.LightningModule.all_gather`, that for a single GPU it doesn't return a new
dimension but for the parallel settings it does.
"""
first_tensor_old_shape = _first_tensor_in_collection(data).shape
output = lightning_module.all_gather(data, group=group, sync_grads=sync_grads)
if len(first_tensor_new_shape := _first_tensor_in_collection(output).shape) == len(first_tensor_old_shape) + 1:
return output if return_world_size_dim else apply_to_collection(output, torch.Tensor,
lambda t: t.view(-1, *t.shape[2:]))
elif len(first_tensor_new_shape) == len(first_tensor_old_shape):
return apply_to_collection(output, torch.Tensor, torch.Tensor.unsqueeze, 0) if return_world_size_dim else output
else:
raise ValueError(f"Unexpected new shape for the first tensor in the collection: {first_tensor_new_shape} (old "
f"was {first_tensor_old_shape}). "
f"The new shape was expected to have the same number of dimensions or one more.")
| 3,355 | 49.089552 | 120 | py |
fitclip | fitclip-main/util/typing_utils.py | from os import PathLike
from typing import Union
TYPE_PATH = Union[PathLike, str, bytes]
| 141 | 22.666667 | 50 | py |
fitclip | fitclip-main/util/checkpoint_utils.py | from typing import MutableMapping
import torch
from cached_path import cached_path
from util.typing_utils import TYPE_PATH
def state_dict_from_checkpoint_path(checkpoint_path: TYPE_PATH, prefix: str = "") -> MutableMapping[str, torch.Tensor]:
prefix += ("" if prefix.endswith(".") or not prefix else ".")
checkpoint = torch.load(cached_path(checkpoint_path))
return {k[len(prefix):]: v for k, v in checkpoint["state_dict"].items() if k.startswith(prefix)}
| 472 | 35.384615 | 119 | py |
fitclip | fitclip-main/util/video_utils.py | import os
from typing import Any, Callable, Iterable, Iterator, Optional, Sequence
from torchvision.datasets.video_utils import VideoClips
from util.typing_utils import TYPE_PATH
# From https://en.wikipedia.org/wiki/Video_file_format
VIDEO_FILE_EXTENSIONS = (".3g2", ".3gp", ".amv", ".asf", ".avi", ".drc", ".f4a", ".f4b", ".f4p", ".f4v", ".flv",
".gif", ".gifv", ".m2ts", ".m2v", ".m4p", ".m4v", ".mkv", ".mng", ".mov", ".mp2", ".mp4",
".mpe", ".mpeg", ".mpg", ".mpv", ".mts", ".mxf", ".nsv", ".ogg", ".ogv", ".qt", ".rm",
".rmvb", ".roq", ".svi", ".ts", ".viv", ".vob", ".webm", ".wmv", ".yuv")
def get_videos_in_folder(path: TYPE_PATH,
extensions: Optional[Iterable[str]] = VIDEO_FILE_EXTENSIONS) -> Iterator[str]:
extensions = None if extensions is None else tuple(extensions)
for folder, _, filenames in os.walk(path, followlinks=True):
for filename in filenames:
if os.path.isfile(full_path := os.path.join(folder, filename)) \
and (not extensions or filename.lower().endswith(extensions)):
yield full_path
def get_sorted_videos_in_folder(path: TYPE_PATH,
extensions: Optional[Iterable[str]] = VIDEO_FILE_EXTENSIONS,
key: Optional[Callable[[str], Any]] = None, reverse: bool = False) -> Iterator[str]:
"""Returns a sorted version of `get_videos_in_folder`.
Even though this can be simply applied by the caller, the fact that the main use case of `get_videos_in_folder`
is from a video dataset and that its order should be deterministic (but that `get_videos_in_folder` doesn't
guarantee it) makes this function handy and a wake-up call for this issue.
The videos in a PyTorch `Dataset` need to be deterministic e.g. for a distributed setting, when e.g. using
`DistributedSampler` for it to guarantee each data sample is used once and only once between all processes.
"""
return sorted(get_videos_in_folder(path, extensions), key=key, reverse=reverse)
def resample(num_frames: int, original_fps: float, new_fps: float) -> Sequence[int]:
"""Returns essentially the same as `VideoClips._resample_video_idx`. Unlike it, it always checks for the max frames
(the mentioned function doesn't do it when it returns a `slice`)."""
indices = VideoClips._resample_video_idx(num_frames, original_fps, new_fps)
if isinstance(indices, slice) and indices.stop is None:
indices = range(*indices.indices((indices.start or 0) + num_frames * indices.step))
return indices
| 2,659 | 53.285714 | 119 | py |
fitclip | fitclip-main/util/argparse_with_defaults.py | import argparse
from typing import Any
class ArgumentParserWithDefaults(argparse.ArgumentParser):
"""Custom argument parser that will display the default value for an argument in the help message. """
_action_defaults_to_ignore = {"help", "store_true", "store_false", "store_const"}
@staticmethod
def _is_empty_default(default: Any) -> bool:
return default is None or (isinstance(default, (str, list, tuple, set)) and not default)
def add_argument(self, *args, **kwargs) -> argparse.Action:
# Add default value to the help message when the default is meaningful.
default = kwargs.get("default")
if kwargs.get("action") not in self._action_defaults_to_ignore and not self._is_empty_default(default):
kwargs["help"] = f"{kwargs.get('help', '')} (default = {default})"
return super().add_argument(*args, **kwargs)
| 981 | 45.761905 | 111 | py |
fitclip | fitclip-main/util/iter_utils.py | import collections
import itertools
from typing import Any, Iterable, Iterator, Literal, Optional, Sequence, Tuple, TypeVar
T = TypeVar("T")
def consume(it: Iterator[Any]) -> None:
collections.deque(it, maxlen=0)
# See https://docs.python.org/3/library/itertools.html#itertools-recipes
def pairwise(it: Iterable[T]) -> Iterable[Tuple[T, T]]:
a, b = itertools.tee(it)
next(b, None)
return zip(a, b)
def can_be_iterated_more_than_once(it: Iterable[Any]) -> bool:
try:
object.__getattribute__(it, "__iter__")
except AttributeError:
return False
try:
object.__getattribute__(it, "__next__")
except AttributeError:
return True
return False
# See `grouper` in https://docs.python.org/3/library/itertools.html#itertools-recipes.
def batch(iterable: Iterable[T], n: int, *, incomplete: Literal["fill", "ignore"] = "ignore",
fill_value: Optional[Any] = None) -> Iterator[Iterable[T]]:
"""Batches the data into non-overlapping fixed-length batches.
Examples:
grouper("ABCDEFGH", 3) --> ABC DEF
grouper("ABCDEFGH", 3, incomplete="fill", fill_value="x") --> ABC DEF GHx
"""
args = [iter(iterable)] * n
if incomplete == "fill":
return itertools.zip_longest(*args, fillvalue=fill_value)
elif incomplete == "ignore":
return zip(*args)
else:
raise ValueError(f"Expected 'fill' or 'ignore'; got '{incomplete}'")
def batch_sequence(seq: Sequence[T], n: int) -> Iterator[Sequence[T]]:
"""Yield successive n-sized chunks from `seq`."""
for i in range(0, len(seq), n):
yield seq[i:i + n]
| 1,784 | 30.315789 | 93 | py |
fitclip | fitclip-main/scripts/apply_wise_ft.py | import argparse
import torch
from aligner.encoder.clip_video_text_encoder import load_clip_model
from aligner.wise import wise_state_dict
from util.argparse_with_defaults import ArgumentParserWithDefaults
def parse_args() -> argparse.Namespace:
parser = ArgumentParserWithDefaults("Applies weight-space ensembles for fine-tuning (WiSE-FT) on 2 CLIP "
"checkpoints.",
description="See https://arxiv.org/abs/2109.01903 for more info.")
parser.add_argument("input_path_or_name1", metavar="INPUT_FILE_OR_NAME_1")
parser.add_argument("input_path_or_name2", metavar="INPUT_FILE_OR_NAME_2")
parser.add_argument("output_path", metavar="OUTPUT_FILE")
parser.add_argument("--weight-for-2", type=float, default=0.5)
return parser.parse_args()
def main() -> None:
args = parse_args()
model1 = load_clip_model(args.input_path_or_name1)
model2 = load_clip_model(args.input_path_or_name2)
# We don't use the logic scale from CLIP but ours, so we had deleted it. Here we need to re-create the variable,
# so it doesn't fail when using the checkpoints.
model1.logit_scale = getattr(model1, "logit_scale", torch.tensor(float("nan")))
model2.logit_scale = getattr(model2, "logit_scale", torch.tensor(float("nan")))
state_dict = wise_state_dict(model1, model2, weight_for_2=args.weight_for_2)
torch.save(state_dict, args.output_path)
if __name__ == "__main__":
main()
| 1,526 | 37.175 | 116 | py |
fitclip | fitclip-main/scripts/csv_diff.py | import argparse
import pandas as pd
from util.argparse_with_defaults import ArgumentParserWithDefaults
def parse_args() -> argparse.Namespace:
parser = ArgumentParserWithDefaults()
parser.add_argument("path1", metavar="FILE1")
parser.add_argument("path2", metavar="FILE2")
return parser.parse_args()
def main() -> None:
args = parse_args()
df1 = pd.read_csv(args.path1)
df2 = pd.read_csv(args.path2)
print(pd.concat([df1, df2]).drop_duplicates(keep=False).to_csv(index=False))
if __name__ == "__main__":
main()
| 635 | 21.714286 | 80 | py |
fitclip | fitclip-main/scripts/subcorr.py | import argparse
import sys
from typing import Any, Callable, Iterable, MutableMapping, Optional, Sequence, Union
import PIL.Image
import clip
import decord
import numpy as np
import seaborn as sns
import torch
from clip.model import CLIP
from matplotlib import pyplot as plt
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
from spacy.tokens import Doc, Span
def get_video_info(path: str) -> MutableMapping[str, Any]:
video_reader = decord.VideoReader(path)
frame_indices = list(range(0, len(video_reader), 10))
frames = [PIL.Image.fromarray(f) for f in video_reader.get_batch(frame_indices).asnumpy()]
thumbnails_frame_indices = video_reader.get_key_indices()
thumbnails = [PIL.Image.fromarray(f) for f in video_reader.get_batch(thumbnails_frame_indices).asnumpy()]
thumbnails = [f.copy() for f in thumbnails]
for thumbnail in thumbnails:
thumbnail.thumbnail((64, 64))
return {
"frames": frames,
"frame_times": video_reader.get_frame_timestamp(frame_indices).mean(axis=-1), # noqa
"thumbnails": thumbnails,
"thumbnail_times": video_reader.get_frame_timestamp(thumbnails_frame_indices).mean(axis=-1), # noqa
}
def encode_visual(images: Iterable[PIL.Image.Image], clip_model: CLIP,
image_preprocessor: Callable[[PIL.Image.Image], torch.Tensor],
device: Optional[Any] = None) -> torch.Tensor:
images = torch.stack([image_preprocessor(image) for image in images])
if device is not None:
images = images.to(device)
with torch.inference_mode():
encoded_images = clip_model.encode_image(images)
return encoded_images / encoded_images.norm(dim=-1, keepdim=True)
def encode_text(text: str, clip_model: CLIP, device: Optional[Any] = None) -> torch.Tensor:
tokenized_texts = clip.tokenize([text])
if device is not None:
tokenized_texts = tokenized_texts.to(device)
with torch.inference_mode():
encoded_texts = clip_model.encode_text(tokenized_texts)
return encoded_texts / encoded_texts.norm(dim=-1, keepdim=True)
def text_probs(encoded_images: torch.Tensor, encoded_texts: torch.Tensor) -> np.ndarray:
with torch.inference_mode():
# clip_model.logit_scale.exp() == 100
return (100 * encoded_images @ encoded_texts.T).softmax(dim=0).squeeze(-1).cpu().numpy() # noqa
def create_figure(times: Sequence[float], probs: Sequence[float], thumbnail_times: Sequence[float],
thumbnails: Iterable[PIL.Image.Image], title: Union[Doc, Span, str]) -> plt.Axes:
# noinspection SpellCheckingInspection
sns.set(rc={"figure.figsize": (1.0 * len(thumbnail_times), 1.5)})
ax = sns.lineplot(x=times, y=probs)
plt.xticks(thumbnail_times)
ax.set_title(title.text if isinstance(title, (Doc, Span)) else title, fontsize=35, y=0.6)
ax.set(xlabel="time", ylabel="probability")
plt.fill_between(times, probs)
if isinstance(title, (Doc, Span)):
start_time = title[0]._.start_time
end_time = title[-1]._.end_time
plt.axvspan(start_time, end_time, alpha=0.5, color="red")
for i, (time, thumbnail) in enumerate(zip(thumbnail_times, thumbnails)):
im = OffsetImage(thumbnail, axes=ax)
ab = AnnotationBbox(im, (time, 0), xybox=(0, -60), frameon=False, boxcoords="offset points", pad=0)
ax.add_artist(ab)
plt.margins(x=0, tight=True)
plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
return ax
def create_figure_for_text(encoded_frames: torch.Tensor, text: Union[Doc, Span, str], clip_model: CLIP,
times: Sequence[float], thumbnail_times: Sequence[float],
thumbnails: Iterable[PIL.Image.Image]) -> plt.Axes:
encoded_texts = encode_text(text.text if isinstance(text, (Doc, Span)) else text, clip_model,
device=encoded_frames.device)
probs = text_probs(encoded_frames, encoded_texts)
return create_figure(times, probs, thumbnail_times, thumbnails, text)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("path", metavar="PATH")
return parser.parse_args()
def main() -> None:
sns.set_theme()
args = parse_args()
device = "cuda" if torch.cuda.is_available() else "cpu"
clip_model, image_preprocessor = clip.load("ViT-B/16", device=device)
# noinspection SpellCheckingInspection
video_info = get_video_info(args.path)
encoded_frames = encode_visual(video_info["frames"], clip_model, image_preprocessor, device=device)
for text in sys.stdin:
if text := text.strip():
create_figure_for_text(encoded_frames, text, clip_model, video_info["frame_times"],
video_info["thumbnail_times"], video_info["thumbnails"])
plt.show()
if __name__ == "__main__":
main()
| 4,981 | 35.101449 | 109 | py |
fitclip | fitclip-main/scripts/sample_csv.py | import argparse
import sys
import pandas as pd
from util.argparse_with_defaults import ArgumentParserWithDefaults
def parse_args() -> argparse.Namespace:
parser = ArgumentParserWithDefaults()
parser.add_argument("path", metavar="FILE", nargs="?", default="-")
parser.add_argument("-s", "--size", type=int, default=10)
args = parser.parse_args()
args.path = sys.stdin if args.path == "-" else args.path
return args
def main() -> None:
args = parse_args()
print(pd.read_csv(args.path).sample(args.size).to_csv(index=False))
if __name__ == "__main__":
main()
| 624 | 21.321429 | 71 | py |
fitclip | fitclip-main/scripts/prepare_trained_clip_checkpoint_for_evaluation.py | import argparse
import torch
from util.checkpoint_utils import state_dict_from_checkpoint_path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("input_path", metavar="INPUT_FILE")
parser.add_argument("output_path", metavar="OUTPUT_FILE")
parser.add_argument("--prefix", default="encoder.model.")
return parser.parse_args()
def main() -> None:
args = parse_args()
state_dict = state_dict_from_checkpoint_path(args.input_path, prefix=args.prefix)
# We don't use the logic scale from CLIP but ours, so we had deleted it. Here we need to re-create the variable,
# so it doesn't fail when loading this `state_dict`.
state_dict["logit_scale"] = torch.tensor(float("nan"))
torch.save(state_dict, args.output_path)
if __name__ == "__main__":
main()
| 868 | 27.032258 | 116 | py |
fitclip | fitclip-main/scripts/checkpoint_to_state_dict.py | import argparse
import sys
import torch
from util.checkpoint_utils import state_dict_from_checkpoint_path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("input_path", metavar="INPUT_FILE")
parser.add_argument("--prefix", default="encoder.model.")
return parser.parse_args()
def main() -> None:
args = parse_args()
state_dict = state_dict_from_checkpoint_path(args.input_path, prefix=args.prefix)
torch.save(state_dict, sys.stdout.buffer)
if __name__ == "__main__":
main()
| 582 | 22.32 | 85 | py |
fitclip | fitclip-main/scripts/list_possible_pos.py | import fileinput
from nltk.corpus import wordnet as wn
from nltk.corpus.reader import POS_LIST
if __name__ == "__main__":
for line in fileinput.input():
if line := line.strip():
print("".join(pos for pos in POS_LIST if wn.synsets(line, pos=pos)))
| 295 | 25.909091 | 80 | py |
fitclip | fitclip-main/scripts/prepare_trained_checkpoint_for_evaluation.py | import argparse
import torch
from cached_path import cached_path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("input_path", metavar="INPUT_FILE", type=cached_path)
parser.add_argument("output_path", metavar="OUTPUT_FILE")
parser.add_argument("--prefix", default="encoder.model.")
return parser.parse_args()
def main() -> None:
args = parse_args()
checkpoint = torch.load(args.input_path)
prefix = args.prefix + ("" if args.prefix.endswith(".") else ".")
checkpoint["state_dict"] = {k[len(prefix):]: v for k, v in checkpoint["state_dict"].items() if k.startswith(prefix)}
torch.save(checkpoint, args.output_path)
if __name__ == "__main__":
main()
| 771 | 26.571429 | 120 | py |
fitclip | fitclip-main/scripts/speech_to_text.py | import sys
from google.cloud.speech_v1p1beta1 import RecognitionAudio, RecognitionConfig, RecognitionMetadata, \
SpeakerDiarizationConfig, SpeechClient
# We use a Python script as the `gcloud` equivalent command doesn't support the enhanced models
# (`gcloud ml speech recognize-long-running`, not even the alpha and beta ones).
# noinspection PyTypeChecker
def main() -> None:
assert len(sys.argv) == 2, f"Valid syntax: {sys.argv[0]} GS_PATH"
path = sys.argv[1] # -Cv9h3ic2JI.opus, czQwCto9O80.opus, mono: --BLA_8Qixs
if path.startswith("gs://"):
audio = RecognitionAudio(uri=path)
else:
with open(path, "rb") as file:
audio = RecognitionAudio(content=file.read())
kwargs = {
"audio_channel_count": 2, # It fails otherwise for many audios. FIXME: fails with mono
}
if path.endswith(".opus"):
kwargs["encoding"] = RecognitionConfig.AudioEncoding.OGG_OPUS # All our Opus videos are in an Ogg container.
# When using Ogg-Opus, the endpoint needs the following fields.
kwargs["sample_rate"] = 48000 # All our Opus audios I've seen use this rate (at least 100).
else:
kwargs["encoding"] = RecognitionConfig.AudioEncoding.ENCODING_UNSPECIFIED
metadata = RecognitionMetadata(original_media_type=RecognitionMetadata.OriginalMediaType.VIDEO)
config = RecognitionConfig(language_code="en-US", enable_word_time_offsets=True, enable_word_confidence=True,
# Option not supported in the enhanced video model:
# alternative_language_codes=["en-GB", "en-IN", "en-AU"],
enable_automatic_punctuation=True, use_enhanced=True, model="video", metadata=metadata,
diarization_config=SpeakerDiarizationConfig(enable_speaker_diarization=True,
min_speaker_count=1, max_speaker_count=10),
**kwargs)
response = SpeechClient().long_running_recognize(config=config, audio=audio)
result = response.result(timeout=10000)
print(type(result).to_json(result))
if __name__ == "__main__":
main()
| 2,428 | 47.58 | 118 | py |
fitclip | fitclip-main/scripts/open_clip_checkpoint_to_model.py | import argparse
import torch
from cached_path import cached_path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("input_path", metavar="INPUT_FILE", type=cached_path)
parser.add_argument("output_path", metavar="OUTPUT_FILE")
return parser.parse_args()
def main() -> None:
args = parse_args()
checkpoint = torch.load(args.input_path)
state_dict = checkpoint["state_dict"]
first_key = next(iter(state_dict))
prefix = next(prefix for prefix in ["model", "module"] if first_key.startswith(prefix + "."))
torch.save({k[len(prefix + "."):]: v for k, v in state_dict.items()}, args.output_path)
if __name__ == "__main__":
main()
| 744 | 25.607143 | 97 | py |
fitclip | fitclip-main/demo/app.py | import json
import random
from typing import Tuple
from flask import Flask, Response, jsonify, request
from flask_cors import CORS, cross_origin
from demo.search import search_in_subtitles
app = application = Flask(__name__, static_url_path="/") # `application` is gunicorn's default, `app` is flask's.
cors = CORS(app)
app.config["CORS_HEADERS"] = "Content-Type"
@app.route("/search")
@cross_origin()
def search() -> Tuple[Response, int]:
try:
query = request.args.get("q", "[]")
pattern = json.loads(query) # [{"LOWER": "this", "DEP": {"IN": ["nsubj", "dobj", "iobj"]}}]
top_k = int(request.args.get("top_k", "10"))
results = list(search_in_subtitles(pattern))
return jsonify([
{
"video_id": span.doc._.video_id,
"start_time": span[0]._.start_time,
"end_time": span[-1]._.end_time,
"text": span.text,
}
for span in random.sample(results, min(top_k, len(results)))
]), 200
except Exception as e: # noqa
return jsonify(status=500, message=repr(e)), 500
@app.route("/")
def root() -> Response:
return app.send_static_file("index.html")
| 1,213 | 30.128205 | 114 | py |
fitclip | fitclip-main/demo/search.py | import json
import os
import re
from typing import Any, Iterable, Iterator, Mapping, Optional, Sequence
import spacy
import spacy_alignments
from cached_path import cached_path
from spacy.matcher import Matcher
from spacy.tokens import Doc, DocBin, Span, Token
from tqdm.auto import tqdm
RE_MULTIPLE_SPACES = re.compile(r" {2,}")
CAPTIONS_DIR = os.path.join(os.environ["SCRATCH_DIR"], "captions")
spacy.prefer_gpu()
NLP = spacy.load("en_core_web_trf")
Doc.set_extension("video_id", default=None)
Token.set_extension("start_time", default=None)
Token.set_extension("end_time", default=None)
def _list_caption_paths(dir_path: str) -> Iterator[str]:
with os.scandir(dir_path) as it:
for entry in it:
if entry.is_file() and entry.name.endswith(".json"): # noqa
yield entry.path # noqa
def _captions_to_text(caption_full_dict: Mapping[str, Any]) -> str:
return RE_MULTIPLE_SPACES.sub(" ", " ".join(d["alternatives"][0]["transcript"].strip()
for d in caption_full_dict["results"][:-1])).strip()
def _parse_caption_time(s: str) -> float:
return float(s[:-1])
def _load_caption(path: str) -> Optional[Mapping[str, Any]]:
with open(path) as file:
caption_full_dict = json.load(file)
if results := caption_full_dict["results"]:
tokens_info = results[-1]["alternatives"][0]["words"]
else:
tokens_info = None
if tokens_info:
return { # Save some memory by just keeping what we actually use.
"text": _captions_to_text(caption_full_dict),
"video_id": os.path.basename(path).rsplit(".", maxsplit=1)[0],
"tokens_info": [{
"word": wi["word"],
"start_time": _parse_caption_time(wi["startTime"]),
"end_time": _parse_caption_time(wi["endTime"]),
} for wi in tokens_info],
}
else:
return None # There are around 750/150k that fall here for different reasons.
def _add_caption_info_to_doc(doc: Doc, tokens_info: Sequence[Mapping[str, Any]]) -> Doc:
spacy2caption = spacy_alignments.get_alignments([t.text for t in doc], [w["word"] for w in tokens_info])[0]
for token, caption_token_indices in zip(doc, spacy2caption):
token._.start_time = tokens_info[caption_token_indices[0]]["start_time"]
token._.end_time = tokens_info[caption_token_indices[-1]]["end_time"]
return doc
def _create_docs() -> Iterator[Doc]:
caption_paths = list(_list_caption_paths(CAPTIONS_DIR))
# caption_paths = random.sample(caption_paths, min(len(caption_paths), 100))
# We don't keep the captions in memory as it can be a lot.
caption_it = (caption for path in caption_paths if (caption := _load_caption(path)))
doc_and_context_it = NLP.pipe(((c["text"], (c["video_id"], c["tokens_info"])) # noqa
for c in caption_it), as_tuples=True)
for doc, (video_id, tokens_info) in tqdm(doc_and_context_it, total=len(caption_paths), desc="Parsing"):
doc._.trf_data = None # It takes up a lot of memory.
doc._.video_id = video_id
yield _add_caption_info_to_doc(doc, tokens_info)
def _load_cached_docs() -> Iterator[Doc]:
print("Loading cached docs…")
with open(cached_path("parsed_docs"), "rb") as file:
return DocBin().from_bytes(file.read()).get_docs(NLP.vocab)
def _save_docs(docs: Iterable[Doc]) -> None:
print("Saving cached docs…")
with open("/tmp/.docs", "wb") as file:
file.write(DocBin(store_user_data=True, docs=docs).to_bytes())
if os.environ.get("LOAD_CACHED_DOCS", "0").lower() in {"1", "true", "y"}:
DOCS = list(_load_cached_docs())
else:
DOCS = list(_create_docs())
if os.environ.get("SAVE_CACHED_DOCS", "0").lower() in {"1", "true", "y"}:
_save_docs(DOCS)
print("Docs ready")
def search_in_subtitles(pattern: Iterable[Mapping[str, Any]]) -> Iterator[Span]:
matcher = Matcher(NLP.vocab)
matcher.add("search", [pattern])
for doc in DOCS:
for m in matcher(doc):
yield doc[m[1]:m[2]]
| 4,180 | 34.432203 | 111 | py |
fitclip | fitclip-main/aligner/video_text_module.py | from typing import Any, Literal, Mapping, MutableMapping, Optional, Sequence, Tuple, Union
import math
import pytorch_lightning as pl
import torch.distributed.nn
from overrides import overrides
from torch import nn
from torch.nn.modules.loss import _Loss
from aligner.encoder.video_text_encoder import TYPE_OUTPUT, VideoTextEncoder
from aligner.loss import NCELoss
from util.tensor_utils import all_gather
TYPE_INPUT = MutableMapping[str, Any]
TYPE_SPLIT = Literal["train", "val"]
def log_lr(pl_module: pl.LightningModule, **kwargs) -> None:
for i, optimizer in enumerate(pl_module.trainer.optimizers):
for j, param_group in enumerate(optimizer.param_groups):
if (lr := param_group.get("lr")) is not None: # noqa
pl_module.log(f"lr_{i}_group_{j}", lr, **kwargs)
class VideoTextLightningModule(pl.LightningModule): # noqa
def __init__(self, encoder: VideoTextEncoder, init_temperature: float = 0.05, min_temperature: float = 0.001,
fit_temperature: bool = True, loss: Optional[_Loss] = None) -> None:
super().__init__()
self.encoder = encoder
# Use the temperature as in CLIP: save it in log-space and fit it along with the model.
self.logit_scale = nn.Parameter(torch.tensor([- math.log(init_temperature)]), requires_grad=fit_temperature)
# The following constant is set also as a parameter, so it's moved to the correct device automatically.
self.max_logit_scale = nn.Parameter(torch.tensor([- math.log(min_temperature)]), requires_grad=False)
self.loss = loss or NCELoss()
@overrides(check_signature=False)
def forward(self, batch: TYPE_INPUT,
_batch_idx: int = 0) -> Union[TYPE_OUTPUT, Tuple[torch.Tensor, torch.Tensor, Sequence[str]]]:
batch.pop("video_id", None)
return self.encoder(**batch)
def _step(self, batch: TYPE_INPUT, batch_idx: int = 0) -> TYPE_OUTPUT:
return self(batch, batch_idx)
@overrides(check_signature=False)
def training_step(self, batch: TYPE_INPUT, _batch_idx: int = 0) -> TYPE_OUTPUT:
output = self._step(batch, _batch_idx)
# Need to log the step because PL doesn't log it in Neptune.
first_video_value = next(v for k, v in batch.items() if k.startswith("video"))
self.log("step", float(self.global_step), batch_size=len(first_video_value))
return output
def _step_end(self, output: TYPE_OUTPUT, split: TYPE_SPLIT,
log_kwargs: Optional[Mapping[str, Any]] = None) -> Union[torch.Tensor, TYPE_OUTPUT]:
log_kwargs = log_kwargs or {}
encoded_video, encoded_text = all_gather(self, output, sync_grads=split == "train")
batch_size = len(encoded_video)
logit_scale = self.logit_scale.exp()
scores = logit_scale * encoded_video @ encoded_text.T
loss = self.loss(scores)
# Note train loss it's already shown in the progress bar by PL by default.
#
# Note that we need to pass the batch size in the first step log
# as it can't be easily inferred by PL in our case.
self.log(f"loss/{split}", loss, prog_bar=split != "train", batch_size=batch_size, **log_kwargs)
if split == "train":
self.log("batch_size", float(batch_size), batch_size=batch_size)
self.log("temperature", 1 / logit_scale, batch_size=batch_size)
return loss if split == "train" else (encoded_video, encoded_text)
@overrides(check_signature=False)
def training_step_end(self, output: TYPE_OUTPUT) -> torch.Tensor:
loss = self._step_end(output, split="train")
log_lr(self)
return loss
@overrides(check_signature=False)
def predict_step(self, batch: TYPE_INPUT, batch_idx: int = 0) -> Mapping[str, torch.Tensor]:
encoded_video, encoded_text = self._step(batch, batch_idx)
return {
"encoded_videos": encoded_video,
"encoded_texts": encoded_text,
"video_ids": batch["video_id"]
}
@overrides(check_signature=False)
def optimizer_step(self, *args, **kwargs) -> None:
super().optimizer_step(*args, **kwargs)
if self.logit_scale >= self.max_logit_scale:
self.logit_scale.copy_(self.max_logit_scale)
| 4,376 | 43.663265 | 116 | py |
fitclip | fitclip-main/aligner/__main__.py | import logging
import os
from time import strftime
from typing import Mapping, Optional
import hydra
import torch
from omegaconf import DictConfig
from pytorch_lightning.loggers import NeptuneLogger, TensorBoardLogger
from aligner.cli import create_model_data_module_trainer_and_ckpt_path, init_cli
from aligner.logger_utils import get_logger_by_type
# Note it's better to have this as a module, so it's importable and DDP works fine in debug mode.
# Maybe this issue is caused by Hydra moving the CWD to somewhere else.
LOGGER = logging.getLogger(__name__)
# Set an env var, if empty, to the desired working directory in sweep mode. Then we read it from the config.
# This way we make sure all processes use the same folder.
os.environ.setdefault("SWEEP_DIR", f"multirun/{strftime('%Y-%m-%d')}/{strftime('%H-%M-%S')}")
@hydra.main(config_path="../config", config_name="trainer")
def main(cfg: DictConfig) -> Optional[float]:
init_cli(cfg)
if cfg.get("trainer", {}).get("strategy") == "dp":
LOGGER.warning("DP strategy not supported by the current metric logging scheme."
" See https://torchmetrics.readthedocs.io/en/stable/pages/lightning.html#logging-torchmetrics")
model, data_module, trainer, ckpt_path = create_model_data_module_trainer_and_ckpt_path(cfg)
output = None
if cfg.command == "train":
if cfg.get("validate_before_training"):
LOGGER.info("Validation before training started.")
with torch.inference_mode():
metrics_list = trainer.validate(model, datamodule=data_module, ckpt_path=ckpt_path)
LOGGER.info("Validation before training finished.")
if (tb_logger := get_logger_by_type(trainer, TensorBoardLogger)) and not tb_logger._default_hp_metric:
tb_logger.log_hyperparams(model.hparams_initial, metrics={k: v for metrics in metrics_list
for k, v in metrics.items()})
LOGGER.info("Training started.")
trainer.fit(model, datamodule=data_module, ckpt_path=ckpt_path)
if optimized_metric_name := cfg.get("optimized_metric_name"):
output = trainer.callback_metrics.get(optimized_metric_name)
elif cfg.command == "tune":
assert ckpt_path is None, "Checkpoint path not supported when tuning."
if trainer._accelerator_connector.is_distributed:
LOGGER.warning("Tuning with the PL Trainer is known to have some issues in distributed settings."
" See e.g. https://github.com/PyTorchLightning/pytorch-lightning/issues/4280")
LOGGER.info("Tuning started.")
trainer.tune(model, datamodule=data_module)
elif cfg.command in {"evaluate", "validate"}:
with torch.inference_mode():
trainer.validate(model, datamodule=data_module, ckpt_path=ckpt_path)
elif cfg.command == "test":
with torch.inference_mode():
trainer.test(model, datamodule=data_module, ckpt_path=ckpt_path)
elif cfg.command == "predict":
if trainer._accelerator_connector.is_distributed:
LOGGER.warning("Predicting with the PL Trainer is known to have some issues in distributed settings."
" See e.g. https://github.com/PyTorchLightning/pytorch-lightning/issues/10618")
output_path = cfg.get("output_path", "predictions.pt")
with torch.inference_mode():
predictions = trainer.predict(model, datamodule=data_module, ckpt_path=ckpt_path)
assert predictions
first_prediction = predictions[0]
assert isinstance(first_prediction, Mapping)
keys = first_prediction
predictions_map = {k: torch.cat([prediction[k] for prediction in predictions])
if isinstance(first_prediction[k], torch.Tensor)
else [p for prediction in predictions for p in prediction[k]]
for k in keys}
torch.save(predictions_map, output_path)
else:
raise ValueError(f"Unrecognized command: {cfg.command}")
if (neptune_logger := get_logger_by_type(trainer, NeptuneLogger)) and trainer.is_global_zero:
# In a Hydra multirun (sweep) scenario, Neptune experiments from finished runs are marked as still running
neptune_logger.run.stop()
# Return the optimized metric value for hparam search.
return output
if __name__ == "__main__":
main()
| 4,715 | 43.490566 | 118 | py |
fitclip | fitclip-main/aligner/logger_utils.py | from typing import Optional, Type, TypeVar
import pytorch_lightning as pl
from pytorch_lightning.loggers import LightningLoggerBase, LoggerCollection
T = TypeVar("T", bound=LightningLoggerBase)
def get_logger_by_type(trainer: pl.Trainer, logger_class: Type[T]) -> Optional[T]:
if isinstance(trainer.logger, LoggerCollection):
return next((logger for logger in trainer.logger._logger_iterable if isinstance(logger, logger_class)), None)
elif isinstance(trainer.logger, logger_class):
return trainer.logger
else:
return None
| 564 | 32.235294 | 117 | py |
fitclip | fitclip-main/aligner/teacher_student.py | import itertools
from typing import Iterable, Mapping, MutableMapping, Optional, Tuple, Union
import torch.distributed.nn
from overrides import overrides
from torch import nn
from aligner.encoder import video_text_encoder
from aligner.encoder.video_text_encoder import TYPE_TOKENIZER, VideoTextEncoder
from aligner.loss import TeacherStudentNCELoss
from aligner.text_video_retrieval import TextVideoRetrievalLightningModule
from aligner.video_text_module import TYPE_INPUT, TYPE_SPLIT, log_lr
from util.tensor_utils import all_gather, pad, split_in_collection
TYPE_OUTPUT = Tuple[video_text_encoder.TYPE_OUTPUT, video_text_encoder.TYPE_OUTPUT]
TYPE_MULTI_OUTPUT = Mapping[str, TYPE_OUTPUT]
def _replace_in_tokenized_text(tokenized_text: MutableMapping[str, torch.Tensor],
new_tokenized_text: Mapping[str, torch.Tensor], start_idx: int, end_idx: int,
tokenizer: TYPE_TOKENIZER) -> None:
"""Replaces the content in the tensor `tokenized_text` from the index `start_idx` to `end_idx` (exclusive) for
`new_tokenized_text`.
When it needs to know details about the tokenization, it uses `tokenizer`.
"""
for k in tokenized_text:
padding_value = 0 if "mask" in k else getattr(tokenizer, "pad_token_id", 0)
# We suppose right padding.
if tokenized_text[k].shape[1] > new_tokenized_text[k].shape[1]:
padded = pad(new_tokenized_text[k], min_size=tokenized_text[k].shape[1], value=padding_value)
tokenized_text[k] = torch.cat((tokenized_text[k][:start_idx], padded, tokenized_text[k][end_idx:]))
elif tokenized_text[k].shape[1] < new_tokenized_text[k].shape[1]:
padded = pad(tokenized_text[k], min_size=new_tokenized_text[k].shape[1], value=padding_value)
tokenized_text[k] = torch.cat((padded[:start_idx], new_tokenized_text[k], padded[end_idx:]))
else:
tokenized_text[k] = torch.cat((tokenized_text[k][:start_idx], new_tokenized_text[k],
tokenized_text[k][end_idx:]))
class TeacherStudentLightningModule(TextVideoRetrievalLightningModule): # noqa
"""
Distillation training module.
If specified, `prompts` is used with the unlabeled dataset videos instead of the labels it provides (if any).
"""
def __init__(self, encoder: VideoTextEncoder, teacher: VideoTextEncoder, labeled_dataset_name: str = "labeled",
labeled_dataset_loss_share: Optional[float] = None,
dataset_names: Iterable[str] = ("labeled", "unlabeled"), prompts: Optional[Iterable[str]] = None,
**kwargs) -> None:
super().__init__(encoder=encoder, dataset_names=dataset_names, **kwargs)
self.teacher = teacher
assert self.dataset_names, "This module uses dataset names."
assert len(self.dataset_names) == 2, "The current implementation needs exactly 2 datasets."
# FIXME: it doesn't work with different datasets for training and evaluation, because it needs certain names
# for training; and this logic assumes the same dataset names for both.
if labeled_dataset_loss_share is None:
self.dataset_loss_share = {name: 1 / len(self.dataset_names) for name in self.dataset_names}
else:
self.dataset_loss_share = {labeled_dataset_name: labeled_dataset_loss_share}
self.dataset_loss_share.update((name, (1 - labeled_dataset_loss_share) / (len(self.dataset_names) - 1))
for name in self.dataset_names
if name != labeled_dataset_name)
self.teacher_student_logit_scale = nn.Parameter(self.logit_scale.clone(),
requires_grad=self.logit_scale.requires_grad)
# noinspection SpellCheckingInspection
self.teacher_student_loss = TeacherStudentNCELoss(reduction="batchmean")
for p in self.teacher.parameters():
p.requires_grad = False
self.labeled_dataset_name = labeled_dataset_name
self.unlabeled_dataset_name = next(k for k in self.dataset_names if k != labeled_dataset_name)
if prompts is None:
self.tokenized_prompts = None
self.teacher_tokenized_prompts = None
else:
prompts = list(prompts)
# We use parameters so the device and dtype are moved correctly along with this module.
self.tokenized_prompts = nn.ParameterDict((k, nn.Parameter(v, requires_grad=False)) # noqa
for k, v in encoder.get_tokenizer()(prompts).items())
self.teacher_tokenized_prompts = nn.ParameterDict((k, nn.Parameter(v, requires_grad=False)) # noqa
for k, v in teacher.get_tokenizer()(prompts).items())
@overrides(check_signature=False)
def _step(self, batch: TYPE_INPUT, _batch_idx: int = 0) -> TYPE_OUTPUT:
# Note we pass the labeled dataset portion to the teacher, but then we don't use it.
return self({"video": batch["video_student"], "text": batch["text_student"]}), \
self.teacher(video=batch["video_teacher"], text=batch["text_teacher"])
@overrides(check_signature=False)
def training_step(self, batch: TYPE_INPUT, _batch_idx: int = 0) -> TYPE_MULTI_OUTPUT:
keys, lengths = zip(*((key, sum(1 for _ in group))
for key, group in itertools.groupby(dataset for dataset in batch.pop("dataset"))))
assert len(keys) == len(self.dataset_names), "All datasets should be present in each batch."
if self.tokenized_prompts is None:
unlabeled_dataset_idx = None
else:
unlabeled_dataset_idx = keys.index(self.unlabeled_dataset_name)
start_idx_in_batch = sum(lengths[i] for i in range(unlabeled_dataset_idx))
end_idx_in_batch = start_idx_in_batch + lengths[unlabeled_dataset_idx]
_replace_in_tokenized_text(tokenized_text=batch["text_student"],
new_tokenized_text=self.tokenized_prompts, start_idx=start_idx_in_batch,
end_idx=end_idx_in_batch, tokenizer=self.encoder.get_tokenizer())
_replace_in_tokenized_text(tokenized_text=batch["text_teacher"],
new_tokenized_text=self.teacher_tokenized_prompts,
start_idx=start_idx_in_batch, end_idx=end_idx_in_batch,
tokenizer=self.teacher.get_tokenizer())
output = self._step(batch, _batch_idx)
# Need to log the step because PL doesn't log it in Neptune.
first_video_value = next(v for k, v in batch.items() if k.startswith("video"))
self.log(f"step", self.global_step, batch_size=len(first_video_value))
if self.tokenized_prompts is None:
split_output = split_in_collection(output, lengths)
else:
text_split_sections = list(lengths)
text_split_sections[unlabeled_dataset_idx] = len(next(iter(self.tokenized_prompts.values())))
student_video_sections = split_in_collection(output[0][0], lengths)
student_text_sections = split_in_collection(output[0][1], text_split_sections)
teacher_video_sections = split_in_collection(output[1][0], lengths)
teacher_text_sections = split_in_collection(output[1][1], text_split_sections)
split_output = (((student_video_sections[i], student_text_sections[i]),
(teacher_video_sections[i], teacher_text_sections[i]))
for i in range(len(student_video_sections)))
return dict(zip(keys, split_output))
def _dataset_step_end(self, output: TYPE_OUTPUT, split: TYPE_SPLIT,
dataset_name: Optional[str] = None) -> Union[torch.Tensor, video_text_encoder.TYPE_OUTPUT]:
gathered_output = all_gather(self, output, sync_grads=split == "train")
(encoded_video, encoded_text), (teacher_encoded_video, teacher_encoded_text) = gathered_output
batch_size = len(encoded_video)
logit_scale = self.logit_scale.exp()
scores = logit_scale * encoded_video @ encoded_text.T
if dataset_name == self.labeled_dataset_name:
loss = self.loss(scores)
else:
teacher_student_logit_scale = self.teacher_student_logit_scale.exp()
teacher_scores = teacher_student_logit_scale * teacher_encoded_video @ teacher_encoded_text.T
loss = self.teacher_student_loss(scores, teacher_scores) * teacher_student_logit_scale ** 2
if split == "train":
# Note that we need to pass the batch size in the first step log
# as it can't be easily inferred by PL in our case.
self.log("batch_size", float(batch_size), batch_size=batch_size)
self.log("temperature/labeled", 1 / logit_scale)
self.log("temperature/unlabeled", 1 / teacher_student_logit_scale)
prefix = f"loss/{split}_{dataset_name}" if dataset_name else f"loss/{split}"
# Note that we need to pass the batch size in the first step log
# as it can't be easily inferred by PL in our case.
self.log(prefix, loss, prog_bar=split != "train", batch_size=batch_size, add_dataloader_idx=False)
return loss if split == "train" else (encoded_video, encoded_text)
@overrides(check_signature=False)
def training_step_end(self, output: TYPE_MULTI_OUTPUT) -> torch.Tensor:
loss = sum(self._dataset_step_end(batch, split="train", dataset_name=name) * self.dataset_loss_share[name]
for name, batch in output.items())
self.log("loss/train", loss) # Note train loss it's already shown in the progress bar by PL by default.
log_lr(self)
return loss
@overrides(check_signature=False)
def _validation_dataset_step_end(self, output: TYPE_OUTPUT,
dataset_name: Optional[str] = None) -> video_text_encoder.TYPE_OUTPUT:
return self._dataset_step_end(output, split="val", dataset_name=dataset_name)
@overrides(check_signature=False)
def optimizer_step(self, *args, **kwargs) -> None:
super().optimizer_step(*args, **kwargs)
if self.teacher_student_logit_scale >= self.max_logit_scale:
self.teacher_student_logit_scale.copy_(self.max_logit_scale)
| 10,735 | 54.05641 | 117 | py |
fitclip | fitclip-main/aligner/loss.py | from typing import Literal
import torch
from overrides import overrides
from torch.nn import functional as F
from torch.nn.modules.loss import _Loss
TYPE_REDUCTION = Literal["none", "mean", "sum"]
# noinspection SpellCheckingInspection
TYPE_REDUCTION_KL_DIV = Literal["none", "batchmean", "mean", "sum"]
def _rows_to_columns_nce_loss(scores: torch.Tensor, reduction: TYPE_REDUCTION = "mean") -> torch.Tensor:
loss = - F.log_softmax(scores, dim=-1).diag()
if reduction == "mean":
return loss.mean()
elif reduction == "sum":
return loss.sum()
else:
return loss
def nce_loss(scores: torch.Tensor, reduction: TYPE_REDUCTION = "mean") -> torch.Tensor:
return (_rows_to_columns_nce_loss(scores, reduction=reduction)
+ _rows_to_columns_nce_loss(scores.T, reduction=reduction))
def _rows_to_columns_teacher_student_nce_loss(scores: torch.Tensor, teacher_scores: torch.Tensor,
reduction: TYPE_REDUCTION_KL_DIV = "mean") -> torch.Tensor:
logits = F.log_softmax(scores, dim=-1)
teacher_probs = F.softmax(teacher_scores, dim=-1)
return F.kl_div(logits, teacher_probs, reduction=reduction)
def teacher_student_nce_loss(scores: torch.Tensor, teacher_scores: torch.Tensor,
reduction: TYPE_REDUCTION_KL_DIV = "mean") -> torch.Tensor:
return (_rows_to_columns_teacher_student_nce_loss(scores, teacher_scores, reduction=reduction)
+ _rows_to_columns_teacher_student_nce_loss(scores.T, teacher_scores.T, reduction=reduction))
class NCELoss(_Loss):
@overrides(check_signature=False)
def forward(self, scores: torch.Tensor) -> torch.Tensor:
return nce_loss(scores, reduction=self.reduction) # noqa
class TeacherStudentNCELoss(_Loss):
@overrides(check_signature=False)
def forward(self, scores: torch.Tensor, teacher_scores: torch.Tensor) -> torch.Tensor:
return teacher_student_nce_loss(scores, teacher_scores, reduction=self.reduction) # noqa
class SimilarityLoss(_Loss):
@overrides(check_signature=False)
def forward(self, scores: torch.Tensor) -> torch.Tensor:
# Note we actually don't need all the scores.
loss = - torch.log(torch.sigmoid(scores.diag()))
if self.reduction == "mean":
return loss.mean()
elif self.reduction == "sum":
return loss.sum()
else:
return loss
| 2,447 | 36.090909 | 105 | py |
fitclip | fitclip-main/aligner/text_video_retrieval.py | from collections import OrderedDict
from typing import Iterable, Mapping, Optional, Sequence, Tuple, Union
import torch
import torch.distributed.nn
from overrides import overrides
from torch import nn
from torchmetrics import Metric, Recall
from aligner.encoder.video_text_encoder import TYPE_OUTPUT
from aligner.metrics import MedianRank, Rank
from aligner.video_text_module import TYPE_INPUT, VideoTextLightningModule
from util.tensor_utils import all_gather
class TextVideoRetrievalLightningModule(VideoTextLightningModule): # noqa
def __init__(self, *args, dataset_names: Optional[Iterable[str]] = None, compute_rank: bool = False,
**kwargs) -> None:
super().__init__(*args, **kwargs)
metrics_dict = {"r1": Recall(), "r5": Recall(top_k=5), "r10": Recall(top_k=10), "mr": MedianRank()}
if compute_rank:
metrics_dict["rank"] = Rank()
self.dataset_names = list(dataset_names) if dataset_names else None
self.multiple_datasets = self.dataset_names is not None and len(self.dataset_names) > 1
if self.multiple_datasets:
assert all("_" not in name for name in self.dataset_names), \
"Underscores in dataset names are problematic because of how we get their corresponding metrics."
self.metrics: Mapping[str, Metric] = nn.ModuleDict((f"{name}_{dataset_name}", metric.clone()) # noqa
for dataset_name in self.dataset_names
for name, metric in metrics_dict.items())
else:
self.metrics: Mapping[str, Metric] = nn.ModuleDict(metrics_dict)
@overrides(check_signature=False)
def validation_step(self, batch: TYPE_INPUT, batch_idx: int = 0,
dataloader_idx: Optional[int] = None) -> Tuple[TYPE_OUTPUT, Optional[int]]:
return self._step(batch, batch_idx), dataloader_idx
def _validation_dataset_step_end(self, output: TYPE_OUTPUT, dataset_name: Optional[str] = None) -> TYPE_OUTPUT:
encoded_video, encoded_text = all_gather(self, output)
batch_size = len(encoded_video)
logit_scale = self.logit_scale.exp()
scores = logit_scale * encoded_video @ encoded_text.T
loss = self.loss(scores)
# Note that we need to pass the batch size in the first step log
# as it can't be easily inferred by PL in our case.
key = "loss/val" + ("" if dataset_name is None else f"_{dataset_name}")
self.log(key, loss, prog_bar=True, batch_size=batch_size, add_dataloader_idx=False)
return encoded_video, encoded_text
@overrides(check_signature=False)
def validation_step_end(self, output: Tuple[TYPE_OUTPUT, int]) -> TYPE_OUTPUT:
step_output, data_loader_idx = output
assert self.multiple_datasets == (data_loader_idx is not None)
dataset_name = self.dataset_names[data_loader_idx] if self.multiple_datasets else None
return self._validation_dataset_step_end(step_output, dataset_name=dataset_name)
def _validate_dataset(self, outputs: Sequence[TYPE_OUTPUT], dataset_name: Optional[str] = None) -> None:
assert self.multiple_datasets == (dataset_name is not None)
encoded_videos, encoded_texts = (torch.cat(x) for x in zip(*outputs))
batch_size = len(encoded_videos)
scores = encoded_texts @ encoded_videos.T
target = torch.arange(scores.shape[-1], device=scores.device)
for name, metric in self.metrics.items():
if not dataset_name or name.endswith(f"_{dataset_name}"):
metric(scores, target)
# Note that we need to pass the batch size in the first step log
# as it can't be easily inferred by PL in our case.
self.log(name, metric, prog_bar=True, batch_size=batch_size, add_dataloader_idx=False)
@overrides(check_signature=False)
def validation_epoch_end(self, outputs: Union[Sequence[TYPE_OUTPUT], Sequence[Sequence[TYPE_OUTPUT]]]) -> None:
if self.multiple_datasets:
for i, (name, dataset_output) in enumerate(zip(self.dataset_names, outputs)):
# Necessary to set the current data loader ID so PL knows to which one the logged metrics belong
# (because it returns the metrics by data loader).
self._current_dataloader_idx = i
self._validate_dataset(dataset_output, dataset_name=name) # noqa
self._current_dataloader_idx = None
else:
self._validate_dataset(outputs)
if "rank" in self.metrics:
self.print(self.metrics["rank"].compute().tolist())
@overrides
def load_state_dict(self, state_dict: "OrderedDict[str, torch.Tensor]", strict: bool = True):
# If it's exactly this class, then ignore any teacher-related thing.
# We do it here, so we can control it more, and avoid bugs with a general solution.
if type(self) is TextVideoRetrievalLightningModule:
incompatible_keys = super().load_state_dict(state_dict, strict=False)
unexpected_keys = set(incompatible_keys.unexpected_keys)
for key in incompatible_keys.unexpected_keys:
if key.startswith("teacher"):
unexpected_keys.remove(key)
# We then do as in super:
if strict:
error_msgs = []
if unexpected_keys:
unexpected_key_str = ", ".join(f'"{k}"' for k in unexpected_keys)
error_msgs.append(f"Unexpected key(s) in state_dict: {unexpected_key_str}. ")
if incompatible_keys.missing_keys:
missing_keys_str = ', '.join(f'"{k}"' for k in incompatible_keys.missing_keys)
error_msgs.append(f"Missing key(s) in state_dict: {missing_keys_str}. ")
if error_msgs:
error_msgs_str = "\n\t".join(error_msgs)
raise RuntimeError(f"Error(s) in loading state_dict for {self.__class__.__name__}:\n\t"
f"{error_msgs_str}")
return incompatible_keys
else:
return super().load_state_dict(state_dict, strict)
| 6,325 | 46.924242 | 115 | py |
fitclip | fitclip-main/aligner/video_text_classification.py | import logging
import math
from typing import Any, Iterable, Mapping, Optional, Sequence, TypeVar
import torch
from overrides import overrides
from pytorch_lightning.callbacks import RichProgressBar
from pytorch_lightning.utilities.apply_func import apply_to_collection
from torch import nn
from torchmetrics import Accuracy, Metric
from aligner.encoder.video_text_encoder import VideoTextEncoder
from aligner.metrics import MedianRank
from aligner.video_text_module import VideoTextLightningModule
from util import iter_utils
LOGGER = logging.getLogger(__name__)
T = TypeVar("T")
def batch_tokenized_text(tokenized: Mapping[str, Sequence[T]], n: int) -> Iterable[Mapping[str, T]]:
tokenized_dicts = {k: iter(iter_utils.batch_sequence(v, n)) for k, v in tokenized.items()}
length = math.ceil(len(next(iter(tokenized.values()))) / n)
for _ in range(length):
yield {k: next(tokenized_dicts[k]) for k in tokenized}
class VideoTextClassificationLightningModule(VideoTextLightningModule): # noqa
def __init__(self, encoder: VideoTextEncoder, labels: Iterable[str], templates: Optional[Iterable[str]],
return_metrics_by_class: bool = False, **kwargs) -> None:
super().__init__(encoder, **kwargs)
labels = list(labels)
label_count = len(labels)
# If different templates are provided, we used them for each label
# and reset the labels to be {labels} x {templates}.
if templates:
templates = list(templates)
self.template_count = len(templates)
labels = [template.format(label) for label in labels for template in templates]
else:
self.template_count = 1
# We tokenize all the labels but defer the encoding until the model is in the device.
tokenized_labels = encoder.get_tokenizer()(labels)
device = next(encoder.parameters()).device
tokenized_labels = apply_to_collection(tokenized_labels, torch.Tensor, torch.Tensor.to, device)
self.tokenized_labels = nn.ParameterDict(apply_to_collection(tokenized_labels, torch.Tensor, nn.Parameter,
requires_grad=False))
# We encode just one label to allocate the size correctly.
encoded_text = self.encoder.encode_text({k: v[:1] for k, v in tokenized_labels.items()})
self.encoded_labels = nn.Parameter(torch.empty(label_count, encoded_text.shape[-1]), requires_grad=False)
self.metrics: Mapping[str, Metric] = nn.ModuleDict({"a1": Accuracy(), "a5": Accuracy(top_k=5),
"mr": MedianRank()})
if return_metrics_by_class:
self.metrics_by_class = nn.ModuleDict({f"a1_{k}": Accuracy() for k in range(label_count)})
else:
self.metrics_by_class = None
def _on_start(self) -> None:
# Note that for training they should be encoded at running time, not here.
# But we aren't training any text classification model but evaluating them.
#
# We compute them here and not during init because here the model is already in the device.
# This is especially much faster than in CPU (init) when using templates.
batch_size = 32
callback = next(callback for callback in self.trainer.callbacks if isinstance(callback, RichProgressBar))
progress = callback.progress
if self.trainer.is_global_zero:
progress_task = progress.add_task(
description="Encoding the labels",
total=math.ceil(len(next(iter(self.tokenized_labels.values()))) / batch_size))
else:
progress_task = None
encoded_label_list = []
for tokenized_labels_batch in batch_tokenized_text(self.tokenized_labels, batch_size):
encoded_label_list.append(self.encoder.encode_text(tokenized_labels_batch))
if progress_task is not None:
progress.update(progress_task, advance=1)
encoded_labels = torch.cat(encoded_label_list)
encoded_labels = encoded_labels.reshape(-1, self.template_count, encoded_labels.shape[1]).mean(dim=1)
self.encoded_labels.copy_(encoded_labels)
if progress_task is not None:
# If we remove it, it later fails, not sure why. So we just hide it.
progress.update(progress_task, visible=False)
@overrides
def on_validation_start(self) -> None:
self._on_start()
@overrides
def on_test_start(self) -> None:
self._on_start()
@overrides
def on_predict_start(self) -> None:
self._on_start()
@overrides(check_signature=False)
def forward(self, video: torch.Tensor) -> torch.Tensor:
return self.encoder.encode_video(video) @ self.encoded_labels.T
@overrides(check_signature=False)
def validation_step(self, batch: Mapping[str, Any], _batch_idx: int = 0) -> None:
scores = self(batch["video"])
label_id = batch["target"][1]
for name, metric in self.metrics.items():
metric(scores, label_id)
# Note that we need to pass the batch size in the first step log
# as it can't be easily inferred by PL in our case.
self.log(name, metric, prog_bar=True, batch_size=len(batch["video"]))
if self.metrics_by_class is not None:
for scores_instance, label_id_instance in zip(scores, label_id):
metric = self.metrics_by_class[f"a1_{label_id_instance}"]
metric(scores_instance.unsqueeze(0), label_id_instance.unsqueeze(0))
self.log(f"a1_{label_id_instance}", metric, batch_size=1)
@overrides(check_signature=False)
def predict_step(self, batch: Mapping[str, Any], _batch_idx: int = 0) -> Mapping[str, torch.Tensor]:
return {
"predictions": self(batch["video"]).argmax(dim=-1),
"labels": batch["target"][1],
"video_ids": batch["video_id"],
}
| 6,045 | 41.879433 | 114 | py |
fitclip | fitclip-main/aligner/cli.py | import copy
import logging
import warnings
from types import MethodType
from typing import Any, Mapping, Optional, Tuple, Type
import hydra
import pytorch_lightning as pl
from cached_path import cached_path
from omegaconf import DictConfig
from pytorch_lightning import seed_everything
from torch.optim import Optimizer
from aligner.data.data_module_group import DataModuleStructuredGroup, EvalDataModuleGroup, MixedBatchDataModule, \
TrainAndEvalDataModules
from aligner.data.video_data_module import ENCODER_OR_ENCODER_MAP, VideoClassificationDataModule
from aligner.encoder.video_text_encoder import VideoTextEncoder
from aligner.video_text_classification import VideoTextClassificationLightningModule
from aligner.video_text_module import VideoTextLightningModule
LOGGER = logging.getLogger(__name__)
# This is because PL can't automatically infer the batch size, that's needed for logging. But we set it manually
# within the modules.
warnings.filterwarnings("ignore", message=r"^Trying to infer the `batch_size` from an ambiguous collection\. .+")
def fullname(klass: Type[Any]) -> str:
return f"{klass.__module__}.{klass.__qualname__}"
def set_logging_level(level: int) -> None:
logging.basicConfig(level=level)
# `basicConfig` will only work for new loggers, so we also need to set up the existing ones:
for logger in logging.root.manager.loggerDict.values():
if isinstance(logger, logging.Logger): # Otherwise, it could be a `logging.PlaceHolder`.
logger.setLevel(level)
logging.getLogger().setLevel(level) # The root logger is not present in the previous iterable.
def init_cli(cfg: DictConfig) -> None:
if cfg.get("silent"):
set_logging_level(logging.WARNING)
else:
set_logging_level(logging.INFO)
if "seed" in cfg:
seed_everything(cfg.seed, workers=True)
def instantiate_data_module(cfg: DictConfig, encoder: ENCODER_OR_ENCODER_MAP) -> pl.LightningDataModule:
kwargs = {}
if cfg._target_ in {fullname(klass) for klass in [DataModuleStructuredGroup, EvalDataModuleGroup,
MixedBatchDataModule]}:
if isinstance(cfg.data_modules, Mapping):
kwargs["data_modules"] = {k: instantiate_data_module(v, encoder=encoder) # noqa
for k, v in cfg.data_modules.items()}
else:
kwargs["data_modules"] = {instantiate_data_module(cfg_dm, encoder=encoder)
for cfg_dm in cfg.data_modules}
# Convert because otherwise the passed `data_modules` is a `DictConfig` instead of a `dict` and
# `train_dataloader` can't respect the same collection type as `DictConfig` can't have normal classes.
kwargs["_convert_"] = "all"
elif cfg._target_ == fullname(TrainAndEvalDataModules):
kwargs["train_data_module"] = instantiate_data_module(cfg.train_data_module, encoder=encoder)
kwargs["eval_data_module"] = instantiate_data_module(cfg.eval_data_module, encoder=encoder)
else:
kwargs["encoder"] = encoder
# Necessary as well when the encoder is a dict.
kwargs["_convert_"] = "all"
return hydra.utils.instantiate(cfg, **kwargs)
def create_model_data_module_trainer_and_ckpt_path(
cfg: DictConfig, model_kwargs: Optional[Mapping[str, Any]] = None) -> Tuple[VideoTextLightningModule,
pl.LightningDataModule, pl.Trainer,
str]:
model_kwargs = model_kwargs or {}
LOGGER.info(f"Instantiating encoder <{getattr(cfg.encoder, '_target_', type(cfg.encoder).__name__)}>…")
encoder: ENCODER_OR_ENCODER_MAP = hydra.utils.instantiate(cfg.encoder)
if isinstance(encoder, Mapping) and cfg.get("use_student_encoder_for_data_preprocessing"):
encoder_for_data_preprocessing = encoder["student"]
else:
encoder_for_data_preprocessing = encoder
LOGGER.info("Encoder instantiated.")
LOGGER.info(f"Instantiating data module <{cfg.data._target_}>…")
data_module = instantiate_data_module(cfg.data, encoder=encoder_for_data_preprocessing)
LOGGER.info("Data module instantiated.")
LOGGER.info(f"Instantiating model <{cfg.model._target_}>…")
if isinstance(encoder, Mapping):
model_kwargs.setdefault("encoder", encoder["student"])
model_kwargs.setdefault("teacher", encoder["teacher"])
else:
model_kwargs.setdefault("encoder", encoder)
if isinstance(data_module, VideoClassificationDataModule):
assert isinstance(encoder_for_data_preprocessing, VideoTextEncoder), \
"Encoder can't be a mapping and has to support text when doing classification."
cfg.model._target_ = fullname(VideoTextClassificationLightningModule)
model_kwargs.setdefault("labels", data_module.categories)
model_kwargs.setdefault("templates", data_module.templates)
if prompts_path := cfg.get("prompts"): # noqa
with open(cached_path(prompts_path)) as file:
model_kwargs.setdefault("prompts", [stripped_line
for line in file
if (stripped_line := line.strip())]) # noqa
model: VideoTextLightningModule = hydra.utils.instantiate(cfg.model, **model_kwargs)
LOGGER.info("Model instantiated.")
if "optimizer" in cfg:
LOGGER.info(f"Instantiating Optimizer <{cfg.optimizer._target_}>…")
def configure_optimizers(self: pl.LightningModule) -> Optimizer:
if (lr_ := self.hparams.get("lr")) is not None: # To be used by auto LR find.
cfg.optimizer["lr"] = lr_
return hydra.utils.instantiate(cfg.optimizer, self.parameters())
model.configure_optimizers = MethodType(configure_optimizers, model)
LOGGER.info("Optimizer instantiated.")
LOGGER.info(f"Instantiating trainer <{cfg.trainer._target_}>…")
trainer: pl.Trainer = hydra.utils.instantiate(cfg.trainer)
LOGGER.info("Trainer instantiated.")
# We do what `model.save_hyperparameters(cfg)` would do but without needing a current frame to get the args from.
# It turns out that, even if you provide args, it still checks the current frame for args, and set those
# conditioned by the provided args.
model._log_hyperparams = trainer.logger
model._set_hparams(cfg) # noqa
model._hparams_initial = copy.deepcopy(model._hparams)
ckpt_path = cached_path(cfg.checkpoint_path) if cfg.get("path") else None
return model, data_module, trainer, ckpt_path
| 6,809 | 44.099338 | 119 | py |
fitclip | fitclip-main/aligner/wise.py | import copy
from typing import Mapping, TypeVar
import torch
from torch import nn
T = TypeVar("T", bound=nn.Module)
def wise_state_dict(model1: T, model2: T, weight_for_2: float = 0.5) -> Mapping[str, torch.Tensor]:
state_dict1 = dict(model1.named_parameters())
state_dict2 = dict(model2.named_parameters())
assert set(state_dict1) == set(state_dict2)
return {k: (1 - weight_for_2) * state_dict1[k] + weight_for_2 * state_dict2[k] for k in state_dict1}
def wise(model1: T, model2: T, weight_for_2: float = 0.5, copy_model1: bool = True) -> T:
assert type(model1) is type(model2)
model = copy.deepcopy(model1 if copy_model1 else model2)
model.load_state_dict(wise_state_dict(model1, model2, weight_for_2=weight_for_2)) # noqa
return model
| 779 | 31.5 | 104 | py |
fitclip | fitclip-main/aligner/metrics.py | import torch
from overrides import overrides
from torchmetrics import Metric
class Rank(Metric):
is_differentiable: bool = False
higher_is_better: bool = False
full_state_update: bool = False
def __init__(self, **kwargs) -> None:
super().__init__(**kwargs)
self.add_state("ranks", default=[], dist_reduce_fx="cat")
@overrides(check_signature=False)
def update(self, predictions: torch.Tensor, target: torch.Tensor) -> None:
sorted_predicted_positions = predictions.argsort(dim=1, descending=True)
ranks = torch.where(sorted_predicted_positions == target.unsqueeze(-1))[1] # noqa
self.ranks.append(ranks)
@overrides
def compute(self) -> torch.Tensor:
# It could be already reduced depending on when we call it (e.g., at the epoch end).
return self.ranks if isinstance(self.ranks, torch.Tensor) else torch.cat(self.ranks)
class MeanRank(Rank):
@overrides
def compute(self) -> torch.Tensor:
return super().compute().mean() + 1
class MedianRank(Rank):
@overrides
def compute(self) -> torch.Tensor:
return super().compute().median() + 1
| 1,162 | 30.432432 | 92 | py |
fitclip | fitclip-main/aligner/transforms.py | """From https://github.com/pytorch/vision/blob/993325d/references/video_classification/transforms.py"""
import random
from typing import Any
import torch
import torch.nn as nn
from overrides import overrides
from torchvision.transforms import InterpolationMode, RandomResizedCrop, functional as F
from util.tensor_utils import pad
class ConvertBHWCtoBCHW(nn.Module):
"""Convert tensor from (B, H, W, C) to (B, C, H, W)."""
@overrides(check_signature=False)
def forward(self, v: torch.Tensor) -> torch.Tensor:
return v.permute(0, 3, 1, 2)
class ConvertBCHWtoCBHW(nn.Module):
"""Convert tensor from (B, C, H, W) to (C, B, H, W)."""
@overrides(check_signature=False)
def forward(self, v: torch.Tensor) -> torch.Tensor:
return v.permute(1, 0, 2, 3)
# Added by me:
class ConvertBHWCtoCBHW(nn.Module):
"""Convert tensor from (B, H, W, C) to (C, B, H, W)."""
@overrides(check_signature=False)
def forward(self, v: torch.Tensor) -> torch.Tensor:
return v.permute(3, 0, 1, 2)
class PadToMinFrames:
def __init__(self, min_frames: int, frame_dim: int = 0, padding_value: Any = 0) -> None:
self.min_frames = min_frames
self.frame_dim = frame_dim
self.padding_value = padding_value
def __call__(self, video: torch.Tensor) -> torch.Tensor:
return pad(video, min_size=self.min_frames, dim=self.frame_dim, value=self.padding_value)
class MaxFrames:
def __init__(self, max_frames: int, frame_dim: int = 0) -> None:
self.max_frames = max_frames
self.frame_dim = frame_dim
def __call__(self, video: torch.Tensor) -> torch.Tensor:
return video[(slice(None),) * self.frame_dim + (slice(None, self.max_frames),)]
class RandomResizedCropWithRandomInterpolation(RandomResizedCrop):
@overrides
def forward(self, img: torch.Tensor) -> torch.Tensor:
i, j, h, w = self.get_params(img, self.scale, self.ratio) # noqa
interpolation = random.choice([InterpolationMode.BILINEAR, InterpolationMode.BICUBIC])
return F.resized_crop(img, i, j, h, w, self.size, interpolation)
| 2,123 | 33.258065 | 103 | py |
fitclip | fitclip-main/aligner/encoder/videoclip_video_text_encoder.py | import os
from typing import Iterable, Iterator, Optional
import torch
from overrides import overrides
from torchvision import transforms as T
from transformers import AutoTokenizer
from aligner.data.frame_sampler import ConsecutiveFrameSampler, FrameSampler
from aligner.encoder.s3dg import S3DG
from aligner.encoder.video_encoder import TYPE_TRANSFORM, TYPE_VIDEO_INPUT, float_standard_denormalize
from aligner.encoder.video_text_encoder import TYPE_TEXT_INPUT, TYPE_TOKENIZER, VideoTextEncoder
from aligner.encoder.videoclip import MMFusionSeparate
from aligner.transforms import ConvertBHWCtoCBHW, PadToMinFrames
from util.typing_utils import TYPE_PATH
class VideoClipVideoTextEncoder(VideoTextEncoder):
def __init__(self, video_encoder_pretrained_path: Optional[TYPE_PATH] = None,
model_pretrained_path: Optional[TYPE_PATH] = None, num_frames: int = 32, max_tokens: int = 64) -> None:
super().__init__()
self.num_frames = num_frames
self.max_tokens = max_tokens
self.video_encoder = S3DG()
if video_encoder_pretrained_path:
self.video_encoder.load_state_dict(torch.load(video_encoder_pretrained_path))
self.model = MMFusionSeparate(max_video_len=num_frames)
if model_pretrained_path:
self.model.load_state_dict(torch.load(model_pretrained_path))
os.environ["TOKENIZERS_PARALLELISM"] = "0"
self.tokenizer = AutoTokenizer.from_pretrained(self.model.model_name)
@overrides(check_signature=False)
def encode_video(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
batch_size, clip_count = video.shape[:2]
assert batch_size == 1, "Only batch_size = 1 is supported for now."
device = video.device
# FIXME: VideoCLIP uses up to 32 clips per video, which complicates our implementation.
# These clips are randomly sampled when there's more than 32 clips.
# These clips are composed of non-overlapping 32 consecutive frames, and the video is sampled at 30 fps.
video_features = self.video_encoder(video).view(batch_size, clip_count, self.video_encoder.output_size)
video_mask = torch.ones((batch_size, self.num_frames), dtype=torch.bool, device=device)
text = torch.tensor([[self.tokenizer.cls_token_id, self.tokenizer.sep_token_id]], device=device) \
.expand(batch_size, 2)
text_mask = torch.ones((batch_size, 2), dtype=torch.bool, device=device)
return self.model.forward_video(video_features, video_mask, text, text_mask)
@overrides(check_signature=False)
def encode_text(self, text: TYPE_TEXT_INPUT) -> torch.Tensor:
return self.model.forward_text(text["input_ids"], text["attention_mask"])
def _tokenize(self, texts: Iterable[str]) -> TYPE_TEXT_INPUT:
texts = [f"{self.tokenizer.sep_token} {text}" for text in texts]
return self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=self.max_tokens)
@overrides
def get_tokenizer(self) -> TYPE_TOKENIZER:
return self._tokenize
@overrides
def decode_text(self, text: TYPE_TEXT_INPUT) -> Iterator[str]:
return self.tokenizer.batch_decode(text["input_ids"])
@overrides
def get_train_frame_sampler(self) -> FrameSampler:
raise NotImplementedError
@overrides
def get_eval_frame_sampler(self) -> FrameSampler:
return ConsecutiveFrameSampler(self.num_frames, fps=30)
@overrides
def get_train_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
raise NotImplementedError
@overrides
def get_eval_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
return T.Compose([
ConvertBHWCtoCBHW(),
T.ConvertImageDtype(dtype),
T.Resize(224),
T.CenterCrop(224),
PadToMinFrames(self.num_frames, frame_dim=1),
])
@property
@overrides
def should_pad_batch(self) -> bool:
return False
@overrides
def to_bchw(self, t: torch.Tensor) -> torch.Tensor:
return t.permute(0, 2, 1, 3, 4)
@overrides
def denormalize_video_tensor(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
return float_standard_denormalize(video)
| 4,268 | 39.657143 | 120 | py |
fitclip | fitclip-main/aligner/encoder/mil_nce_video_text_encoder.py | import re
from typing import Any, Iterable, Iterator, Mapping, Optional, Union
import numpy as np
import torch
from cached_path import cached_path
from overrides import overrides
from torch import nn
from torchvision import transforms as T
from aligner.data.frame_sampler import ConsecutiveFrameSampler, FrameSampler
from aligner.encoder.s3dg import S3DG
from aligner.encoder.video_encoder import TYPE_TRANSFORM, float_standard_denormalize
from aligner.encoder.video_text_encoder import TYPE_TEXT_INPUT, TYPE_TOKENIZER, TYPE_VIDEO_INPUT, VideoTextEncoder
from aligner.transforms import ConvertBHWCtoCBHW, PadToMinFrames
from util.typing_utils import TYPE_PATH
def load_pretrained_video_encoder(path: TYPE_PATH,
map_location: Optional[Union[str, torch.device]] = None) -> Mapping[str, Any]:
checkpoint = torch.load(path, map_location=map_location)
state_dict = get_video_encoder_state_dict_from_pretrained_mil_nce_checkpoint(checkpoint) \
if "state_dict" in checkpoint else checkpoint
# Backward compatibility, also with the MIL-NCE paper pretrained one.
return {k: v for k, v in state_dict.items() if not k.startswith("text_module.")}
def load_pretrained_text_encoder(path: TYPE_PATH,
map_location: Optional[Union[str, torch.device]] = None) -> Mapping[str, Any]:
checkpoint = torch.load(path, map_location=map_location)
if "state_dict" in checkpoint:
return get_text_encoder_state_dict_from_pretrained_mil_nce_checkpoint(checkpoint)
elif any(k.startswith("text_module.") for k in checkpoint):
# Backward compatibility, also with a MIL-NCE paper pretrained one.
prefix = "text_module."
return {k[len(prefix):]: v for k, v in checkpoint.items() if k.startswith(prefix)}
else:
return checkpoint
def get_video_encoder_state_dict_from_pretrained_mil_nce_checkpoint(
checkpoint: Mapping[str, Any]) -> Mapping[str, torch.Tensor]:
pl_module_state_dict = checkpoint["state_dict"]
# Look for the corresponding encoder, with backward compatibility.
prefix = "encoder." if any(k.startswith("encoder.") for k in pl_module_state_dict.keys()) else "video_encoder."
return {k[len(prefix):]: v for k, v in pl_module_state_dict.items() if k.startswith(prefix)}
def get_text_encoder_state_dict_from_pretrained_mil_nce_checkpoint(
checkpoint: Mapping[str, Any]) -> Mapping[str, torch.Tensor]:
pl_module_state_dict = checkpoint["state_dict"]
# Look for the corresponding encoder, with backward compatibility.
prefix = "encoder.text_module." if any(k.startswith("encoder.text_module.") for k in pl_module_state_dict.keys()) \
else "text_encoder."
return {k[len(prefix):]: v for k, v in pl_module_state_dict.items() if k.startswith(prefix)}
class GlobalMaxPool1d(nn.Module):
@overrides(check_signature=False)
def forward(self, t: torch.Tensor) -> torch.Tensor:
return t.max(dim=1)[0]
class MilNceTextEncoder(nn.Module):
def __init__(self, output_size: int = 512, vocab_size: int = 66250, word_embedding_size: int = 300,
embedding: Optional[torch.Tensor] = None, hidden_size: int = 2048) -> None:
super().__init__()
# noinspection SpellCheckingInspection
self.word_embd = nn.Embedding(vocab_size, word_embedding_size) if embedding is None \
else nn.Embedding.from_pretrained(embedding)
self.fc1 = nn.Linear(self.word_embd.embedding_dim, hidden_size)
self.relu = nn.ReLU(inplace=True)
self.max_pooling = GlobalMaxPool1d()
self.fc2 = nn.Linear(hidden_size, output_size)
@overrides(check_signature=False)
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
text = self.word_embd(input_ids)
text = self.relu(self.fc1(text))
text = self.max_pooling(text)
return self.fc2(text)
def truncate_or_pad_1d_tensor(tensor: torch.Tensor, size: int, fill_value: Any = 0) -> torch.Tensor:
if len(tensor) >= size:
return tensor[:size]
else:
padded_tensor = torch.full((size,), fill_value, dtype=tensor.dtype, device=tensor.device,
requires_grad=tensor.requires_grad)
padded_tensor[:len(tensor)] = tensor
return padded_tensor
class MilNceTokenizer:
RE_WORD = re.compile(r"[\w']+")
def __init__(self, vocab: Mapping[str, int], max_tokens: int = 20, lowercase: bool = True) -> None:
super().__init__()
self.vocab = vocab
self.max_tokens = max_tokens
self.lowercase = lowercase
self.indices_to_tokens = {i: token for token, i in vocab.items()}
def _tokenize(self, text: str) -> Iterator[str]:
if self.lowercase:
text = text.lower()
return self.RE_WORD.findall(text)
def _index(self, tokens: Iterable[str]) -> torch.Tensor:
tokens_in_vocab_tensor = torch.tensor([self.vocab[word] for word in tokens if word in self.vocab],
dtype=torch.long)
return truncate_or_pad_1d_tensor(tokens_in_vocab_tensor, self.max_tokens)
def __call__(self, text: str) -> TYPE_TEXT_INPUT:
return {"input_ids": self._index(self._tokenize(text))}
def decode(self, ids: Iterable[int]) -> str:
return " ".join(self.indices_to_tokens[i] for i in ids if i != 0)
class MilNceVideoTextEncoder(VideoTextEncoder):
def __init__(self, vocab_path: TYPE_PATH = "https://www.rocq.inria.fr/cluster-willow/amiech/howto100m/s3d_dict.npy",
pretrained_path: Optional[TYPE_PATH] = None, max_tokens: int = 20, num_frames: int = 16) -> None:
super().__init__()
self.video_encoder = S3DG()
self.text_encoder = MilNceTextEncoder()
vocab: Mapping[str, int] = {t.item(): i + 1 for i, t in enumerate(np.load(cached_path(vocab_path)))}
self.tokenizer = MilNceTokenizer(vocab=vocab, max_tokens=max_tokens)
self.num_frames = num_frames
if pretrained_path:
pretrained_path = cached_path(pretrained_path)
self.video_encoder.load_state_dict(load_pretrained_video_encoder(pretrained_path, # noqa
map_location="cpu"))
self.text_encoder.load_state_dict(load_pretrained_text_encoder(pretrained_path, # noqa
map_location="cpu"))
@overrides(check_signature=False)
def encode_video(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
return self.video_encoder(video)
@overrides(check_signature=False)
def encode_text(self, text: TYPE_TEXT_INPUT) -> torch.Tensor:
return self.text_encoder(text["input_ids"])
def _tokenize(self, texts: Iterable[str]) -> TYPE_TEXT_INPUT:
tokenized = [self.tokenizer(text) for text in texts]
return {k: torch.stack([t[k] for t in tokenized]) for k in next(iter(tokenized), [])}
@overrides
def get_tokenizer(self) -> TYPE_TOKENIZER:
return self._tokenize
@overrides
def decode_text(self, text: TYPE_TEXT_INPUT) -> Iterator[str]:
for text_instance in text["input_ids"]:
yield self.tokenizer.decode(text_instance.tolist())
@overrides
def get_train_frame_sampler(self) -> FrameSampler:
raise NotImplementedError
@overrides
def get_eval_frame_sampler(self) -> FrameSampler:
return ConsecutiveFrameSampler(self.num_frames, fps=5)
@overrides
def get_train_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
raise NotImplementedError
@overrides
def get_eval_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
return T.Compose([
ConvertBHWCtoCBHW(),
T.ConvertImageDtype(dtype),
T.Resize(224),
T.CenterCrop(224),
PadToMinFrames(self.num_frames, frame_dim=1),
])
@property
@overrides
def should_pad_batch(self) -> bool:
return False
@overrides
def to_bchw(self, t: torch.Tensor) -> torch.Tensor:
return t.permute(0, 2, 1, 3, 4)
@overrides
def denormalize_video_tensor(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
return float_standard_denormalize(video)
| 8,365 | 41.040201 | 120 | py |
fitclip | fitclip-main/aligner/encoder/video_text_encoder.py | from abc import abstractmethod
from typing import Callable, Iterable, Iterator, Mapping, Tuple
import torch
from overrides import overrides
from aligner.encoder.video_encoder import TYPE_VIDEO_INPUT, VideoEncoder
TYPE_TEXT_INPUT = Mapping[str, torch.Tensor]
TYPE_OUTPUT = Tuple[torch.Tensor, torch.Tensor]
TYPE_TOKENIZER = Callable[[Iterable[str]], Mapping[str, torch.Tensor]]
class VideoTextEncoder(VideoEncoder):
@abstractmethod
def encode_text(self, text: TYPE_TEXT_INPUT) -> torch.Tensor:
raise NotImplementedError
@overrides(check_signature=False)
def forward(self, video: TYPE_VIDEO_INPUT, text: TYPE_TEXT_INPUT) -> TYPE_OUTPUT:
return self.encode_video(video), self.encode_text(text)
@abstractmethod
def get_tokenizer(self) -> TYPE_TOKENIZER:
raise NotImplementedError
@abstractmethod
def decode_text(self, text: TYPE_TEXT_INPUT) -> Iterator[str]:
"""Decodes a batch of texts."""
raise NotImplementedError
| 994 | 30.09375 | 85 | py |
fitclip | fitclip-main/aligner/encoder/video_encoder.py | from abc import abstractmethod
from typing import Callable, Optional, Tuple
import torch
from overrides import overrides
from torch import nn
from aligner.data.frame_sampler import FrameSampler
TYPE_VIDEO_INPUT = torch.Tensor
TYPE_TRANSFORM = Callable[[torch.Tensor], torch.Tensor]
class VideoEncoder(nn.Module):
@abstractmethod
def encode_video(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
raise NotImplementedError
@overrides(check_signature=False)
def forward(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
return self.encode_video(video)
@abstractmethod
def get_train_frame_sampler(self) -> FrameSampler:
raise NotImplementedError
@abstractmethod
def get_eval_frame_sampler(self) -> FrameSampler:
raise NotImplementedError
@abstractmethod
def get_train_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
raise NotImplementedError
@abstractmethod
def get_eval_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
raise NotImplementedError
@property
# Don't set as abstract method to avoid some boilerplate in subclasses.
def should_pad_batch(self) -> bool:
raise NotImplementedError
@abstractmethod
def to_bchw(self, t: torch.Tensor) -> torch.Tensor:
raise NotImplementedError
@abstractmethod
def denormalize_video_tensor(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
"""Converts a transformed video tensor into an unsigned 8-bit integer tensor in the range 0-255."""
raise NotImplementedError
def float_standard_denormalize(video: TYPE_VIDEO_INPUT, mean: Optional[Tuple[float, float, float]] = None,
std: Optional[Tuple[float, float, float]] = None) -> torch.Tensor:
if std is not None:
video *= torch.tensor(std, device=video.device, dtype=video.dtype).view(-1, 1, 1)
if mean is not None:
video += torch.tensor(mean, device=video.device, dtype=video.dtype).view(-1, 1, 1)
return (video * 255).to(torch.uint8) # noqa
| 2,121 | 32.15625 | 107 | py |
fitclip | fitclip-main/aligner/encoder/slip.py | # All rights reserved.
import gzip
import html
from collections import OrderedDict
from functools import lru_cache
from typing import Iterable, Iterator
import ftfy
import numpy as np
import regex as re
import timm
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from cached_path import cached_path
from torch import autograd
@lru_cache()
def default_bpe():
return cached_path("https://github.com/facebookresearch/SLIP/raw/main/bpe_simple_vocab_16e6.txt.gz")
@lru_cache()
def bytes_to_unicode():
"""
Returns list of utf-8 byte and a corresponding list of unicode strings.
The reversible bpe codes work on unicode strings.
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
This is a significant percentage of your normal, say, 32K bpe vocab.
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
And avoids mapping to whitespace/control characters the bpe code barfs on.
"""
bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
cs = bs[:]
n = 0
for b in range(2 ** 8):
if b not in bs:
bs.append(b)
cs.append(2 ** 8 + n)
n += 1
cs = [chr(n) for n in cs]
return dict(zip(bs, cs))
def get_pairs(word):
"""Return set of symbol pairs in a word.
Word is represented as tuple of symbols (symbols being variable-length strings).
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs
def basic_clean(text):
text = ftfy.fix_text(text)
text = html.unescape(html.unescape(text))
return text.strip()
def whitespace_clean(text):
text = re.sub(r'\s+', ' ', text)
text = text.strip()
return text
class SimpleTokenizer:
def __init__(self, bpe_path: str = default_bpe()):
self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
merges = merges[1:49152 - 256 - 2 + 1]
merges = [tuple(merge.split()) for merge in merges]
vocab = list(bytes_to_unicode().values())
vocab = vocab + [v + '</w>' for v in vocab]
for merge in merges:
vocab.append(''.join(merge))
vocab.extend(['<|startoftext|>', '<|endoftext|>'])
self.encoder = dict(zip(vocab, range(len(vocab))))
self.decoder = {v: k for k, v in self.encoder.items()}
self.bpe_ranks = dict(zip(merges, range(len(merges))))
self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
self.pat = re.compile(
r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""",
re.IGNORECASE)
def bpe(self, token):
if token in self.cache:
return self.cache[token]
word = tuple(token[:-1]) + (token[-1] + '</w>',)
pairs = get_pairs(word)
if not pairs:
return token + '</w>'
while True:
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf')))
if bigram not in self.bpe_ranks:
break
first, second = bigram
new_word = []
i = 0
while i < len(word):
try:
j = word.index(first, i)
new_word.extend(word[i:j])
i = j
except:
new_word.extend(word[i:])
break
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
new_word.append(first + second)
i += 2
else:
new_word.append(word[i])
i += 1
new_word = tuple(new_word)
word = new_word
if len(word) == 1:
break
else:
pairs = get_pairs(word)
word = ' '.join(word)
self.cache[token] = word
return word
def encode(self, text):
bpe_tokens = []
text = whitespace_clean(basic_clean(text)).lower()
for token in re.findall(self.pat, text):
token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
return bpe_tokens
def decode(self, tokens):
text = ''.join(self.decoder[token] for token in tokens)
text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
return text
def __call__(self, texts, context_length=77):
if isinstance(texts, str):
texts = [texts]
sot_token = self.encoder["<|startoftext|>"]
eot_token = self.encoder["<|endoftext|>"]
all_tokens = [[sot_token] + self.encode(text) + [eot_token] for text in texts]
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long)
for i, tokens in enumerate(all_tokens):
tokens = tokens[:context_length]
result[i, :len(tokens)] = torch.tensor(tokens)
if len(result) == 1:
return result[0]
return result
def is_dist_avail_and_initialized() -> bool:
return dist.is_available() and dist.is_initialized()
def get_world_size() -> int:
return dist.get_world_size() if is_dist_avail_and_initialized() else 1
def get_rank() -> int:
return dist.get_rank() if is_dist_avail_and_initialized() else 0
def all_gather_batch(tensors):
"""
Performs all_gather operation on the provided tensors.
"""
# Queue the gathered tensors
world_size = get_world_size()
# There is no need for reduction in the single-proc case
if world_size == 1:
return tensors
tensor_list = []
for tensor in tensors:
tensor_all = [torch.ones_like(tensor) for _ in range(world_size)]
dist.all_gather(
tensor_all,
tensor,
async_op=False # performance opt
)
tensor_list.append(tensor_all)
return [torch.cat(tensor_all) for tensor_all in tensor_list]
class GatherLayer(autograd.Function): # noqa
"""
Gather tensors from all workers with support for backward propagation:
This implementation does not cut the gradients as torch.distributed.all_gather does.
"""
@staticmethod
def forward(ctx, x): # noqa
output = [torch.zeros_like(x) for _ in range(dist.get_world_size())]
dist.all_gather(output, x)
return tuple(output)
@staticmethod
def backward(ctx, *grads):
all_gradients = torch.stack(grads)
dist.all_reduce(all_gradients)
return all_gradients[dist.get_rank()]
def all_gather_batch_with_grad(tensors: Iterable[torch.Tensor]) -> Iterator[torch.Tensor]:
"""
Performs all_gather operation on the provided tensors.
Graph remains connected for backward grad computation.
"""
return tensors if get_world_size() == 1 else [torch.cat(GatherLayer.apply(tensor)) for tensor in tensors]
class CLIPLoss(nn.Module):
def __init__(self):
super().__init__()
self.labels = None
self.last_local_batch_size = None
def forward(self, outputs):
image_embed = outputs['image_embed']
text_embed = outputs['text_embed']
logit_scale = outputs['logit_scale']
local_batch_size = image_embed.size(0)
if local_batch_size != self.last_local_batch_size:
self.labels = local_batch_size * get_rank() + torch.arange(
local_batch_size, device=image_embed.device
)
self.last_local_batch_size = local_batch_size
# normalized features
image_embed = F.normalize(image_embed, dim=-1, p=2)
text_embed = F.normalize(text_embed, dim=-1, p=2)
# gather features from all GPUs
image_embed_all, text_embed_all = all_gather_batch([image_embed, text_embed])
# cosine similarity as logits
logits_per_image = logit_scale * image_embed @ text_embed_all.t()
logits_per_text = logit_scale * text_embed @ image_embed_all.t()
loss = (F.cross_entropy(logits_per_image, self.labels) + F.cross_entropy(logits_per_text, self.labels)) / 2
# compute accuracy
with torch.no_grad():
pred = torch.argmax(logits_per_image, dim=-1)
correct = pred.eq(self.labels).sum()
acc = 100 * correct / local_batch_size
return {'loss': loss, 'clip_loss': loss, 'clip_acc': acc}
class SIMCLRLoss(nn.Module):
"""
This is the SimCLR loss in https://arxiv.org/abs/2002.05709
The embedding vectors are assumed to have size (2 x batch_size, embedding_dim) and
the memory layout that can be reshaped into shape (2, batch_size, embedding_dim).
This memory layout is consistent with the SimCLR collator in
https://github.com/facebookresearch/vissl/blob/master/vissl/data/collators/simclr_collator.py
Config params:
temperature (float): the temperature to be applied on the logits
"""
def __init__(self, temperature=0.1):
super().__init__()
self.tau = temperature
self.labels = None
self.masks = None
self.last_local_batch_size = None
def forward(self, outputs):
q_a = outputs['aug1_embed']
q_b = outputs['aug2_embed']
q_a = F.normalize(q_a, dim=-1, p=2)
q_b = F.normalize(q_b, dim=-1, p=2)
local_batch_size = q_a.size(0)
k_a, k_b = all_gather_batch_with_grad([q_a, q_b])
if local_batch_size != self.last_local_batch_size:
self.labels = local_batch_size * get_rank() + torch.arange(
local_batch_size, device=q_a.device
)
total_batch_size = local_batch_size * get_world_size()
self.masks = F.one_hot(self.labels, total_batch_size) * 1e9
self.last_local_batch_size = local_batch_size
logits_aa = torch.matmul(q_a, k_a.transpose(0, 1)) / self.tau
logits_aa = logits_aa - self.masks
logits_bb = torch.matmul(q_b, k_b.transpose(0, 1)) / self.tau
logits_bb = logits_bb - self.masks
logits_ab = torch.matmul(q_a, k_b.transpose(0, 1)) / self.tau
logits_ba = torch.matmul(q_b, k_a.transpose(0, 1)) / self.tau
loss_a = F.cross_entropy(torch.cat([logits_ab, logits_aa], dim=1), self.labels)
loss_b = F.cross_entropy(torch.cat([logits_ba, logits_bb], dim=1), self.labels)
loss = (loss_a + loss_b) / 2 # divide by 2 to average over all samples
# compute accuracy
with torch.no_grad():
pred = torch.argmax(torch.cat([logits_ab, logits_aa], dim=1), dim=-1)
correct = pred.eq(self.labels).sum()
acc = 100 * correct / local_batch_size
return {'loss': loss, 'ssl_loss': loss, 'ssl_acc': acc}
class SLIPLoss(nn.Module):
def __init__(self, ssl_loss, ssl_scale):
super().__init__()
self.clip_loss = CLIPLoss()
self.ssl_loss = ssl_loss
self.ssl_scale = ssl_scale
def forward(self, outputs):
clip_loss_dict = self.clip_loss(outputs)
clip_loss = clip_loss_dict['clip_loss']
clip_acc = clip_loss_dict['clip_acc']
ssl_loss_dict = self.ssl_loss(outputs)
ssl_loss = ssl_loss_dict['ssl_loss']
ssl_acc = ssl_loss_dict['ssl_acc']
return {'loss': clip_loss + self.ssl_scale * ssl_loss,
'clip_loss': clip_loss,
'clip_acc': clip_acc,
'ssl_loss': ssl_loss,
'ssl_acc': ssl_acc}
class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: torch.Tensor):
orig_type = x.dtype
ret = super().forward(x.type(torch.float32))
return ret.type(orig_type)
class QuickGELU(nn.Module):
def forward(self, x: torch.Tensor): # noqa
return x * torch.sigmoid(1.702 * x) # noqa
class ResidualAttentionBlock(nn.Module):
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(OrderedDict([
("c_fc", nn.Linear(d_model, d_model * 4)),
("gelu", QuickGELU()),
("c_proj", nn.Linear(d_model * 4, d_model))
]))
self.ln_2 = LayerNorm(d_model)
self.attn_mask = attn_mask
def attention(self, x: torch.Tensor):
self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
def forward(self, x: torch.Tensor):
x = x + self.attention(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
class Transformer(nn.Module):
def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
super().__init__()
self.width = width
self.layers = layers
self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
def forward(self, x: torch.Tensor):
return self.resblocks(x)
class CLIP(nn.Module):
def __init__(self,
embed_dim: int,
# vision
vision_width: int,
vision_model: nn.Module,
# text
context_length: int,
vocab_size: int,
transformer_width: int,
transformer_heads: int,
transformer_layers: int,
**kwargs,
):
super().__init__()
self.context_length = context_length
self.vision_width = vision_width
self.visual = vision_model
self.transformer = Transformer(
width=transformer_width,
layers=transformer_layers,
heads=transformer_heads,
attn_mask=self.build_attention_mask(),
)
self.vocab_size = vocab_size
self.token_embedding = nn.Embedding(vocab_size, transformer_width)
self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
self.ln_final = LayerNorm(transformer_width)
self.image_projection = nn.Parameter(torch.empty(vision_width, embed_dim))
self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
self.initialize_parameters()
def initialize_parameters(self):
nn.init.normal_(self.token_embedding.weight, std=0.02)
nn.init.normal_(self.positional_embedding, std=0.01)
proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
attn_std = self.transformer.width ** -0.5
fc_std = (2 * self.transformer.width) ** -0.5
for block in self.transformer.resblocks:
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
nn.init.normal_(self.image_projection, std=self.vision_width ** -0.5)
nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
def build_attention_mask(self):
# lazily create causal attention mask, with full attention between the vision tokens
# pytorch uses additive attention mask; fill with -inf
mask = torch.empty(self.context_length, self.context_length)
mask.fill_(float("-inf"))
mask.triu_(1) # zero out the lower diagonal
return mask
def encode_image(self, image):
x = self.visual(image)
x = x @ self.image_projection
return x
def encode_text(self, text):
x = self.token_embedding(text) # [batch_size, n_ctx, d_model]
x = x + self.positional_embedding
x = x.permute(1, 0, 2) # NLD -> LND
x = self.transformer(x)
x = x.permute(1, 0, 2) # LND -> NLD
x = self.ln_final(x)
# x.shape = [batch_size, n_ctx, transformer.width]
# take features from the eot embedding (eot_token is the highest number in each sequence)
x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
return x
def forward(self, image, text):
image_embed = self.encode_image(image)
text_embed = self.encode_text(text)
return {'image_embed': image_embed,
'text_embed': text_embed,
'logit_scale': self.logit_scale.exp()}
def _build_mlp(in_dim, mlp_dim, out_dim):
return nn.Sequential(OrderedDict([
("layer1", nn.Linear(in_dim, mlp_dim)),
("bn1", nn.SyncBatchNorm(mlp_dim)),
("relu1", nn.ReLU(inplace=True)),
("layer2", nn.Linear(mlp_dim, mlp_dim)),
("bn2", nn.SyncBatchNorm(mlp_dim)),
("relu2", nn.ReLU(inplace=True)),
("layer3", nn.Linear(mlp_dim, out_dim)),
]))
class SIMCLR(nn.Module):
def __init__(self,
# vision
vision_width: int,
vision_model: nn.Module,
# ssl
ssl_mlp_dim: int,
ssl_emb_dim: int,
**kwargs, # noqa
):
super().__init__()
self.vision_width = vision_width
self.visual = vision_model
self.image_mlp = _build_mlp(in_dim=vision_width, mlp_dim=ssl_mlp_dim, out_dim=ssl_emb_dim)
def encode_image(self, image):
return self.visual(image)
def forward(self, aug1, aug2):
h1 = self.visual(aug1)
h2 = self.visual(aug2)
aug1_embed = self.image_mlp(h1)
aug2_embed = self.image_mlp(h2)
return {'aug1_embed': aug1_embed, 'aug2_embed': aug2_embed}
class SLIP(CLIP):
def __init__(self, ssl_mlp_dim: int, ssl_emb_dim: int, **kwargs):
super().__init__(**kwargs)
self.image_mlp = _build_mlp(in_dim=self.vision_width, mlp_dim=ssl_mlp_dim, out_dim=ssl_emb_dim)
def forward(self, image, text, aug1, aug2): # noqa
aug1_embed = self.image_mlp(self.visual(aug1))
aug2_embed = self.image_mlp(self.visual(aug2))
image_embed = self.encode_image(image)
text_embed = self.encode_text(text)
return {'image_embed': image_embed, 'text_embed': text_embed, 'logit_scale': self.logit_scale.exp(),
'aug1_embed': aug1_embed, 'aug2_embed': aug2_embed}
def get_loss(model, ssl_temp, ssl_scale):
if model.startswith('SLIP'):
ssl_loss = SIMCLRLoss(temperature=ssl_temp)
return SLIPLoss(ssl_loss, ssl_scale)
if model.startswith('CLIP'):
return CLIPLoss()
if model.startswith('SIMCLR'):
return SIMCLRLoss(temperature=ssl_temp)
def get_metric_names(model):
if model.startswith('SLIP'):
return ['loss', 'clip_loss', 'ssl_loss', 'clip_acc', 'ssl_acc']
elif model.startswith('CLIP'):
return ['loss', 'clip_loss', 'clip_acc']
else:
return ['loss', 'ssl_loss', 'ssl_acc']
@timm.models.registry.register_model
def vit_small_mocov3_patch16_224(**kwargs):
return timm.models.vision_transformer._create_vision_transformer("vit_small_patch16_224", patch_size=16,
embed_dim=384, depth=12, num_heads=12, **kwargs)
def CLIP_VITS16(**kwargs):
vision_model = timm.create_model('vit_small_mocov3_patch16_224', num_classes=0)
model = CLIP(embed_dim=512, vision_width=384, vision_model=vision_model, context_length=77, vocab_size=49408,
transformer_width=512, transformer_heads=8, transformer_layers=12, **kwargs)
return model
def SIMCLR_VITS16(**kwargs):
vision_model = timm.create_model('vit_small_mocov3_patch16_224', num_classes=0)
model = SIMCLR(vision_width=384, vision_model=vision_model, **kwargs)
return model
def SLIP_VITS16(**kwargs):
vision_model = timm.create_model('vit_small_mocov3_patch16_224', num_classes=0)
model = SLIP(embed_dim=512, vision_width=384, vision_model=vision_model, context_length=77, vocab_size=49408,
transformer_width=512, transformer_heads=8, transformer_layers=12, **kwargs)
return model
def CLIP_VITB16(**kwargs):
vision_model = timm.create_model('vit_base_patch16_224', num_classes=0)
model = CLIP(embed_dim=512, vision_width=768, vision_model=vision_model, context_length=77, vocab_size=49408,
transformer_width=512, transformer_heads=8, transformer_layers=12, **kwargs)
return model
def SIMCLR_VITB16(**kwargs):
vision_model = timm.create_model('vit_base_patch16_224', num_classes=0)
model = SIMCLR(vision_width=768, vision_model=vision_model, **kwargs)
return model
def SLIP_VITB16(**kwargs):
vision_model = timm.create_model('vit_base_patch16_224', num_classes=0)
model = SLIP(embed_dim=512, vision_width=768, vision_model=vision_model, context_length=77, vocab_size=49408,
transformer_width=512, transformer_heads=8, transformer_layers=12, **kwargs)
return model
def CLIP_VITL16(**kwargs):
vision_model = timm.create_model('vit_large_patch16_224', num_classes=0)
model = CLIP(embed_dim=512, vision_width=1024, vision_model=vision_model, context_length=77, vocab_size=49408,
transformer_width=512, transformer_heads=8, transformer_layers=12, **kwargs)
return model
def SIMCLR_VITL16(**kwargs):
vision_model = timm.create_model('vit_large_patch16_224', num_classes=0)
model = SIMCLR(vision_width=1024, vision_model=vision_model, **kwargs)
return model
def SLIP_VITL16(**kwargs):
vision_model = timm.create_model('vit_large_patch16_224', num_classes=0)
model = SLIP(embed_dim=512, vision_width=1024, vision_model=vision_model, context_length=77, vocab_size=49408,
transformer_width=512, transformer_heads=8, transformer_layers=12, **kwargs)
return model
| 22,773 | 34.640063 | 120 | py |
fitclip | fitclip-main/aligner/encoder/s3dg.py | # Initially copied from the MIL-NCE repo.
"""Contains the definition for Gated Separable 3D network (S3D-G). """
from typing import Literal, Tuple
import torch
from overrides import overrides
from torch import nn
from torch.nn.common_types import _size_3_t, _size_6_t
class InceptionBlock(nn.Module):
def __init__(self, input_dim: int, num_outputs_0_0a: int, num_outputs_1_0a: int, num_outputs_1_0b: int,
num_outputs_2_0a: int, num_outputs_2_0b: int, num_outputs_3_0b: int, gating: bool = True) -> None:
super().__init__()
self.conv_b0 = STConv3D(input_dim, num_outputs_0_0a, kernel_size=1)
self.conv_b1_a = STConv3D(input_dim, num_outputs_1_0a, kernel_size=1)
self.conv_b1_b = STConv3D(num_outputs_1_0a, num_outputs_1_0b, kernel_size=3, padding=1, separable=True)
self.conv_b2_a = STConv3D(input_dim, num_outputs_2_0a, kernel_size=1)
self.conv_b2_b = STConv3D(num_outputs_2_0a, num_outputs_2_0b, kernel_size=3, padding=1, separable=True)
self.maxpool_b3 = torch.nn.MaxPool3d(kernel_size=3, stride=1, padding=1)
self.conv_b3_b = STConv3D(input_dim, num_outputs_3_0b, 1)
self.gating = gating
self.output_dim = num_outputs_0_0a + num_outputs_1_0b + num_outputs_2_0b + num_outputs_3_0b
if gating:
self.gating_b0 = SelfGating(num_outputs_0_0a)
self.gating_b1 = SelfGating(num_outputs_1_0b)
self.gating_b2 = SelfGating(num_outputs_2_0b)
self.gating_b3 = SelfGating(num_outputs_3_0b)
@overrides(check_signature=False)
def forward(self, input_: torch.Tensor) -> torch.Tensor:
b0 = self.conv_b0(input_)
b1 = self.conv_b1_a(input_)
b1 = self.conv_b1_b(b1)
b2 = self.conv_b2_a(input_)
b2 = self.conv_b2_b(b2)
b3 = self.maxpool_b3(input_)
b3 = self.conv_b3_b(b3)
if self.gating:
b0 = self.gating_b0(b0)
b1 = self.gating_b1(b1)
b2 = self.gating_b2(b2)
b3 = self.gating_b3(b3)
return torch.cat((b0, b1, b2, b3), dim=1)
class SelfGating(nn.Module):
"""Feature gating as used in S3D-G. """
def __init__(self, input_dim: int) -> None:
super().__init__()
self.fc = nn.Linear(input_dim, input_dim)
self.sigmoid = nn.modules.activation.Sigmoid()
@overrides(check_signature=False)
def forward(self, input_: torch.Tensor) -> torch.Tensor:
spatiotemporal_average = input_.mean(dim=[2, 3, 4])
weights = self.fc(spatiotemporal_average)
weights = self.sigmoid(weights)
return weights[:, :, None, None, None] * input_
def _size3_to_spatial_temporal(size: _size_3_t, fill_value: int) -> Tuple[_size_3_t, _size_3_t]:
size = nn.modules.conv._triple(size)
return (fill_value, size[1], size[2]), (size[0], fill_value, fill_value)
class STConv3D(nn.Module):
def __init__(self, input_dim: int, output_dim: int, kernel_size: _size_3_t, stride: _size_3_t = 1,
padding: _size_3_t = 0, separable: bool = False) -> None:
super().__init__()
self.separable = separable
self.relu = nn.ReLU(inplace=True)
if separable:
assert (isinstance(kernel_size, int) and kernel_size != 1) or kernel_size[0] != 1
spatial_kernel_size, temporal_kernel_size = _size3_to_spatial_temporal(kernel_size, fill_value=1)
spatial_stride, temporal_stride = _size3_to_spatial_temporal(stride, fill_value=1)
spatial_padding, temporal_padding = _size3_to_spatial_temporal(padding, fill_value=0)
self.conv1 = nn.Conv3d(input_dim, output_dim, kernel_size=spatial_kernel_size, stride=spatial_stride,
padding=spatial_padding, bias=False)
self.conv2 = nn.Conv3d(output_dim, output_dim, kernel_size=temporal_kernel_size, stride=temporal_stride,
padding=temporal_padding, bias=False)
self.bn2 = nn.BatchNorm3d(output_dim)
else:
self.conv1 = nn.Conv3d(input_dim, output_dim, kernel_size=kernel_size, stride=stride, # noqa
padding=padding, bias=False)
self.bn1 = nn.BatchNorm3d(output_dim)
@overrides(check_signature=False)
def forward(self, input_: torch.Tensor) -> torch.Tensor:
out = self.relu(self.bn1(self.conv1(input_)))
if self.separable:
out = self.relu(self.bn2(self.conv2(out)))
return out
def _pad_top_bottom(kernel_dim: int, stride_val: int) -> Tuple[int, int]:
pad_along = max(kernel_dim - stride_val, 0)
pad_top_ = pad_along // 2
pad_bottom_ = pad_along - pad_top_
return pad_top_, pad_bottom_
def _get_padding_shape(kernel_size: _size_3_t, stride: _size_3_t) -> _size_6_t:
kernel_size = nn.modules.conv._triple(kernel_size)
stride = nn.modules.conv._triple(stride)
padding_shape = [padding_value
for pair in zip(kernel_size, stride)
for padding_value in _pad_top_bottom(*pair)]
depth_top = padding_shape.pop(0)
depth_bottom = padding_shape.pop(0)
padding_shape.append(depth_top)
padding_shape.append(depth_bottom)
return tuple(padding_shape)
class MaxPool3dTFPadding(torch.nn.Module):
def __init__(self, kernel_size: _size_3_t, stride: _size_3_t, padding: Literal["SAME"] = "SAME") -> None:
super().__init__()
if padding == "SAME":
self.padding_shape = _get_padding_shape(kernel_size, stride)
self.pad = torch.nn.ConstantPad3d(self.padding_shape, 0)
else:
raise ValueError(f"Padding strategy not supported: {padding}")
self.pool = torch.nn.MaxPool3d(kernel_size, stride, ceil_mode=True)
@overrides(check_signature=False)
def forward(self, input_: torch.Tensor) -> torch.Tensor:
input_ = self.pad(input_)
return self.pool(input_)
class S3DG(nn.Module):
def __init__(self, embedding_size: int = 512, space_to_depth: bool = True,
init: Literal["default", "kaiming_normal"] = "default", use_last_layer: bool = True) -> None:
super().__init__()
self.use_last_layer = use_last_layer
self.space_to_depth = space_to_depth
if space_to_depth:
self.conv1 = STConv3D(24, 64, kernel_size=(2, 4, 4), stride=1, padding=(1, 2, 2), separable=False) # noqa
else:
self.conv1 = STConv3D(3, 64, kernel_size=(3, 7, 7), stride=2, padding=(1, 3, 3), separable=False) # noqa
self.conv_2b = STConv3D(64, 64, kernel_size=1, separable=False)
self.conv_2c = STConv3D(64, 192, kernel_size=3, padding=1, separable=True)
self.gating = SelfGating(192)
self.maxpool_2a = MaxPool3dTFPadding(kernel_size=(1, 3, 3), stride=(1, 2, 2))
self.maxpool_3a = MaxPool3dTFPadding(kernel_size=(1, 3, 3), stride=(1, 2, 2))
self.mixed_3b = InceptionBlock(192, 64, 96, 128, 16, 32, 32)
self.mixed_3c = InceptionBlock(self.mixed_3b.output_dim, 128, 128, 192, 32, 96, 64)
self.maxpool_4a = MaxPool3dTFPadding(kernel_size=3, stride=2)
self.mixed_4b = InceptionBlock(self.mixed_3c.output_dim, 192, 96, 208, 16, 48, 64)
self.mixed_4c = InceptionBlock(self.mixed_4b.output_dim, 160, 112, 224, 24, 64, 64)
self.mixed_4d = InceptionBlock(self.mixed_4c.output_dim, 128, 128, 256, 24, 64, 64)
self.mixed_4e = InceptionBlock(self.mixed_4d.output_dim, 112, 144, 288, 32, 64, 64)
self.mixed_4f = InceptionBlock(self.mixed_4e.output_dim, 256, 160, 320, 32, 128, 128)
self.maxpool_5a = self.maxPool3d_5a_2x2 = MaxPool3dTFPadding(kernel_size=2, stride=2)
self.mixed_5b = InceptionBlock(self.mixed_4f.output_dim, 256, 160, 320, 32, 128, 128)
self.mixed_5c = InceptionBlock(self.mixed_5b.output_dim, 384, 192, 384, 48, 128, 128)
self.fc = nn.Linear(self.mixed_5c.output_dim, embedding_size)
if init == "kaiming_normal":
for m in self.modules():
if isinstance(m, nn.Conv3d):
nn.init.kaiming_normal_(m.weight, mode="fan_in", nonlinearity="relu")
elif isinstance(m, nn.BatchNorm3d):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
@property
def output_size(self) -> int:
return self.fc.out_features if self.use_last_layer else self.mixed_5c.output_dim
@staticmethod
def _space_to_depth(input_: torch.Tensor) -> torch.Tensor:
B, C, T, H, W = input_.shape
input_ = input_.view(B, C, T // 2, 2, H // 2, 2, W // 2, 2)
input_ = input_.permute(0, 3, 5, 7, 1, 2, 4, 6)
input_ = input_.contiguous().view(B, 8 * C, T // 2, H // 2, W // 2)
return input_
@overrides(check_signature=False)
def forward(self, input_: torch.Tensor) -> torch.Tensor:
if self.space_to_depth:
input_ = self._space_to_depth(input_)
net = self.conv1(input_)
if self.space_to_depth:
net = net[:, :, 1:, 1:, 1:]
net = self.maxpool_2a(net)
net = self.conv_2b(net)
net = self.conv_2c(net)
if self.gating:
net = self.gating(net)
net = self.maxpool_3a(net)
net = self.mixed_3b(net)
net = self.mixed_3c(net)
net = self.maxpool_4a(net)
net = self.mixed_4b(net)
net = self.mixed_4c(net)
net = self.mixed_4d(net)
net = self.mixed_4e(net)
net = self.mixed_4f(net)
net = self.maxpool_5a(net)
net = self.mixed_5b(net)
net = self.mixed_5c(net)
net = torch.mean(net, dim=(2, 3, 4))
if self.use_last_layer:
return self.fc(net)
else:
return net
| 9,814 | 43.817352 | 118 | py |
fitclip | fitclip-main/aligner/encoder/frozen_in_time.py | import logging
import sys
from typing import Any, Dict, Literal, Mapping, MutableMapping, Optional, Tuple, Union
import numpy as np
import timm
import torch
import torch.nn as nn
import torch.nn.functional as F
from cached_path import TYPE_PATH, cached_path
from transformers import AutoModel
from aligner.encoder import frozen_in_time_stub
from aligner.encoder.video_transformer import SpaceTimeTransformer
LOGGER = logging.getLogger(__name__)
STATE_DICT_MODULE_KEY = "module."
def state_dict_data_parallel_fix(load_state_dict: MutableMapping[str, Any],
curr_state_dict: MutableMapping[str, Any]) -> MutableMapping[str, Any]:
first_load_key = next(iter(load_state_dict.keys()))
first_curr_key = next(iter(curr_state_dict.keys()))
if not first_curr_key.startswith(STATE_DICT_MODULE_KEY) and first_load_key.startswith(STATE_DICT_MODULE_KEY):
return {k[len(STATE_DICT_MODULE_KEY):]: v for k, v in load_state_dict.items()}
elif first_curr_key.startswith(STATE_DICT_MODULE_KEY) and not first_load_key.startswith(STATE_DICT_MODULE_KEY):
return {STATE_DICT_MODULE_KEY + k: v for k, v in load_state_dict.items()}
else:
return load_state_dict
class BaseModel(nn.Module):
"""Base class for all models"""
def __str__(self) -> str:
return f"{super().__str__()}\n" \
f"Trainable parameters: {sum(np.prod(p.size()) for p in self.parameters() if p.requires_grad)}"
class FrozenInTime(BaseModel):
def __init__(self, video_params: Dict[str, Any], text_params: Dict[str, Any], projection_dim: int = 256,
load_checkpoint: Optional[TYPE_PATH] = None, projection: Literal["", "minimal"] = "minimal",
load_temporal_fix: Literal["zeros", "interp", "bilinear"] = "zeros") -> None:
super().__init__()
self.video_params = video_params
self.text_params = text_params
self.load_temporal_fix = load_temporal_fix
if not text_params["pretrained"]:
raise ValueError("HuggingFace text models require `pretrained` init.")
transformers_modeling_utils_logger = logging.getLogger("transformers.modeling_utils")
transformers_modeling_utils_logger.disabled = True
self.text_model = AutoModel.from_pretrained(text_params["model"])
transformers_modeling_utils_logger.disabled = False
pretrained = video_params["pretrained"]
if video_params["model"] == "SpaceTimeTransformer":
num_frames = video_params.get("num_frames", 4)
time_init = video_params.get("time_init", "zeros")
attention_style = video_params.get("attention_style", "frozen-in-time")
arch_config = video_params.get("arch_config", "base_patch16_224")
if arch_config == "base_patch16_224":
vit_model = timm.models.vision_transformer.vit_base_patch16_224(pretrained=pretrained)
model = SpaceTimeTransformer(num_frames=num_frames, time_init=time_init,
attention_style=attention_style)
else:
raise ValueError(f"Unrecognized arch_config: {arch_config}")
model.head = nn.Identity()
model.pre_logits = nn.Identity()
ftr_dim = model.embed_dim
if not load_checkpoint:
vit_checkpoint = vit_model.state_dict()
model.load_state_dict(vit_checkpoint, strict=False)
self.video_model = model
else:
raise ValueError(f"{video_params['model']} not supported")
# for backwards compatibility (old models)
self.video_model.fc = nn.Identity()
# Project to a common embedding
if projection == "minimal":
txt_proj = nn.Sequential(nn.ReLU(), nn.Linear(self.text_model.config.hidden_size, projection_dim))
vid_proj = nn.Sequential(nn.Linear(ftr_dim, projection_dim))
elif projection == "":
txt_proj = nn.Identity()
vid_proj = nn.Identity()
else:
raise ValueError(f"Unrecognized projection: {projection}")
self.txt_proj = txt_proj
self.vid_proj = vid_proj
if load_checkpoint:
load_checkpoint = cached_path(load_checkpoint)
sys.modules["parse_config"] = frozen_in_time_stub
LOGGER.info("Loading frozen-in-time checkpoint…")
# `map_location="cpu"` to avoid bloating GPU=0 with each process' copy of it.
checkpoint = torch.load(load_checkpoint, map_location="cpu")
del sys.modules["parse_config"]
state_dict = checkpoint["state_dict"]
new_state_dict = state_dict_data_parallel_fix(state_dict, self.state_dict())
new_state_dict = self._inflate_positional_embeds(new_state_dict)
self.load_state_dict(new_state_dict, strict=True) # noqa
LOGGER.info("Checkpoint loaded.")
def forward(self, data: Mapping[str, Any], return_embeds: bool = True) -> Union[torch.Tensor,
Tuple[torch.Tensor, torch.Tensor]]:
text_data = data["text"]
video_data = data["video"]
text_embeddings = self.compute_text(text_data)
video_embeddings = self.compute_video(video_data)
if return_embeds:
return text_embeddings, video_embeddings
return sim_matrix(text_embeddings, video_embeddings)
def compute_text(self, text_data: Mapping[str, Any]) -> torch.Tensor:
if self.text_params["model"].startswith("bert"):
text_embeddings = self.text_model(text_data["input_ids"], attention_mask=text_data["attention_mask"])[
"pooler_output"]
elif self.text_params["model"].startswith("distilbert"):
text_embeddings = self.text_model(**text_data).last_hidden_state[:, 0, :]
else:
raise ValueError(f"Unrecognized text model: {self.text_params['model']}")
return self.txt_proj(text_embeddings)
def compute_video(self, video_data: Mapping[str, Any]) -> torch.Tensor:
video_embeddings = self.video_model(video_data)
return self.vid_proj(video_embeddings)
def _inflate_positional_embeds(self, new_state_dict: MutableMapping[str, Any]) -> Mapping[str, Any]:
# allow loading of timesformer with fewer num_frames
curr_keys = set(self.state_dict().keys())
if "video_model.temporal_embed" in new_state_dict and "video_model.temporal_embed" in curr_keys:
load_temporal_embed = new_state_dict["video_model.temporal_embed"]
load_num_frames = load_temporal_embed.shape[1]
curr_num_frames = self.video_params["num_frames"]
embed_dim = load_temporal_embed.shape[2]
if load_num_frames != curr_num_frames:
if load_num_frames > curr_num_frames:
LOGGER.warning(f"The loaded {self.video_params['model']} model has MORE frames than the current "
f"one. Loading weights, filling in the extras via {self.load_temporal_fix}")
new_temporal_embed = load_temporal_embed[:, :curr_num_frames, :]
else:
LOGGER.warning(f"The loaded {self.video_params['model']} model has FEWER frames than the current "
f"one. Loading weights, filling in the extras via {self.load_temporal_fix}")
if self.load_temporal_fix == "zeros":
new_temporal_embed = torch.zeros([load_temporal_embed.shape[0], curr_num_frames, embed_dim])
new_temporal_embed[:, :load_num_frames] = load_temporal_embed
elif self.load_temporal_fix in ["interp", "bilinear"]:
# interpolate
# unsqueeze so pytorch thinks it's an image
mode = "nearest"
if self.load_temporal_fix == "bilinear":
mode = "bilinear"
load_temporal_embed = load_temporal_embed.unsqueeze(0)
new_temporal_embed = F.interpolate(load_temporal_embed,
(curr_num_frames, embed_dim), mode=mode).squeeze(0)
else:
raise ValueError(f"Unrecognized load_temporal_fix: {self.load_temporal_fix}")
new_state_dict["video_model.temporal_embed"] = new_temporal_embed
# allow loading with smaller spatial patches. assumes custom border crop, to append the
# border patches to the input sequence
if "video_model.pos_embed" in new_state_dict and "video_model.pos_embed" in curr_keys:
load_pos_embed = new_state_dict["video_model.pos_embed"]
load_num_patches = load_pos_embed.shape[1]
curr_pos_embed = self.state_dict()["video_model.pos_embed"]
if load_num_patches != curr_pos_embed.shape[1]:
raise ValueError(
"Loading models with different spatial resolution / patch number not yet implemented, sorry.")
return new_state_dict
def sim_matrix(a: torch.Tensor, b: torch.Tensor, eps: float = 1e-8) -> torch:
a_n, b_n = a.norm(dim=1)[:, None], b.norm(dim=1)[:, None]
a_norm = a / torch.max(a_n, eps * torch.ones_like(a_n)) # noqa
b_norm = b / torch.max(b_n, eps * torch.ones_like(b_n)) # noqa
return torch.mm(a_norm, b_norm.transpose(0, 1))
| 9,799 | 49.515464 | 119 | py |
fitclip | fitclip-main/aligner/encoder/frozen_in_time_video_text_encoder.py | import os
from typing import Iterable, Iterator
import torch
from overrides import overrides
from torchvision import transforms as T
from transformers import AutoTokenizer
from aligner.data.frame_sampler import FrameSampler, RandomFromUniformIntervalsFrameSampler, UniformFrameSampler
from aligner.encoder.frozen_in_time import FrozenInTime
from aligner.encoder.video_encoder import TYPE_TRANSFORM, TYPE_VIDEO_INPUT, float_standard_denormalize
from aligner.encoder.video_text_encoder import TYPE_TEXT_INPUT, TYPE_TOKENIZER, VideoTextEncoder
from aligner.transforms import ConvertBHWCtoBCHW, RandomResizedCropWithRandomInterpolation
def _normalize(t: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:
return t / torch.max(t.norm(dim=1, keepdim=True), eps * torch.ones_like(t)) # noqa
class FrozenInTimeVideoTextEncoder(VideoTextEncoder):
# FIXME: set the max tokens by default as in CLIP, also to avoid spending too much memory when using prompts.
def __init__(self, model: FrozenInTime, image_size: int = 224, num_frames: int = 4, max_tokens: int = 77) -> None:
super().__init__()
self.model = model
os.environ["TOKENIZERS_PARALLELISM"] = "0"
self.tokenizer = AutoTokenizer.from_pretrained(model.text_params["model"])
self.normalize = T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225))
self.image_size = image_size
self.num_frames = num_frames
self.max_tokens = max_tokens
@overrides(check_signature=False)
def encode_video(self, video: TYPE_VIDEO_INPUT, eps: float = 1e-8) -> torch.Tensor:
return _normalize(self.model.compute_video(video), eps=eps)
@overrides(check_signature=False)
def encode_text(self, text: TYPE_TEXT_INPUT, eps: float = 1e-8) -> torch.Tensor:
return _normalize(self.model.compute_text(text), eps=eps)
def _tokenize(self, texts: Iterable[str]) -> TYPE_TEXT_INPUT:
texts = texts if isinstance(texts, (list, tuple)) else list(texts)
return self.tokenizer(texts, return_tensors="pt", padding=True, truncation=True, max_length=self.max_tokens)
@overrides
def get_tokenizer(self) -> TYPE_TOKENIZER:
return self._tokenize
@overrides
def decode_text(self, text: TYPE_TEXT_INPUT) -> Iterator[str]:
return self.tokenizer.batch_decode(text["input_ids"], skip_special_tokens=True)
@overrides
def get_train_frame_sampler(self) -> FrameSampler:
return RandomFromUniformIntervalsFrameSampler(self.num_frames)
@overrides
def get_eval_frame_sampler(self) -> FrameSampler:
return UniformFrameSampler(self.num_frames)
@overrides
def get_train_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
return T.Compose([
ConvertBHWCtoBCHW(),
T.ConvertImageDtype(dtype),
RandomResizedCropWithRandomInterpolation(self.image_size, scale=(0.5, 1.0)),
T.RandomHorizontalFlip(),
self.normalize,
])
@overrides
def get_eval_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
return T.Compose([
ConvertBHWCtoBCHW(),
T.ConvertImageDtype(dtype),
T.Resize(self.image_size),
T.CenterCrop(self.image_size),
self.normalize,
])
@property
@overrides
def should_pad_batch(self) -> bool:
return True
@overrides
def to_bchw(self, t: torch.Tensor) -> torch.Tensor:
return t
@overrides
def denormalize_video_tensor(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
return float_standard_denormalize(video, mean=self.normalize.mean, std=self.normalize.std)
| 3,686 | 37.810526 | 118 | py |
fitclip | fitclip-main/aligner/encoder/videoclip.py | import torch
import torch.utils.checkpoint
from torch import nn
from transformers import AutoConfig, BertModel, BertPreTrainedModel
from transformers.activations import ACT2FN
from transformers.models.bert.modeling_bert import BertEmbeddings, BertEncoder
class VideoTokenMLP(nn.Module):
def __init__(self, config):
super().__init__()
input_dim = config.input_dim if hasattr(config, "input_dim") else 512
self.linear1 = nn.Linear(input_dim, config.hidden_size)
self.LayerNorm = nn.LayerNorm(config.hidden_size)
self.activation = ACT2FN[config.hidden_act]
self.linear2 = nn.Linear(config.hidden_size, config.hidden_size)
def forward(self, hidden_states):
hidden_states = self.linear1(hidden_states)
hidden_states = self.activation(hidden_states)
hidden_states = self.LayerNorm(hidden_states)
hidden_states = self.linear2(hidden_states)
return hidden_states
class MMBertEmbeddings(BertEmbeddings):
def __init__(self, config):
super().__init__(config)
self.max_video_len = config.max_video_len
if hasattr(config, "use_seg_emb") and config.use_seg_emb:
"""the original VLM paper uses seg_embeddings for temporal space.
although not used it changed the randomness of initialization.
we keep it for reproducibility.
"""
self.seg_embeddings = nn.Embedding(256, config.hidden_size)
def forward( # noqa
self,
input_ids,
input_video_embeds,
token_type_ids=None,
position_ids=None,
inputs_embeds=None,
):
input_tensor = input_ids if input_ids is not None else inputs_embeds
if input_video_embeds is not None:
input_shape = (
input_tensor.size(0),
input_tensor.size(1) + input_video_embeds.size(1),
)
else:
input_shape = (input_tensor.size(0), input_tensor.size(1))
if position_ids is None:
"""
Auto skip position embeddings for text only case.
use cases:
(1) action localization and segmentation:
feed in len-1 dummy video token needs text part to
skip input_video_embeds.size(1) for the right
position_ids for video [SEP] and rest text tokens.
(2) MMFusionShare for two forward passes:
in `forward_text`: input_video_embeds is None.
need to skip video [SEP] token.
# video_len + 1: [CLS] + video_embed
# self.max_video_len + 1: [SEP] for video.
# self.max_video_len + 2: [SEP] for video.
# self.max_video_len + input_ids.size(1): rest for text.
"""
if input_video_embeds is not None:
video_len = input_video_embeds.size(1)
starting_offset = self.max_video_len + 1 # video [SEP]
ending_offset = self.max_video_len + input_ids.size(1)
else:
video_len = 0
starting_offset = self.max_video_len + 2 # first text token.
ending_offset = self.max_video_len + input_ids.size(1) + 1
position_ids = torch.cat([
self.position_ids[:, :video_len + 1],
self.position_ids[:, starting_offset:ending_offset]
], dim=1)
if token_type_ids is None:
token_type_ids = torch.zeros(
input_shape, dtype=torch.long, device=self.position_ids.device
)
"""
the format of input_ids is [CLS] [SEP] caption [SEP] padding.
the goal is to build [CLS] video tokens [SEP] caption [SEP] .
"""
if inputs_embeds is None:
inputs_embeds = self.word_embeddings(input_ids)
if input_video_embeds is not None:
inputs_mm_embeds = torch.cat([
inputs_embeds[:, :1], input_video_embeds, inputs_embeds[:, 1:]
], dim=1)
else:
# text only for `MMFusionShare`.
inputs_mm_embeds = inputs_embeds
position_embeddings = self.position_embeddings(position_ids)
token_type_embeddings = self.token_type_embeddings(token_type_ids)
embeddings = inputs_mm_embeds + position_embeddings
embeddings += token_type_embeddings
embeddings = self.LayerNorm(embeddings)
embeddings = self.dropout(embeddings)
return embeddings
class MultiLayerAttentionMaskBertEncoder(BertEncoder):
"""extend BertEncoder with the capability of
multiple layers of attention mask."""
def forward( # noqa
self,
hidden_states,
attention_mask=None,
head_mask=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_attentions=False,
output_hidden_states=False,
return_dict=False,
):
all_hidden_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
layer_head_mask = head_mask[i] if head_mask is not None else None
layer_attention_mask = (
attention_mask[:, i, :, :, :]
if attention_mask.dim() == 5
else attention_mask
)
if getattr(self.config, "gradient_checkpointing", False):
def create_custom_forward(module):
def custom_forward(*inputs):
return module(*inputs, output_attentions)
return custom_forward
layer_outputs = torch.utils.checkpoint.checkpoint(
create_custom_forward(layer_module),
hidden_states,
layer_attention_mask,
layer_head_mask,
encoder_hidden_states,
encoder_attention_mask,
)
else:
layer_outputs = layer_module(
hidden_states,
layer_attention_mask,
layer_head_mask,
encoder_hidden_states,
encoder_attention_mask,
output_attentions,
)
hidden_states = layer_outputs[0]
if output_attentions:
all_attentions = all_attentions + (layer_outputs[1],)
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_states,)
return tuple(
v
for v in [hidden_states, all_hidden_states, all_attentions]
if v is not None
)
class MMBertModel(BertModel):
"""MMBertModel has MMBertEmbedding to support video tokens."""
def __init__(self, config, add_pooling_layer=True): # noqa
super().__init__(config)
# overwrite embedding
self.embeddings = MMBertEmbeddings(config)
self.encoder = MultiLayerAttentionMaskBertEncoder(config)
self.init_weights() # noqa
def forward(
self,
input_ids=None,
input_video_embeds=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
encoder_hidden_states=None,
encoder_attention_mask=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
separate_forward_split=None,
):
output_attentions = (
output_attentions
if output_attentions is not None
else self.config.output_attentions # noqa
)
output_hidden_states = (
output_hidden_states
if output_hidden_states is not None
else self.config.output_hidden_states # noqa
)
return_dict = (
return_dict if return_dict is not None
else self.config.use_return_dict # noqa
)
if input_ids is not None and inputs_embeds is not None:
raise ValueError(
"You cannot specify both input_ids "
"and inputs_embeds at the same time"
)
elif input_ids is not None:
if input_video_embeds is not None:
input_shape = (
input_ids.size(0),
input_ids.size(1) + input_video_embeds.size(1),
)
else:
input_shape = (
input_ids.size(0),
input_ids.size(1),
)
elif inputs_embeds is not None:
if input_video_embeds is not None:
input_shape = (
inputs_embeds.size(0),
inputs_embeds.size(1) + input_video_embeds.size(1),
)
else:
input_shape = (
input_ids.size(0),
input_ids.size(1),
)
else:
raise ValueError(
"You have to specify either input_ids or inputs_embeds")
device = (inputs_embeds if input_ids is None else input_ids).device
if attention_mask is None:
attention_mask = torch.ones(input_shape, device=device)
if token_type_ids is None:
token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
# We can provide a self-attention mask of dimensions
# [batch_size, from_seq_length, to_seq_length]
# ourselves in which case
# we just need to make it broadcastable to all heads.
extended_attention_mask: torch.Tensor = \
self.get_extended_attention_mask(
attention_mask, input_shape, device)
# If a 2D or 3D attention mask is provided for the cross-attention
# we need to make broadcastable to
# [batch_size, num_heads, seq_length, seq_length]
if self.config.is_decoder and encoder_hidden_states is not None: # noqa
(
encoder_batch_size,
encoder_sequence_length,
_,
) = encoder_hidden_states.size()
encoder_hidden_shape = (
encoder_batch_size, encoder_sequence_length)
if encoder_attention_mask is None:
encoder_attention_mask = torch.ones(
encoder_hidden_shape, device=device)
encoder_extended_attention_mask = self.invert_attention_mask( # noqa
encoder_attention_mask
)
else:
encoder_extended_attention_mask = None
# Prepare head mask if needed
# 1.0 in head_mask indicate we keep the head
# attention_probs has shape bsz x n_heads x N x N
# input head_mask has shape [num_heads] or
# [num_hidden_layers x num_heads]
# and head_mask is converted to shape
# [num_hidden_layers x batch x num_heads x seq_length x seq_length]
head_mask = self.get_head_mask( # noqa
head_mask, self.config.num_hidden_layers) # noqa
embedding_output = self.embeddings(
input_ids,
input_video_embeds,
position_ids=position_ids,
token_type_ids=token_type_ids,
inputs_embeds=inputs_embeds,
)
if separate_forward_split is not None:
split_embedding_output = \
embedding_output[:, :separate_forward_split]
split_extended_attention_mask = extended_attention_mask[
:, :, :, :separate_forward_split, :separate_forward_split
]
split_encoder_outputs = self.encoder(
split_embedding_output,
attention_mask=split_extended_attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
assert (
len(split_encoder_outputs) <= 2
), "we do not support merge on attention for now."
encoder_outputs = [[split_encoder_outputs[0]]]
if len(split_encoder_outputs) == 2:
encoder_outputs.append([])
for _all_hidden_states in split_encoder_outputs[1]:
encoder_outputs[-1].append([_all_hidden_states])
split_embedding_output = \
embedding_output[:, separate_forward_split:]
split_extended_attention_mask = extended_attention_mask[
:, :, :, separate_forward_split:, separate_forward_split:
]
split_encoder_outputs = self.encoder(
split_embedding_output,
attention_mask=split_extended_attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
assert len(split_encoder_outputs) <= 2, "we do not support merge on attention for now."
encoder_outputs[0].append(split_encoder_outputs[0])
encoder_outputs[0] = torch.cat(encoder_outputs[0], dim=1)
if len(split_encoder_outputs) == 2:
for layer_idx, _all_hidden_states in enumerate(
split_encoder_outputs[1]
):
encoder_outputs[1][layer_idx].append(_all_hidden_states)
encoder_outputs[1][layer_idx] = torch.cat(
encoder_outputs[1][layer_idx], dim=1
)
encoder_outputs = tuple(encoder_outputs)
else:
encoder_outputs = self.encoder(
embedding_output,
attention_mask=extended_attention_mask,
head_mask=head_mask,
encoder_hidden_states=encoder_hidden_states,
encoder_attention_mask=encoder_extended_attention_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = encoder_outputs[0]
pooled_output = None if self.pooler is None else self.pooler(sequence_output) # noqa
return (sequence_output, pooled_output) + encoder_outputs[1:]
def get_extended_attention_mask(self, attention_mask, input_shape, device):
"""This is borrowed from `modeling_utils.py` with the support of
multi-layer attention masks.
The second dim is expected to be number of layers.
See `MMAttentionMaskProcessor`.
Makes broadcastable attention and causal masks so that future
and masked tokens are ignored.
Arguments:
attention_mask (:obj:`torch.Tensor`):
Mask with ones indicating tokens to attend to,
zeros for tokens to ignore.
input_shape (:obj:`Tuple[int]`):
The shape of the input to the model.
device: (:obj:`torch.device`):
The device of the input to the model.
Returns:
:obj:`torch.Tensor` The extended attention mask, with the same dtype as :obj:`attention_mask.dtype`.
"""
# We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] ourselves
# in which case we just need to make it broadcastable to all heads.
if attention_mask.dim() == 4:
extended_attention_mask = attention_mask[:, :, None, :, :]
extended_attention_mask = extended_attention_mask.to(dtype=self.dtype) # noqa; fp16 compatibility
extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0
return extended_attention_mask
else:
return super().get_extended_attention_mask(attention_mask, input_shape, device) # noqa
class MMBertForEncoder(BertPreTrainedModel):
"""A BertModel for Contrastive Learning."""
def __init__(self, config):
super().__init__(config)
self.videomlp = VideoTokenMLP(config)
self.bert = MMBertModel(config)
self.init_weights() # noqa
def forward(
self,
input_ids=None,
input_video_embeds=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
return_dict = self.config.use_return_dict if return_dict is None else return_dict # noqa
video_tokens = None if input_video_embeds is None else self.videomlp(input_video_embeds)
return self.bert(input_ids, video_tokens, attention_mask=attention_mask, token_type_ids=token_type_ids, # noqa
position_ids=position_ids, head_mask=head_mask, inputs_embeds=inputs_embeds,
output_attentions=output_attentions, output_hidden_states=output_hidden_states,
return_dict=return_dict)
class MMFusion(nn.Module):
"""a MMPT wrapper class for MMBert style models.
TODO: move isolated mask to a subclass.
"""
def __init__(self, max_video_len: int = 32, last_iso_layer: int = 12, num_hidden_video_layers: int = 6):
super().__init__()
self.model_name = "bert-base-uncased"
transformer_config = AutoConfig.from_pretrained(self.model_name)
self.hidden_size = transformer_config.hidden_size
self.is_train = False
# 0 means no iso; 1-12 means iso up to that layer.
self.num_hidden_layers = transformer_config.num_hidden_layers
self.last_iso_layer = last_iso_layer
model_config = AutoConfig.from_pretrained(self.model_name)
model_config.max_video_len = max_video_len
# TODO: make each model a set of config class.
if hasattr(model_config, "num_layers"):
model_config.num_layers = num_hidden_video_layers
else:
model_config.num_hidden_layers = num_hidden_video_layers
self.video_encoder = MMBertForEncoder.from_pretrained(self.model_name, config=model_config)
# exact same NLP model from HuggingFace transformer.
self.text_encoder = AutoConfig.from_pretrained("bert-base-uncased")
def forward(
self,
caps,
cmasks,
vfeats,
vmasks,
**kwargs
):
raise NotImplementedError(
"Please derive MMFusion module."
)
def _mm_on_the_fly(
self,
cmasks,
vmasks,
attention_mask
):
"""helper function for mask, seg_ids and token_type_ids."""
if attention_mask is None:
attention_mask = self._mm_attention_mask(cmasks, vmasks)
"""
0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
| first sequence | second sequence |
"""
token_type_ids = torch.cat([
torch.zeros((vmasks.size(0), vmasks.size(1) + 2), dtype=torch.long, device=vmasks.device),
torch.ones((cmasks.size(0), cmasks.size(1) - 2), dtype=torch.long, device=cmasks.device)], dim=1)
return attention_mask, token_type_ids
def _mm_attention_mask(self, cmasks, vmasks):
assert cmasks.size(0) == vmasks.size(0), "{}, {}, {}, {}".format(
str(cmasks.size()),
str(vmasks.size()),
str(cmasks.size(0)),
str(vmasks.size(0)),
)
mm_mask = torch.cat([cmasks[:, :1], vmasks, cmasks[:, 1:]], dim=1)
if self.last_iso_layer == 0:
# hard attention mask.
return mm_mask
else:
# a gpu iso mask; 0 : num_iso_layer is isolated;
# num_iso_layer: are MM-fused.
# make an iso layer
batch_size = cmasks.size(0)
iso_mask = self._make_iso_mask(batch_size, cmasks, vmasks)
mm_mask = mm_mask[:, None, :].repeat(1, mm_mask.size(-1), 1)
iso_mm_masks = []
# hard attention mask.
iso_mask = iso_mask[:, None, :, :].repeat(1, self.last_iso_layer, 1, 1)
iso_mm_masks.append(iso_mask)
if self.last_iso_layer < self.num_hidden_layers:
mm_mask = mm_mask[:, None, :, :].repeat(1, self.num_hidden_layers - self.last_iso_layer, 1, 1)
iso_mm_masks.append(mm_mask)
iso_mm_masks = torch.cat(iso_mm_masks, dim=1)
return iso_mm_masks
def _make_iso_mask(self, batch_size, cmasks, vmasks): # noqa
cls_self_mask = torch.cat(
[
torch.ones(
(batch_size, 1), dtype=torch.bool, device=cmasks.device),
torch.zeros(
(batch_size, cmasks.size(1) + vmasks.size(1) - 1),
dtype=torch.bool, device=cmasks.device)
], dim=1)
iso_video_mask = torch.cat(
[
# [CLS] is not used.
torch.zeros(
(batch_size, 1), dtype=torch.bool, device=cmasks.device
),
vmasks,
# assume to be 1.
cmasks[:, 1:2],
# 2 means [CLS] + [SEP]
torch.zeros(
(batch_size, cmasks.size(1) - 2),
dtype=torch.bool,
device=cmasks.device,
),
],
dim=1,
)
iso_text_mask = torch.cat(
[
torch.zeros(
(batch_size, 2 + vmasks.size(1)),
dtype=torch.bool,
device=cmasks.device,
), # [CLS] is not used.
cmasks[:, 2:], # assume to be 1.
],
dim=1,
)
cls_self_mask = cls_self_mask[:, None, :]
iso_video_mask = iso_video_mask[:, None, :].repeat(
1, vmasks.size(1) + 1, 1)
iso_text_mask = iso_text_mask[:, None, :].repeat(
1, cmasks.size(1) - 2, 1)
return torch.cat([cls_self_mask, iso_video_mask, iso_text_mask], dim=1)
def _pooling_vt_layer(
self,
layered_sequence_output,
cmasks,
vmasks
):
layer_idx = self.last_iso_layer \
if self.last_iso_layer > 0 else self.num_hidden_layers
hidden_state = layered_sequence_output[layer_idx]
# also output pooled_video and pooled_text.
batch_size = cmasks.size(0)
# pool the modality.
text_offset = vmasks.size(1) + 2 # [CLS] + [SEP]
# video tokens + [SEP]
video_outputs = hidden_state[:, 1:text_offset]
video_attention_mask = torch.cat(
[
vmasks,
torch.ones((batch_size, 1), dtype=torch.bool, device=vmasks.device),
],
dim=1,
)
assert video_outputs.size(1) == video_attention_mask.size(1)
pooled_video = (torch.sum(video_outputs * video_attention_mask.unsqueeze(-1), dim=1)
/ video_attention_mask.sum(1, keepdim=True))
# pooled_video = torch.mean(video_outputs[0], dim=1)
# text tokens + [SEP]
text_attention_mask = cmasks[:, 2:]
text_outputs = hidden_state[:, text_offset:]
assert text_outputs.size(1) == text_attention_mask.size(1)
pooled_text = torch.sum(
text_outputs * text_attention_mask.unsqueeze(-1), dim=1
) / text_attention_mask.sum(1, keepdim=True)
return pooled_video, pooled_text
class MMFusionSeparate(MMFusion):
def forward(
self,
caps,
cmasks,
vfeats,
vmasks,
attention_mask=None,
video_label=None,
text_label=None,
output_hidden_states=False,
**kwargs
):
pooled_video = self.forward_video(
vfeats,
vmasks,
caps,
cmasks,
output_hidden_states
)
pooled_text = self.forward_text(
caps,
cmasks,
output_hidden_states
)
return {"pooled_video": pooled_video, "pooled_text": pooled_text}
def forward_video(
self,
vfeats,
vmasks,
caps,
cmasks,
output_hidden_states=False,
**kwargs # noqa
):
input_ids = caps[:, :2]
attention_mask = torch.cat([cmasks[:, :1], vmasks, cmasks[:, 1:2]], dim=1)
token_type_ids = torch.zeros(
(vmasks.size(0), vmasks.size(1) + 2),
dtype=torch.long,
device=vmasks.device)
outputs = self.video_encoder(
input_ids=input_ids,
input_video_embeds=vfeats,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
output_hidden_states=True
)
video_outputs = outputs[0]
if output_hidden_states:
return video_outputs
batch_size = cmasks.size(0)
video_attention_mask = torch.cat([torch.zeros((batch_size, 1), dtype=torch.bool, device=vmasks.device),
vmasks, torch.ones((batch_size, 1), dtype=torch.bool, device=vmasks.device)],
dim=1)
assert video_outputs.size(1) == video_attention_mask.size(1)
video_attention_mask = video_attention_mask.type(video_outputs.dtype) / video_attention_mask.sum(1,
keepdim=True)
return torch.bmm(video_outputs.transpose(2, 1), video_attention_mask.unsqueeze(2)).squeeze(-1)
def forward_text(
self,
caps,
cmasks,
output_hidden_states=False,
**kwargs # noqa
):
input_ids = torch.cat([
caps[:, :1], caps[:, 2:],
], dim=1)
attention_mask = torch.cat([
cmasks[:, :1],
cmasks[:, 2:]
], dim=1)
# different from sharing, we use all-0 type.
token_type_ids = torch.zeros(
(cmasks.size(0), cmasks.size(1) - 1),
dtype=torch.long,
device=cmasks.device)
outputs = self.text_encoder(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
output_hidden_states=True
)
text_outputs = outputs[0]
if output_hidden_states:
return text_outputs
batch_size = caps.size(0)
# text tokens + [SEP]
text_attention_mask = torch.cat([torch.zeros((batch_size, 1), dtype=torch.bool, device=cmasks.device),
cmasks[:, 2:]], dim=1)
assert text_outputs.size(1) == text_attention_mask.size(1)
text_attention_mask = text_attention_mask.type(text_outputs.dtype) / text_attention_mask.sum(1, keepdim=True)
return torch.bmm(text_outputs.transpose(2, 1), text_attention_mask.unsqueeze(2)).squeeze(-1)
| 28,028 | 38.256303 | 119 | py |
fitclip | fitclip-main/aligner/encoder/video_transformer.py | """
Implementations of Video Transformers in PyTorch
A PyTorch implementation of space-time transformer as described in
'Frozen in Time: A Joint Image and Video Encoder for End-to-End Retrieval' - https://arxiv.org/abs/2104.00650
A PyTorch implementation of timesformer as described in
'Is Space-Time Attention All You Need for Video Understanding?' - https://arxiv.org/abs/2102.05095
Acknowledgments:
- This code builds on Ross Wightman's vision_transformer code in pytorch-image-models:
https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
- It is also inspired by lucidrains timesformer implementation:
https://github.com/lucidrains/TimeSformer-pytorch
Hacked together by Max Bain
"""
from collections import OrderedDict
from functools import partial
import torch
from einops import rearrange, repeat
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
from torch import einsum, nn
def attn(q, k, v):
sim = einsum('b i d, b j d -> b i j', q, k)
attn = sim.softmax(dim=-1)
out = einsum('b i j, b j d -> b i d', attn, v)
return out
class Mlp(nn.Module):
def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
super().__init__()
out_features = out_features or in_features
hidden_features = hidden_features or in_features
self.fc1 = nn.Linear(in_features, hidden_features)
self.act = act_layer()
self.fc2 = nn.Linear(hidden_features, out_features)
self.drop = nn.Dropout(drop)
def forward(self, x):
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
x = self.fc2(x)
x = self.drop(x)
return x
class VideoPatchEmbed(nn.Module):
""" Video to Patch Embedding
"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768,
num_frames=8):
super().__init__()
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) * num_frames
self.img_size = img_size
self.patch_size = patch_size
self.num_patches = num_patches
self.num_frames = num_frames
self.embed_dim = embed_dim
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
def forward(self, x):
B, F, C, H, W = x.shape
assert F <= self.num_frames
x = x.view(-1, C, H, W)
x = self.proj(x)
return x
class VarAttention(nn.Module):
def __init__(self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0., proj_drop=0.,
initialize='random'):
super().__init__()
self.num_heads = num_heads
head_dim = dim // num_heads
# NOTE scale factor was wrong in my original version, can set manually to be compat with prev weights
self.scale = qk_scale or head_dim ** -0.5
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
self.proj = nn.Linear(dim, dim)
if initialize == 'zeros':
self.qkv.weight.data.fill_(0)
self.qkv.bias.data.fill_(0)
# fill proj weight with 1 here to improve training dynamics. Otherwise temporal attention inputs
# are multiplied by 0*0, which is hard for the model to move out of.
self.proj.weight.data.fill_(1)
self.proj.bias.data.fill_(0)
self.attn_drop = nn.Dropout(attn_drop)
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x, einops_from, einops_to, **einops_dims):
h = self.num_heads
# project x to q, k, v values
q, k, v = self.qkv(x).chunk(3, dim=-1)
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
q *= self.scale
# splice out CLS token at index 1
(cls_q, q_), (cls_k, k_), (cls_v, v_) = map(lambda t: (t[:, 0:1], t[:, 1:]), (q, k, v))
# let CLS token attend to key / values of all patches across time and space
cls_out = attn(cls_q, k, v)
# rearrange across time or space
q_, k_, v_ = map(lambda t: rearrange(t, f'{einops_from} -> {einops_to}', **einops_dims), (q_, k_, v_))
# expand cls token keys and values across time or space and concat
r = q_.shape[0] // cls_k.shape[0]
cls_k, cls_v = map(lambda t: repeat(t, 'b () d -> (b r) () d', r=r), (cls_k, cls_v))
k_ = torch.cat((cls_k, k_), dim=1)
v_ = torch.cat((cls_v, v_), dim=1)
# attention
out = attn(q_, k_, v_)
# merge back time or space
out = rearrange(out, f'{einops_to} -> {einops_from}', **einops_dims)
# concat back the cls token
out = torch.cat((cls_out, out), dim=1)
# merge back the heads
out = rearrange(out, '(b h) n d -> b n (h d)', h=h)
# to out
x = self.proj(out)
x = self.proj_drop(x)
return x
class SpaceTimeBlock(nn.Module):
def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None, drop=0., attn_drop=0.,
drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, time_init='zeros',
attention_style='frozen-in-time'):
super().__init__()
self.norm1 = norm_layer(dim)
self.attn = VarAttention(
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop)
self.timeattn = VarAttention(
dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop,
initialize=time_init)
# NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
self.norm2 = norm_layer(dim)
mlp_hidden_dim = int(dim * mlp_ratio)
self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
self.norm3 = norm_layer(dim)
self.attention_style = attention_style
def forward(self, x, einops_from_space, einops_to_space, einops_from_time, einops_to_time,
time_n, space_f):
time_output = self.timeattn(self.norm3(x), einops_from_time, einops_to_time, n=time_n)
time_residual = x + time_output
space_output = self.attn(self.norm1(time_residual), einops_from_space,
einops_to_space, f=space_f)
if self.attention_style == 'frozen-in-time':
space_residual = x + self.drop_path(space_output)
else:
raise NotImplementedError
x = space_residual + self.drop_path(self.mlp(self.norm2(space_residual)))
return x
class SpaceTimeTransformer(nn.Module):
""" Vision Transformer
A PyTorch impl of : `Space-Time Transformer` from Frozen-in-time - by Max Bain.
https://arxiv.org/abs/2104.00650
Based off:
- ViT implementation from the timm library
[https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py]
lucidrains timesformer implementation [https://github.com/lucidrains/TimeSformer-pytorch].
Notable differences:
- allows for variable length input frames (<= num_frames)
- allows for variable length input resolution (<= (img_size, img_size)) [UNTESTED]
- different attention block mechanism
"""
def __init__(self, img_size=224, patch_size=16, in_chans=3, num_classes=1000, embed_dim=768, depth=12,
num_heads=12, mlp_ratio=4., qkv_bias=True, qk_scale=None, representation_size=None,
drop_rate=0., attn_drop_rate=0., drop_path_rate=0., hybrid_backbone=None, norm_layer=None,
num_frames=8, time_init='rand', attention_style='frozen-in-time'):
"""
Args:
img_size (int, tuple): input image size
patch_size (int, tuple): patch size
in_chans (int): number of input channels
num_classes (int): number of classes for classification head
embed_dim (int): embedding dimension
depth (int): depth of transformer
num_heads (int): number of attention heads
mlp_ratio (int): ratio of mlp hidden dim to embedding dim
qkv_bias (bool): enable bias for qkv if True
qk_scale (float): override default qk scale of head_dim ** -0.5 if set
representation_size (Optional[int]): enable and set representation layer (pre-logits) to this value if set
drop_rate (float): dropout rate
attn_drop_rate (float): attention dropout rate
drop_path_rate (float): stochastic depth rate
hybrid_backbone (nn.Module): CNN backbone to use in-place of PatchEmbed module
norm_layer: (nn.Module): normalization layer
num_frames: (int) maximum number of frames expected as input
time_init: (str) how to initialise the time attention layer, 'zeros' allows for the timesformer to start off
as ViT.
attention_style: (str) how to attend to space and time.
"""
super().__init__()
self.num_classes = num_classes
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
self.num_frames = num_frames
self.embed_dim = embed_dim
norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)
if hybrid_backbone is not None:
raise NotImplementedError('hybrid backbone not implemented')
else:
self.patch_embed = VideoPatchEmbed(
img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, num_frames=num_frames)
num_patches = self.patch_embed.num_patches
self.patches_per_frame = num_patches // num_frames
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
self.pos_embed = nn.Parameter(
torch.zeros(1, self.patches_per_frame + 1,
embed_dim)) # remember to take pos_embed[1:] for tiling over time
self.temporal_embed = nn.Parameter(torch.zeros(1, num_frames, embed_dim))
self.pos_drop = nn.Dropout(p=drop_rate)
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
self.blocks = nn.ModuleList([
SpaceTimeBlock(
dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, time_init=time_init,
attention_style=attention_style)
for i in range(depth)])
self.norm = norm_layer(embed_dim)
# Representation layer
if representation_size:
self.num_features = representation_size
self.pre_logits = nn.Sequential(OrderedDict([
('fc', nn.Linear(embed_dim, representation_size)),
('act', nn.Tanh())
]))
else:
self.pre_logits = nn.Identity()
# Classifier head
self.head = nn.Linear(self.num_features, num_classes) if num_classes > 0 else nn.Identity()
trunc_normal_(self.pos_embed, std=.02)
trunc_normal_(self.cls_token, std=.02)
# if num_frames > 1, then we perform ViT inflation and initialise time attention to zero so not necessary.
if num_frames == 1:
self.apply(self._init_weights)
# einops transformations
self.einops_from_space = 'b (f n) d'
self.einops_to_space = '(b f) n d'
self.einops_from_time = 'b (f n) d'
self.einops_to_time = '(b n) f d'
@staticmethod
def _init_weights(m):
if isinstance(m, nn.Linear):
trunc_normal_(m.weight, std=.02)
if isinstance(m, nn.Linear) and m.bias is not None:
nn.init.constant_(m.bias, 0)
elif isinstance(m, nn.LayerNorm):
nn.init.constant_(m.bias, 0)
nn.init.constant_(m.weight, 1.0)
@torch.jit.ignore
def no_weight_decay(self):
return {'pos_embed', 'cls_token'}
def get_classifier(self):
return self.head
def reset_classifier(self, num_classes):
self.num_classes = num_classes
self.head = nn.Linear(self.embed_dim, num_classes) if num_classes > 0 else nn.Identity()
def forward_features(self, x):
b, curr_frames, channels, _, _ = x.shape
x = self.patch_embed(x)
x = x.flatten(2).transpose(2, 1)
x = x.reshape(b, -1, self.patch_embed.embed_dim)
BF = x.shape[0]
cls_tokens = self.cls_token.expand(BF, -1, -1) # stole cls_tokens impl from Phil Wang, thanks
x = torch.cat((cls_tokens, x), dim=1)
# positional embed needs to be tiled for each frame (this does [1,2,3] --> [1,2,3,1,2,3]...)
cls_embed = self.pos_embed[:, 0, :].unsqueeze(1)
tile_pos_embed = self.pos_embed[:, 1:, :].repeat(1, self.num_frames, 1)
# temporal embed needs to be repeated within each frame (this does [1,2,3] --> [1,1,1,2,2,2,3,3,3]...)
tile_temporal_embed = self.temporal_embed.repeat_interleave(self.patches_per_frame, 1)
total_pos_embed = tile_pos_embed + tile_temporal_embed
total_pos_embed = torch.cat([cls_embed, total_pos_embed], dim=1)
curr_patches = x.shape[1]
x = x + total_pos_embed[:, :curr_patches]
x = self.pos_drop(x)
n = self.patches_per_frame
f = curr_frames
for blk in self.blocks:
x = blk(x, self.einops_from_space, self.einops_to_space, self.einops_from_time,
self.einops_to_time,
time_n=n, space_f=f)
x = self.norm(x)[:, 0]
x = self.pre_logits(x)
return x
def forward(self, x):
x = self.forward_features(x)
x = self.head(x)
return x
| 14,253 | 40.800587 | 120 | py |
fitclip | fitclip-main/aligner/encoder/clip_video_text_encoder.py | import os.path
import shutil
import tempfile
from typing import Iterable, Iterator, Tuple
import torch
from cached_path import cached_path
from clip import clip
from clip.model import CLIP
from overrides import overrides
from torch import nn
from torchvision import transforms as T
from aligner.data.frame_sampler import FrameSampler, RandomFromUniformIntervalsFrameSampler, UniformFrameSampler
from aligner.encoder.video_encoder import TYPE_TRANSFORM, float_standard_denormalize
from aligner.encoder.video_text_encoder import TYPE_TEXT_INPUT, TYPE_TOKENIZER, TYPE_VIDEO_INPUT, VideoTextEncoder
from aligner.transforms import ConvertBHWCtoBCHW, RandomResizedCropWithRandomInterpolation
# By default, `clip.load` uses part in half and part in single precision for GPU.
# But this may cause issues with the teacher-student model, and we can actually control it from the trainer.
def load_clip_in_float32(*args, **kwargs) -> Tuple[nn.Module, TYPE_TRANSFORM]:
model, transform = clip.load(*args, **kwargs)
model.float()
return model, transform
# Necessary to use from Hydra so to get the first element of the tuple from `clip.load`.
# It also does more stuff than `clip.load`.
def load_clip_model(name: str, *args, **kwargs) -> nn.Module:
temp_filepaths = []
try:
if "://" in name:
name = cached_path(name)
elif os.path.exists(name) and not os.path.isdir(name) and not os.path.isfile(name):
# It could be a pipe. It could be created by a process substitution.
# We copy it to a file because `clip.load` has a check that it's a file (and hence not a pipe).
with tempfile.NamedTemporaryFile(delete=False) as output_file, open(name, "rb") as input_file:
shutil.copyfileobj(input_file, output_file)
name = output_file.name
temp_filepaths.append(name)
# We don't use the logic scale from CLIP but ours, so it may not exist. Here we need to re-create the variable,
# so it doesn't fail when loading this `state_dict`.
if os.path.exists(name): # It doesn't apply if it's a model name.
state_dict = torch.load(name)
if "logit_scale" not in state_dict:
state_dict["logit_scale"] = torch.tensor(float("nan"))
with tempfile.NamedTemporaryFile(delete=False) as file:
# We create a new file to respect the original one.
torch.save(state_dict, file)
name = file.name
temp_filepaths.append(name)
if not args: # If `args` is not empty, then `device` was set for `clip.load`.
kwargs.setdefault("device", "cpu") # To avoid bloating GPU 0 with each process' copy of it.
return load_clip_in_float32(name, *args, **kwargs)[0]
finally:
for path in temp_filepaths:
os.remove(path)
def _tokenize(texts: Iterable[str]) -> TYPE_TEXT_INPUT:
return {"input_ids": clip.tokenize(texts, truncate=True)} # noqa
class ClipVideoTextEncoder(VideoTextEncoder):
def __init__(self, model: CLIP, num_frames: int = 4) -> None:
super().__init__()
self.model = model
self.normalize = T.Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711))
self.num_frames = num_frames
# Indirectly unregister the param as we don't use it and would otherwise give problems while training.
if hasattr(self.model, "logit_scale"):
delattr(self.model, "logit_scale")
@overrides
def encode_video(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
batch_size = video.shape[0]
images = video.view(-1, *video.shape[2:])
encoded_video = self.model.encode_image(images)
encoded_video = encoded_video / encoded_video.norm(dim=-1, keepdim=True)
# Averaging the representations is the same as averaging the predictions:
# <t, (i1+i2)/2> = 1/2 <t, i1+i2> = (<t, i1> + <t, i2>) / 2
return encoded_video.view(batch_size, -1, *encoded_video.shape[1:]).mean(dim=1)
@overrides
def encode_text(self, text: TYPE_TEXT_INPUT) -> torch.Tensor:
encoded_texts = self.model.encode_text(text["input_ids"])
return encoded_texts / encoded_texts.norm(dim=-1, keepdim=True)
@overrides
def get_tokenizer(self) -> TYPE_TOKENIZER:
return _tokenize
@overrides
def decode_text(self, text: TYPE_TEXT_INPUT) -> Iterator[str]:
for text_instance in text:
yield clip._tokenizer.decode(text_instance["input_ids"])
@overrides
def get_train_frame_sampler(self) -> FrameSampler:
return RandomFromUniformIntervalsFrameSampler(self.num_frames)
@overrides
def get_eval_frame_sampler(self) -> FrameSampler:
return UniformFrameSampler(self.num_frames)
@overrides
def get_train_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
size = self.model.visual.input_resolution
return T.Compose([
ConvertBHWCtoBCHW(),
T.ConvertImageDtype(dtype),
RandomResizedCropWithRandomInterpolation(size, scale=(0.5, 1.0)),
T.RandomHorizontalFlip(),
self.normalize,
])
@overrides
def get_eval_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
size = self.model.visual.input_resolution
return T.Compose([
ConvertBHWCtoBCHW(),
T.ConvertImageDtype(dtype),
T.Resize(size, interpolation=T.InterpolationMode.BICUBIC),
T.CenterCrop(size),
self.normalize,
])
@property
@overrides
def should_pad_batch(self) -> bool:
return True
@overrides
def to_bchw(self, t: torch.Tensor) -> torch.Tensor:
return t
@overrides
def denormalize_video_tensor(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
return float_standard_denormalize(video, mean=self.normalize.mean, std=self.normalize.std)
| 6,022 | 39.972789 | 120 | py |
fitclip | fitclip-main/aligner/encoder/slip_video_text_encoder.py | from typing import Iterable, Iterator, Union
import torch
from cached_path import cached_path
from overrides import overrides
from torchvision import transforms as T
from aligner.data.frame_sampler import FrameSampler, UniformFrameSampler
from aligner.encoder import slip
from aligner.encoder.slip import CLIP, SLIP, SimpleTokenizer
from aligner.encoder.video_encoder import TYPE_TRANSFORM, float_standard_denormalize
from aligner.encoder.video_text_encoder import TYPE_TEXT_INPUT, TYPE_TOKENIZER, TYPE_VIDEO_INPUT, VideoTextEncoder
from aligner.transforms import ConvertBHWCtoBCHW
from util.typing_utils import TYPE_PATH
def load_model(path: TYPE_PATH) -> Union[CLIP, SLIP]:
checkpoint = torch.load(cached_path(path), map_location="cpu")
args = checkpoint["args"]
model = getattr(slip, args.model)(rand_embed=False, ssl_mlp_dim=args.ssl_mlp_dim, ssl_emb_dim=args.ssl_emb_dim)
model.load_state_dict({k.replace("module.", ""): v for k, v in checkpoint["state_dict"].items()})
return model
class SlipVideoTextEncoder(VideoTextEncoder):
def __init__(self, model: Union[CLIP, SLIP], num_frames: int = 4) -> None:
super().__init__()
self.model = model
self.tokenizer = SimpleTokenizer()
self.num_frames = num_frames
# Indirectly unregister the param as we don't use it and would otherwise give problems while training.
if hasattr(self.model, "logit_scale"):
delattr(self.model, "logit_scale")
@overrides
def encode_video(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
batch_size = video.shape[0] # noqa
images = video.view(-1, *video.shape[2:])
encoded_video = self.model.encode_image(images)
encoded_video = encoded_video / encoded_video.norm(dim=-1, keepdim=True)
# Averaging the representations is the same as averaging the predictions:
# <t, (i1+i2)/2> = 1/2 <t, i1+i2> = (<t, i1> + <t, i2>) / 2
return encoded_video.view(batch_size, -1, *encoded_video.shape[1:]).mean(dim=1)
@overrides
def encode_text(self, text: TYPE_TEXT_INPUT) -> torch.Tensor:
encoded_texts = self.model.encode_text(text["input_ids"])
return encoded_texts / encoded_texts.norm(dim=-1, keepdim=True)
def _tokenize(self, texts: Iterable[str]) -> TYPE_TEXT_INPUT:
return {"input_ids": self.tokenizer(texts)}
@overrides
def get_tokenizer(self) -> TYPE_TOKENIZER:
return self._tokenize
@overrides
def decode_text(self, text: TYPE_TEXT_INPUT) -> Iterator[str]:
for text_instance in text:
yield self.tokenizer.decode(text_instance["input_ids"])
@overrides
def get_train_frame_sampler(self) -> FrameSampler:
raise NotImplementedError
@overrides
def get_eval_frame_sampler(self) -> FrameSampler:
return UniformFrameSampler(self.num_frames)
@overrides
def get_train_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
raise NotImplementedError
@overrides
def get_eval_transform(self, dtype: torch.dtype) -> TYPE_TRANSFORM:
size = 224
return T.Compose([
ConvertBHWCtoBCHW(),
T.ConvertImageDtype(dtype),
T.Resize(size),
T.CenterCrop(size),
T.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
])
@property
@overrides
def should_pad_batch(self) -> bool:
return True
@overrides
def to_bchw(self, t: torch.Tensor) -> torch.Tensor:
return t
@overrides
def denormalize_video_tensor(self, video: TYPE_VIDEO_INPUT) -> torch.Tensor:
return float_standard_denormalize(video, mean=self.normalize.mean, std=self.normalize.std)
| 3,736 | 36.37 | 115 | py |
fitclip | fitclip-main/aligner/data/youcook2.py | import os
from glob import iglob
from typing import Optional, Tuple
import pandas as pd
from cached_path import cached_path
from overrides import overrides
from torch.utils.data import DataLoader
from aligner.data.video_data_module import VideoTextDataModule
from aligner.data.video_text_dataset import VideoTextDataset
from util.typing_utils import TYPE_PATH
VAL_VIDEO_INFO_FILE_PATH = "https://raw.githubusercontent.com/antoine77340/MIL-NCE_HowTo100M/master/csv/" \
"validation_youcook.csv"
# Videos can also be obtained from https://www.rocq.inria.fr/cluster-willow/amiech/Youcook2_val.zip!validation
VAL_VIDEOS_FOLDER = "/datasets/yc2_mil_nce_val/"
class YouCook2(VideoTextDataset):
def __init__(self, video_info_file_path: TYPE_PATH, videos_folder: TYPE_PATH, **kwargs) -> None:
self.video_info = pd.read_csv(cached_path(video_info_file_path), dtype={"task": str})
video_folder = cached_path(videos_folder)
video_paths = (next(iglob(os.path.join(video_folder, row.task, f"{row.video_id}.*")))
for _, row in self.video_info.iterrows())
super().__init__(video_paths=video_paths, **kwargs)
@overrides
def _get_target(self, video_idx: int) -> str:
return self.video_info.loc[video_idx, "text"]
@overrides
def _get_times(self, video_idx: int) -> Tuple[Optional[float], Optional[float]]:
row = self.video_info.loc[video_idx]
return row.start, row.end
class YouCook2DataModule(VideoTextDataModule): # noqa
def __init__(self, val_video_info_file_path: TYPE_PATH = VAL_VIDEO_INFO_FILE_PATH,
val_videos_folder: TYPE_PATH = VAL_VIDEOS_FOLDER, **kwargs) -> None:
super().__init__(**kwargs)
self.val_video_info_file_path = val_video_info_file_path
self.val_videos_folder = val_videos_folder
@overrides
def val_dataloader(self) -> DataLoader:
dataset = YouCook2(video_info_file_path=self.val_video_info_file_path, videos_folder=self.val_videos_folder,
**self._create_dataset_encoder_kwargs(train=False))
return self._create_dataloader(dataset, train=False)
| 2,183 | 41 | 116 | py |
fitclip | fitclip-main/aligner/data/moments_in_time.py | import functools
import os
from typing import Mapping, Tuple
import pandas as pd
from cached_path import cached_path
from overrides import overrides
from torch.utils.data import DataLoader
from aligner.data.video_data_module import VideoClassificationDataModule
from aligner.data.video_dataset import VideoDataset
from util.typing_utils import TYPE_PATH
from util.video_utils import get_sorted_videos_in_folder
CATEGORIES_FILE_PATH = "/datasets/moments-in-time/moments_categories.txt"
VAL_VIDEO_INFO_FILE_PATH = "/datasets/moments-in-time/validationSet.csv"
VAL_VIDEOS_FOLDER = "/datasets/moments-in-time/validation"
class MomentsInTime(VideoDataset):
def __init__(self, categories: Mapping[str, int], video_info_file_path: TYPE_PATH, videos_folder: TYPE_PATH,
**kwargs) -> None:
super().__init__(video_paths=get_sorted_videos_in_folder(cached_path(videos_folder)), **kwargs)
self.categories = categories
self.video_info = pd.read_csv(cached_path(video_info_file_path), names=["path", "category", "agreement",
"disagreement"], index_col="path")
@functools.lru_cache
@overrides
def _get_video_id(self, video_idx: int) -> str:
path = self.video_paths[video_idx]
folder_path, filename = os.path.split(path)
folder_name = os.path.basename(folder_path)
return os.path.join(folder_name, filename)
@overrides
def _get_target(self, video_idx: int) -> Tuple[str, int]:
video_id = self._get_video_id(video_idx)
category = self.video_info.loc[video_id, "category"]
return category, self.categories[category]
class MomentsInTimeDataModule(VideoClassificationDataModule): # noqa
categories = {} # Necessary because it's an abstract property. See https://stackoverflow.com/a/42529760/1165181
def __init__(self, categories_file_path: TYPE_PATH = CATEGORIES_FILE_PATH,
val_video_info_file_path: TYPE_PATH = VAL_VIDEO_INFO_FILE_PATH,
val_videos_folder: TYPE_PATH = VAL_VIDEOS_FOLDER, **kwargs) -> None:
super().__init__(**kwargs)
self.val_video_info_file_path = val_video_info_file_path
self.val_videos_folder = val_videos_folder
with open(cached_path(categories_file_path)) as file:
self.categories = {}
for line in file:
category, id_ = line.rstrip().split(",")
self.categories[category] = int(id_)
@overrides
def val_dataloader(self) -> DataLoader:
dataset = MomentsInTime(categories=self.categories, video_info_file_path=self.val_video_info_file_path,
videos_folder=self.val_videos_folder,
**self._create_dataset_encoder_kwargs(train=False))
return self._create_dataloader(dataset, train=False)
| 2,916 | 43.19697 | 116 | py |
fitclip | fitclip-main/aligner/data/frame_sampler.py | import itertools
from abc import ABC, abstractmethod
from typing import Optional, Sequence
import torch
from overrides import overrides
from util.iter_utils import pairwise
from util.video_utils import resample
class FrameSampler(ABC):
"""Returns the frame indices to seek for the given clip start and end frame indices."""
@abstractmethod
def __call__(self, start_frame: int, end_frame: int, fps: float) -> Sequence[int]:
raise NotImplementedError
class RandomFromUniformIntervalsFrameSampler(FrameSampler):
def __init__(self, max_frames: int) -> None:
super().__init__()
self.max_frames = max_frames
@overrides
def __call__(self, start_frame: int, end_frame: int, fps: float) -> Sequence[int]:
num_frames = min(self.max_frames, end_frame - start_frame + 1)
ticks = torch.linspace(start=start_frame, end=end_frame, steps=num_frames + 1, dtype=torch.int)
return [torch.randint(a, b + 1, size=()) for a, b in pairwise(ticks)]
class UniformFrameSampler(FrameSampler):
def __init__(self, max_frames: int) -> None:
super().__init__()
self.max_frames = max_frames
@overrides
def __call__(self, start_frame: int, end_frame: int, fps: float) -> Sequence[int]:
num_frames = min(self.max_frames, end_frame - start_frame + 1)
ticks = torch.linspace(start=start_frame, end=end_frame, steps=num_frames + 1, dtype=torch.int)
return [torch.round((a + b) / 2).to(torch.int) for a, b in pairwise(ticks)]
class FixedFrameFromUniformIntervalsFrameSampler(FrameSampler):
def __init__(self, max_frames: int, frame_index_from_interval_start: int) -> None:
super().__init__()
self.max_frames = max_frames
self.frame_index_from_interval_start = frame_index_from_interval_start
@overrides
def __call__(self, start_frame: int, end_frame: int, fps: float) -> Sequence[int]:
num_frames = min(self.max_frames, end_frame - start_frame + 1)
ticks = torch.linspace(start=start_frame, end=end_frame + 1, steps=num_frames + 1, dtype=torch.int)
return ticks[:-1] + self.frame_index_from_interval_start
class ConsecutiveFrameSampler(FrameSampler):
def __init__(self, max_frames: int, fps: Optional[int] = None) -> None:
super().__init__()
self.max_frames = max_frames
self.fps = fps
@overrides
def __call__(self, start_frame: int, end_frame: int, fps: float) -> Sequence[int]:
if self.fps:
indices = resample(num_frames=self.max_frames, original_fps=fps, new_fps=self.fps)
else:
indices = range(self.max_frames)
smallest_possible_end = min(end_frame, start_frame + indices[-1])
if isinstance(smallest_possible_end, torch.Tensor):
smallest_possible_end = smallest_possible_end.item() # To avoid a warning in the floor division.
start = start_frame + (end_frame - smallest_possible_end) // 2
return list(itertools.takewhile(lambda i: i <= end_frame, (start + i for i in indices)))
| 3,069 | 38.87013 | 109 | py |
fitclip | fitclip-main/aligner/data/video_reader.py | import logging
from abc import ABC, abstractmethod
from typing import Sequence, Union
import PIL
import decord
import numpy as np
import torch
import torchvision.datasets
import torchvision.transforms.functional
from overrides import overrides
from util.typing_utils import TYPE_PATH
LOGGER = logging.getLogger(__name__)
class VideoReader(ABC):
def __init__(self, path: TYPE_PATH) -> None: # noqa
pass
def __call__(self, indices: Sequence[int]) -> torch.Tensor:
raise NotImplementedError
@abstractmethod
def __len__(self) -> int:
raise NotImplementedError
@abstractmethod
def time_to_indices(self, time: Union[float, Sequence[float]]) -> np.ndarray:
raise NotImplementedError
@abstractmethod
def get_avg_fps(self) -> float:
raise NotImplementedError
@staticmethod
def from_path(path: TYPE_PATH) -> "VideoReader":
return (AccImageVideoReader if torchvision.datasets.folder.is_image_file(path) else DecordVideoReader)(path)
decord.bridge.set_bridge("torch")
class DecordVideoReader(VideoReader):
@overrides
def __init__(self, path: TYPE_PATH) -> None:
super().__init__(path)
# Using `width` and `height` from VideoReader is actually faster because it resizes while decoding, however
# it doesn't preserve the aspect ratio (even if setting only one of the two).
# Using the GPU for decoding may actually be faster, but it isn't trivial how to optimize the whole data loading
# process so to accomplish it.
try:
self.video_reader = decord.VideoReader(path, num_threads=1)
except decord.DECORDError:
LOGGER.error(f"An error occurred when trying to load the video with path {path}.")
self.video_reader = None
@overrides
def __call__(self, indices: Sequence[int]) -> torch.Tensor:
if self.video_reader:
try:
return self.video_reader.get_batch(indices) # noqa
except decord.DECORDError:
# FIXME: change the handle for the path? Or how to get the path
LOGGER.error(f"An error occurred when trying to read the video with path {self.video_reader._handle}"
f" and indices {indices}.")
return torch.zeros(len(indices), 256, 256, 3)
@overrides
def __len__(self) -> int:
return len(self.video_reader) if self.video_reader else 1
@overrides
def time_to_indices(self, time: Union[float, Sequence[float]]) -> np.ndarray:
times = self.video_reader.get_frame_timestamp(range(len(self))).mean(-1) if self.video_reader else np.zeros(1)
indices = np.searchsorted(times, time)
# Use `np.bitwise_or` so it works both with scalars and numpy arrays.
return np.where(np.bitwise_or(indices == 0, times[indices] - time <= time - times[indices - 1]), indices,
indices - 1)
@overrides
def get_avg_fps(self) -> float:
return self.video_reader.get_avg_fps() if self.video_reader else 1
torchvision.set_image_backend("accimage")
class AccImageVideoReader(VideoReader):
@overrides
def __init__(self, path: TYPE_PATH) -> None:
super().__init__(path)
self.path = path
@overrides
def __call__(self, indices: Sequence[int]) -> torch.Tensor:
try:
image = torchvision.datasets.folder.accimage_loader(self.path)
image_tensor = torchvision.transforms.functional.to_tensor(image)
return image_tensor.permute(1, 2, 0).unsqueeze(0)
except PIL.UnidentifiedImageError: # Note `accimage_loader` falls back to PIL.
LOGGER.error(f"An error occurred when trying to read the image with path {self.path}.")
return torch.zeros(len(indices), 256, 256, 3)
@overrides
def __len__(self) -> int:
return 1
@overrides
def time_to_indices(self, time: Union[float, Sequence[float]]) -> np.ndarray:
return np.zeros_like(time, dtype=int)
@overrides
def get_avg_fps(self) -> float:
return 1
| 4,118 | 33.90678 | 120 | py |
fitclip | fitclip-main/aligner/data/data_module_group.py | import bisect
from abc import ABC
from typing import Any, Callable, Iterable, Mapping, Optional, Sequence, Union
import pytorch_lightning as pl
from overrides import overrides
from pytorch_lightning import Trainer
from pytorch_lightning.trainer.states import RunningStage
from pytorch_lightning.utilities.apply_func import apply_to_collection
from pytorch_lightning.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS
from torch.utils.data import BatchSampler, ConcatDataset, DataLoader, Dataset, RandomSampler, SequentialSampler
from torchvision.datasets.samplers import DistributedSampler as DistributedSampler2
from aligner.data.multi_source_sampler import RoundRobinMultiSourceSampler
TYPE_DM_ITERABLE_OR_MAP = Union[Iterable[pl.LightningDataModule], Mapping[str, pl.LightningDataModule]]
def _data_modules_iterable(data_modules: TYPE_DM_ITERABLE_OR_MAP) -> Iterable[pl.LightningDataModule]:
return data_modules.values() if isinstance(data_modules, Mapping) else data_modules
def _data_loader_sequence(data_modules: TYPE_DM_ITERABLE_OR_MAP,
fn: Callable[[pl.LightningDataModule], EVAL_DATALOADERS]) -> Sequence[DataLoader]:
dls = (fn(dm) for dm in _data_modules_iterable(data_modules))
return [dl for dls_dm in dls for dl in ([dls_dm] if isinstance(dls_dm, DataLoader) else dls_dm)]
class _DataModuleGroup(pl.LightningDataModule, ABC):
def __init__(self, data_modules: TYPE_DM_ITERABLE_OR_MAP) -> None:
# Before calling super because it sets `trainer`, which recursively uses these.
self.data_modules = data_modules
self._trainer = None
super().__init__()
# Use it as a property, so we can set it to the data modules when set to self.
@property
def trainer(self) -> Trainer:
return self._trainer
@trainer.setter
def trainer(self, value: Trainer) -> None:
self._trainer = value
# `self.trainer` is set during `super().__init__`, which in turn it's called from `super().__new__`,
# which we can't control and happens before `self.data_modules` even exists.
# So we need to handle the case where the attribute doesn't exist.
for dm in _data_modules_iterable(getattr(self, "data_modules", [])):
dm.trainer = value
@overrides
def prepare_data(self) -> None:
for dm in _data_modules_iterable(self.data_modules):
dm.prepare_data()
@overrides
def setup(self, stage: Optional[str] = None) -> None:
for dm in _data_modules_iterable(self.data_modules):
dm.setup(stage)
class EvalDataModuleGroup(_DataModuleGroup): # noqa
@overrides
def val_dataloader(self) -> EVAL_DATALOADERS:
return _data_loader_sequence(self.data_modules, lambda dm: dm.val_dataloader())
@overrides
def test_dataloader(self) -> EVAL_DATALOADERS:
return _data_loader_sequence(self.data_modules, lambda dm: dm.test_dataloader())
@overrides
def predict_dataloader(self) -> EVAL_DATALOADERS:
return _data_loader_sequence(self.data_modules, lambda dm: dm.predict_dataloader())
class DataModuleStructuredGroup(EvalDataModuleGroup):
@overrides
def train_dataloader(self) -> TRAIN_DATALOADERS:
return apply_to_collection(self.data_modules, pl.LightningDataModule, lambda dm: dm.train_dataloader())
class ConcatDatasetWithDatasetKey(ConcatDataset):
"""A `ConcatDataset` that returns the corresponding dataset key for each item.
It supposes the underlying datasets all return mapping items.
"""
def __init__(self, datasets: Union[Iterable[Dataset], Mapping[str, Dataset]]) -> None:
super().__init__(datasets.values() if isinstance(datasets, Mapping) else datasets)
self.keys = list(datasets.keys()) if isinstance(datasets, Mapping) else range(len(self.datasets))
@overrides(check_signature=False)
def __getitem__(self, i: int) -> Mapping[Any, Any]:
item = super().__getitem__(i)
dataset_idx = bisect.bisect_right(self.cumulative_sizes, i)
return {**item, "dataset": self.keys[dataset_idx]}
def _add_distributed_sampler(data_loaders: EVAL_DATALOADERS, mode: RunningStage) -> EVAL_DATALOADERS:
assert all(apply_to_collection(data_loaders, DataLoader, lambda dl: isinstance(dl.sampler, SequentialSampler)))
return apply_to_collection(
data_loaders, DataLoader,
lambda dl: Trainer._update_dataloader(dl, DistributedSampler2(dl.dataset), mode=mode))
class MixedBatchDataModule(EvalDataModuleGroup):
"""A data module that combines many data modules during training, with the same dataset composition for each batch,
but separately for evaluation."""
def __init__(self, *args, train_sequence_sizes: Union[int, Iterable[int], Mapping[str, int]] = 1, **kwargs) -> None:
super().__init__(*args, **kwargs)
if isinstance(train_sequence_sizes, Mapping):
assert isinstance(self.data_modules, Mapping)
self.train_sequence_sizes = [train_sequence_sizes[k] for k in self.data_modules]
else:
self.train_sequence_sizes = train_sequence_sizes
if isinstance(self.train_sequence_sizes, int):
self.train_batch_size = len(self.data_modules) * self.train_sequence_sizes
else:
self.train_batch_size = sum(self.train_sequence_sizes)
@overrides
def train_dataloader(self) -> TRAIN_DATALOADERS:
data_loaders = apply_to_collection(self.data_modules, pl.LightningDataModule, lambda dm: dm.train_dataloader())
datasets = apply_to_collection(data_loaders, DataLoader, lambda dl: dl.dataset)
dataset = ConcatDatasetWithDatasetKey(datasets)
sub_samplers = [RandomSampler(dataset) for dataset in dataset.datasets] # noqa
sampler = RoundRobinMultiSourceSampler(sub_samplers, sequence_sizes=self.train_sequence_sizes,
mode="max_size_cycle")
data_loader_iterable = data_loaders.values() if isinstance(data_loaders, Mapping) else data_loaders
# We suppose each data module has the same args for the train data loader creation for the values obtained
# here from the first data loader.
first_data_loader = next(iter(data_loader_iterable))
# We have to create the batch sampler manually for the distributed setting.
# This is because we need to control how each batch is formed. If we don't do this, the distributed sampler
# comes before the batch sampling, and the mix composition of the batches won't be the intended one.
#
# For simplicity, we apply it regardless of distributed/non-distributed setup.
batch_sampler = BatchSampler(sampler, batch_size=self.train_batch_size, drop_last=True)
if self.trainer._accelerator_connector.is_distributed:
# We need to manually set the distributed sampler instead of doing it automatically with Pytorch Lightning
# because we're using a custom sampler.
#
# This version of DistributedSampler accounts for having a sampler as input.
#
# BTW, there's a similar one (`DistributedSamplerWrapper`) in
batch_sampler = DistributedSampler2(batch_sampler)
# We need to set the sampler as a `batch_sampler` so it activates the auto-collation in the data loader.
data_loader = DataLoader(dataset, batch_sampler=batch_sampler, num_workers=first_data_loader.num_workers,
collate_fn=first_data_loader.collate_fn, pin_memory=first_data_loader.pin_memory,
timeout=first_data_loader.timeout, worker_init_fn=first_data_loader.worker_init_fn,
multiprocessing_context=first_data_loader.multiprocessing_context,
prefetch_factor=first_data_loader.prefetch_factor,
persistent_workers=first_data_loader.persistent_workers)
if self.trainer._accelerator_connector.is_distributed:
# PL only sets the epoch to the sampler, not to the batch sampler. This is because the distributed
# sampler is typically the former not the latter.
# Note that setting the epoch is necessary for shuffling, so every epoch has different batches.
data_loader.sampler.set_epoch = lambda epoch: batch_sampler.set_epoch(epoch)
return data_loader
def _add_distributed_sampler_maybe(self, data_loaders: EVAL_DATALOADERS, mode: RunningStage) -> EVAL_DATALOADERS:
if self.trainer._accelerator_connector.is_distributed:
return _add_distributed_sampler(data_loaders, mode)
else:
return data_loaders
@overrides
def val_dataloader(self) -> EVAL_DATALOADERS:
return self._add_distributed_sampler_maybe(super().val_dataloader(), RunningStage.VALIDATING)
@overrides
def test_dataloader(self) -> EVAL_DATALOADERS:
return self._add_distributed_sampler_maybe(super().test_dataloader(), RunningStage.TESTING)
@overrides
def predict_dataloader(self) -> EVAL_DATALOADERS:
return self._add_distributed_sampler_maybe(super().predict_dataloader(), RunningStage.PREDICTING)
class TrainAndEvalDataModules(_DataModuleGroup):
def __init__(self, train_data_module: pl.LightningDataModule, eval_data_module: pl.LightningDataModule) -> None:
super().__init__([train_data_module, eval_data_module])
@overrides
def train_dataloader(self) -> TRAIN_DATALOADERS:
return self.data_modules[0].train_dataloader() # noqa
@overrides
def val_dataloader(self) -> EVAL_DATALOADERS:
return self.data_modules[1].val_dataloader() # noqa
@overrides
def test_dataloader(self) -> EVAL_DATALOADERS:
return self.data_modules[1].test_dataloader() # noqa
@overrides
def predict_dataloader(self) -> EVAL_DATALOADERS:
return self.data_modules[1].predict_dataloader() # noqa
| 10,134 | 47.492823 | 120 | py |
fitclip | fitclip-main/aligner/data/multi_source_sampler.py | import itertools
import math
import sys
from typing import Generic, Iterable, Iterator, Literal, TypeVar, Union
from torch.utils.data import Sampler
T_co = TypeVar("T_co", covariant=True)
# We don't use `CycleIterator` from PyTorch Lightning because when used along with `itertools.islice`,
# it always creates a new iterator and wrongly starts from scratch because it's both an iterable and iterator (seems
# like the function calls `iter` internally).
class CycleSampler(Generic[T_co]):
def __init__(self, data_source: Iterable[T_co], length: int = sys.maxsize) -> None:
self.length = length
self.data_source = data_source
def __iter__(self) -> Iterator[T_co]:
if not self.length:
return
counter = 0
while True:
it = iter(self.data_source)
for elem in it:
yield elem
counter += 1
if counter >= self.length:
return
def __len__(self) -> int:
return self.length
class RoundRobinMultiSourceSampler(Sampler[int]):
"""
It supposes the dataset passed along to the `DataLoader` instance is a `ConcatDataset` instance.
Recommended to use with `drop_last=True`.
Some inspiration comes from the module `pytorch_lightning.trainer.supporters`.
"""
def __init__(self, sub_samplers: Iterable[Iterable[int]], sequence_sizes: Union[int, Iterable[int]] = 1,
mode: Literal["min_size", "max_size_cycle"] = "min_size") -> None:
sub_samplers = list(sub_samplers)
sequence_sizes = list(sequence_sizes) if isinstance(sequence_sizes, Iterable) \
else [sequence_sizes] * len(sub_samplers)
assert len(sub_samplers) == len(sequence_sizes)
assert all(len(sampler) for sampler in sub_samplers), ("All sub-samplers need to support `len` and be " # noqa
"non-zero.")
assert all(s > 0 for s in sequence_sizes)
super().__init__(sub_samplers)
self.sub_samplers = sub_samplers
self.sequence_sizes = sequence_sizes
self.mode = mode
for sampler in self.sub_samplers:
sampler._original_len = len(sampler) # noqa
if mode == "max_size_cycle":
max_cycle, max_i = max((math.floor(cycle), - i) for i, cycle in enumerate(self._cycles()))
max_i *= -1 # Trick to get the first sampler index among those of max cycle size.
# Use a large number instead of the default inf because `len` can fail otherwise.
self.sub_samplers = [sampler if i == max_i else CycleSampler(sampler, length=sys.maxsize)
for i, sampler in enumerate(self.sub_samplers)]
for i, sampler in enumerate(self.sub_samplers):
if i != max_i:
sampler._original_len = len(sampler.data_source) # noqa
def _cycles(self) -> Iterator[float]:
for sampler, seq_size in zip(self.sub_samplers, self.sequence_sizes):
yield len(sampler) / seq_size
def __iter__(self) -> Iterator[int]:
iterators = [iter(sampler) for sampler in self.sub_samplers]
while True:
cum_size_in_concat_dataset = 0
for it, size, sampler in zip(iterators, self.sequence_sizes, self.sub_samplers):
i = -1
for i, n in enumerate(itertools.islice(it, size)):
yield cum_size_in_concat_dataset + n
if i < size - 1:
return
cum_size_in_concat_dataset += sampler._original_len # noqa
def __len__(self) -> int:
# Note in "max_size_cycle" mode the longest sampler will actually be the smallest one because the rest are
# repeated infinitely.
min_cycle, min_i = min((math.floor(cycle), i) for i, cycle in enumerate(self._cycles()))
return (sum(seq_size * (min_cycle + int(i < min_i)) for i, seq_size in enumerate(self.sequence_sizes))
+ len(self.sub_samplers[min_i]) % self.sequence_sizes[min_i])
| 4,191 | 38.92381 | 119 | py |
fitclip | fitclip-main/aligner/data/video_data_module.py | import multiprocessing
from abc import ABC, abstractmethod
from typing import Any, Iterable, Mapping, MutableMapping, Optional, Union
import pytorch_lightning as pl
import torch.cuda
from overrides import overrides
from pytorch_lightning.utilities.apply_func import apply_to_collection
from torch.utils.data import DataLoader
from aligner.data.frame_sampler import FrameSampler
from aligner.data.video_dataset import VideoDataset
from aligner.encoder.video_encoder import TYPE_TRANSFORM, VideoEncoder
from aligner.encoder.video_text_encoder import VideoTextEncoder
ENCODER_OR_ENCODER_MAP = Union[VideoEncoder, Mapping[str, VideoEncoder]]
def precision_to_dtype(precision: Union[str, int]) -> torch.dtype:
if precision == 32:
return torch.float
elif precision == 64:
return torch.float64
elif precision in {16, "mixed"}:
return torch.float16
else:
raise ValueError(f"Unsupported precision value: {precision}")
class VideoDataModule(pl.LightningDataModule, ABC):
def __init__(self, encoder: ENCODER_OR_ENCODER_MAP, batch_size: Optional[int] = 1,
eval_batch_size: Optional[int] = 32,
num_workers: int = multiprocessing.cpu_count() // max(torch.cuda.device_count(), 1)) -> None:
super().__init__()
self.encoder = encoder
self.batch_size = batch_size
self.eval_batch_size = eval_batch_size
self.num_workers = num_workers
def _create_transform(self, train: bool) -> Union[TYPE_TRANSFORM, Mapping[str, TYPE_TRANSFORM]]:
float_precision = self.trainer.precision_plugin.precision
dtype = precision_to_dtype(float_precision)
return apply_to_collection(self.encoder, VideoEncoder,
lambda e: (e.get_train_transform if train else e.get_eval_transform)(dtype))
def _create_frame_sampler(self, train: bool) -> Union[FrameSampler, Mapping[str, FrameSampler]]:
return apply_to_collection(self.encoder, VideoEncoder,
lambda e: e.get_train_frame_sampler() if train else e.get_eval_frame_sampler())
def _create_dataset_encoder_kwargs(self, train: bool) -> MutableMapping[str, Any]:
# FIXME: Disable the cache because it seems like a new dataset is created by PL every time.
return {"frame_sampler": self._create_frame_sampler(train=train),
"transform": self._create_transform(train=train),
"pad_batch": apply_to_collection(self.encoder, VideoEncoder, lambda e: e.should_pad_batch),
"cache": False}
def _create_dataloader(self, dataset: VideoDataset, train: bool) -> DataLoader:
# Drop last in train so the NCE loss isn't smaller in the charts for the last batch.
# Also, don't waste one step with fewer memory, where we could have the next one with more memory.
batch_size = self.batch_size if train else self.eval_batch_size
return DataLoader(dataset, batch_size=batch_size, num_workers=self.num_workers, pin_memory=True,
persistent_workers=self.num_workers > 0, collate_fn=getattr(dataset, "collate", None),
shuffle=train, drop_last=train)
@overrides
def predict_dataloader(self) -> DataLoader:
return self.val_dataloader()
class VideoTextDataModule(VideoDataModule, ABC):
def __init__(self, encoder: Union[VideoTextEncoder, Mapping[str, VideoTextEncoder]], **kwargs) -> None:
super().__init__(encoder=encoder, **kwargs)
@overrides
def _create_dataset_encoder_kwargs(self, train: bool) -> MutableMapping[str, Any]:
kwargs = super()._create_dataset_encoder_kwargs(train=train)
kwargs["tokenizer"] = apply_to_collection(self.encoder, VideoEncoder, lambda e: e.get_tokenizer())
return kwargs
class VideoClassificationDataModule(VideoDataModule, ABC):
@property
@abstractmethod
def categories(self) -> Mapping[str, int]:
raise NotImplementedError
@property
def templates(self) -> Optional[Iterable[str]]:
return None
| 4,101 | 44.577778 | 114 | py |
fitclip | fitclip-main/aligner/data/video_text_dataset.py | from abc import ABC
from typing import Mapping, Union
from torch.utils.data.dataloader import default_collate
from aligner.data.tokenizer_collate import MappingTokenizerCollate
from aligner.data.video_dataset import VideoDataset
from aligner.encoder.video_text_encoder import TYPE_TOKENIZER
class VideoTextDataset(VideoDataset, ABC):
def __init__(self, tokenizer: Union[TYPE_TOKENIZER, Mapping[str, TYPE_TOKENIZER]], target_key_name: str = "text",
**kwargs) -> None:
super().__init__(target_key_name=target_key_name, **kwargs)
self.collate = MappingTokenizerCollate(tokenizer, target_key_name,
default_collate_fn=getattr(self, "collate", default_collate))
| 744 | 42.823529 | 117 | py |
fitclip | fitclip-main/aligner/data/hmdb.py | import functools
import glob
import os
from typing import Iterable, Literal, Mapping, Optional, Tuple
from cached_path import cached_path
from overrides import overrides
from torch.utils.data import DataLoader
from aligner.data.ucf import UCF_101_TEMPLATES
from aligner.data.video_data_module import VideoClassificationDataModule
from aligner.data.video_dataset import VideoDataset
from util.typing_utils import TYPE_PATH
TRAIN_TAG = 1
TEST_TAG = 2
class Hmdb(VideoDataset):
def __init__(self, categories: Mapping[str, int], splits_folder: TYPE_PATH, split: Literal[1, 2, 3],
tag: Literal[1, 2], videos_folder: TYPE_PATH, **kwargs) -> None:
self.categories = categories
videos_folder = cached_path(videos_folder)
video_paths = []
for path in glob.iglob(os.path.join(cached_path(splits_folder), f"*_test_split{split}.txt")):
category = os.path.basename(path).rsplit("_", maxsplit=2)[0]
with open(path) as file:
for line in file:
filename, file_tag = line.strip().split(maxsplit=1)
file_tag = int(file_tag)
if file_tag == tag:
video_paths.append(os.path.join(videos_folder, category, filename))
super().__init__(video_paths=video_paths, **kwargs)
@functools.lru_cache
@overrides
def _get_video_id(self, video_idx: int) -> str:
path = self.video_paths[video_idx]
folder_path, filename = os.path.split(path)
folder_name = os.path.basename(folder_path)
return os.path.join(folder_name, filename)
@functools.lru_cache
@overrides
def _get_target(self, video_idx: int) -> Tuple[str, int]:
video_id = self._get_video_id(video_idx)
folder_name = os.path.dirname(video_id)
category = folder_name.replace("_", " ")
return category, self.categories[category]
class HmdbDataModule(VideoClassificationDataModule): # noqa
categories = {} # Necessary because it's an abstract property. See https://stackoverflow.com/a/42529760/1165181
def __init__(self, categories_file_path: TYPE_PATH, splits_folder: TYPE_PATH, split: Literal[1, 2, 3],
videos_folder: TYPE_PATH, **kwargs) -> None:
super().__init__(**kwargs)
self.splits_folder = splits_folder
self.split = split
self.videos_folder = videos_folder
with open(cached_path(categories_file_path)) as file:
self.categories = {line.strip(): i for i, line in enumerate(file)}
@property
@overrides
def templates(self) -> Optional[Iterable[str]]:
return UCF_101_TEMPLATES
@overrides
def train_dataloader(self) -> DataLoader:
dataset = Hmdb(categories=self.categories, splits_folder=self.splits_folder, split=self.split,
tag=TRAIN_TAG, videos_folder=self.videos_folder, # noqa
**self._create_dataset_encoder_kwargs(train=True))
return self._create_dataloader(dataset, train=True)
@overrides
def val_dataloader(self) -> DataLoader:
dataset = Hmdb(categories=self.categories, splits_folder=self.splits_folder, split=self.split,
tag=TEST_TAG, videos_folder=self.videos_folder, # noqa
**self._create_dataset_encoder_kwargs(train=False))
return self._create_dataloader(dataset, train=False)
| 3,441 | 39.023256 | 116 | py |
fitclip | fitclip-main/aligner/data/webvid.py | import os
import pandas as pd
from cached_path import cached_path
from overrides import overrides
from torch.utils.data import DataLoader
from aligner.data.video_data_module import VideoTextDataModule
from aligner.data.video_dataset import VideoDataset
from aligner.data.video_text_dataset import VideoTextDataset
from util.typing_utils import TYPE_PATH
from util.video_utils import get_sorted_videos_in_folder
TRAIN_VIDEO_INFO_FILE_PATH = "/datasets/webvid/results_2M_train.csv"
# noinspection SpellCheckingInspection
TRAIN_VIDEOS_FOLDER = "/datasets/webvid/videos_low_resolution/train/webvid_lowres/"
VAL_VIDEO_INFO_FILE_PATH = "/datasets/webvid/results_2M_val.csv"
# noinspection SpellCheckingInspection
VAL_VIDEOS_FOLDER = "/datasets/webvid/videos_low_resolution/val/val_lowres/"
class WebVid(VideoTextDataset):
def __init__(self, video_info_file_path: TYPE_PATH, videos_folder: TYPE_PATH,
filter_videos_from_info_file: bool = False, **kwargs) -> None:
# noinspection SpellCheckingInspection
self.video_info = pd.read_csv(cached_path(video_info_file_path), index_col="videoid", dtype={"videoid": str})
if filter_videos_from_info_file:
video_paths = (cached_path(os.path.join(videos_folder, f"{video_id}.mp4"))
for video_id, _ in self.video_info.iterrows())
else:
video_paths = get_sorted_videos_in_folder(cached_path(videos_folder))
super().__init__(video_paths=video_paths, **kwargs)
@overrides
def _get_target(self, video_idx: int) -> str:
video_id = self._get_video_id(video_idx)
return self.video_info.loc[video_id, "name"]
class WebVidDataModule(VideoTextDataModule): # noqa
def __init__(self, train_video_info_file_path: TYPE_PATH = TRAIN_VIDEO_INFO_FILE_PATH,
train_videos_folder: TYPE_PATH = TRAIN_VIDEOS_FOLDER, train_filter_videos_from_info_file: bool = False,
val_video_info_file_path: TYPE_PATH = VAL_VIDEO_INFO_FILE_PATH,
val_videos_folder: TYPE_PATH = VAL_VIDEOS_FOLDER, val_filter_videos_from_info_file: bool = False,
**kwargs) -> None:
super().__init__(**kwargs)
self.train_video_info_file_path = train_video_info_file_path
self.train_videos_folder = train_videos_folder
self.train_filter_videos_from_info_file = train_filter_videos_from_info_file
self.val_video_info_file_path = val_video_info_file_path
self.val_videos_folder = val_videos_folder
self.val_filter_videos_from_info_file = val_filter_videos_from_info_file
def _dataset(self, video_info_file_path: TYPE_PATH, videos_folder: TYPE_PATH,
filter_videos_from_info_file: bool, train: bool) -> VideoDataset:
return WebVid(video_info_file_path=video_info_file_path, videos_folder=videos_folder,
filter_videos_from_info_file=filter_videos_from_info_file,
**self._create_dataset_encoder_kwargs(train=train))
@overrides
def train_dataloader(self) -> DataLoader:
dataset = self._dataset(video_info_file_path=self.train_video_info_file_path,
videos_folder=self.train_videos_folder,
filter_videos_from_info_file=self.train_filter_videos_from_info_file, train=True)
return self._create_dataloader(dataset, train=True)
@overrides
def val_dataloader(self) -> DataLoader:
dataset = self._dataset(video_info_file_path=self.val_video_info_file_path,
videos_folder=self.val_videos_folder,
filter_videos_from_info_file=self.val_filter_videos_from_info_file, train=False)
return self._create_dataloader(dataset, train=False)
| 3,814 | 49.197368 | 120 | py |
fitclip | fitclip-main/aligner/data/video_dataset.py | import collections.abc
import functools
import logging
import os
from abc import ABC, abstractmethod
from typing import Any, Generic, Iterable, Mapping, Optional, Sequence, Tuple, TypeVar, Union
import torch
from overrides import overrides
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset
from torch.utils.data.dataloader import default_collate
from aligner.data.frame_sampler import FrameSampler
from aligner.data.video_reader import VideoReader
from aligner.encoder.video_encoder import TYPE_TRANSFORM
from util.typing_utils import TYPE_PATH
T = TypeVar("T")
LOGGER = logging.getLogger(__name__)
def get_filename_without_extension(path: TYPE_PATH) -> str:
return os.path.basename(path).split(".", maxsplit=1)[0]
# TODO: support taking multiple clips per video, where they are chosen according to some strategy.
class VideoDataset(Dataset, Generic[T], ABC):
def __init__(self, video_paths: Iterable[TYPE_PATH], frame_sampler: Union[FrameSampler, Mapping[str, FrameSampler]],
transform: Union[TYPE_TRANSFORM, Mapping[str, TYPE_TRANSFORM]] = lambda x: x,
video_key_name: str = "video", target_key_name: str = "target", pad_batch: bool = True,
cache: bool = False) -> None:
super().__init__()
self.video_paths = video_paths if hasattr(video_paths, "__getitem__") else list(video_paths)
self.target_key_name = target_key_name
self.pad_batch = pad_batch
self.cache = cache
if isinstance(frame_sampler, Mapping):
self.frame_sampler_map = {f"{video_key_name}_{k}": v for k, v in frame_sampler.items()}
else:
self.frame_sampler_map = {video_key_name: frame_sampler}
if isinstance(transform, Mapping):
self.transform_map = {f"{video_key_name}_{k}": v for k, v in transform.items()}
else:
self.transform_map = {video_key_name: transform}
if set(self.frame_sampler_map) != set(self.transform_map):
if video_key_name in self.frame_sampler_map:
self.frame_sampler_map = {k: self.frame_sampler_map[video_key_name] for k in self.transform_map}
elif video_key_name in self.transform_map:
self.transform_map = {k: self.transform_map[video_key_name] for k in self.frame_sampler_map}
else:
raise ValueError("The provided keys for the frame sampler and the transform don't match.")
@abstractmethod
def _get_target(self, video_idx: int) -> T:
"""Returns the target associated with `self.video_paths[video_idx]`."""
raise NotImplementedError
@functools.lru_cache
def _get_video_id(self, video_idx: int) -> str:
return get_filename_without_extension(self.video_paths[video_idx])
def _get_times(self, video_idx: int) -> Tuple[Optional[float], Optional[float]]:
"""Returns the video clip start and end times for the given video index, if any."""
return None, None
@functools.lru_cache(maxsize=None)
def _cached_get_item(self, video_idx: int) -> Mapping[str, Union[torch.Tensor, str, T]]:
path = self.video_paths[video_idx]
video_id = self._get_video_id(video_idx)
video_reader = VideoReader.from_path(path)
start_time, end_time = self._get_times(video_idx)
start_frame_idx = 0 if start_time is None else video_reader.time_to_indices(start_time).item()
end_frame_idx = len(video_reader) - 1 if end_time is None else video_reader.time_to_indices(end_time).item()
idxs_map = {k: frame_sampler(start_frame_idx, end_frame_idx, fps=video_reader.get_avg_fps())
for k, frame_sampler in self.frame_sampler_map.items()}
frames_map = {k: video_reader(idxs) for k, idxs in idxs_map.items()}
return {
self.target_key_name: self._get_target(video_idx),
"video_id": video_id,
**{k: transform(frames_map[k]) for k, transform in self.transform_map.items()},
}
@overrides
def __getitem__(self, video_idx: int) -> Mapping[str, Union[torch.Tensor, str, T]]:
# Note we have to explicitly pass `self` to the wrapped one.
fn = self._cached_get_item if self.cache else functools.partial(self._cached_get_item.__wrapped__, self) # noqa
return fn(video_idx)
def __len__(self) -> int:
return len(self.video_paths)
def _collate(self, batch: Sequence[Any]) -> Any:
if self.pad_batch:
elem = batch[0]
if isinstance(elem, torch.Tensor):
return pad_sequence(batch, batch_first=True) # noqa
elif isinstance(elem, collections.abc.Mapping):
return {k: self._collate([d[k] for d in batch]) if k in self.transform_map
else default_collate([d[k] for d in batch])
for k in elem}
return default_collate(batch)
def collate(self, batch: Sequence[Any]) -> Any:
# Use an auxiliary function instead of doing it directly here because it's recursive, and it may also be
# overridden. so in the recursion the overridden version may be called instead of this one.
return self._collate(batch)
| 5,261 | 43.59322 | 120 | py |
fitclip | fitclip-main/aligner/data/tokenizer_collate.py | import collections.abc
from abc import ABC, abstractmethod
from typing import Any, Callable, Iterable, Mapping, Sequence, Tuple, Union
from overrides import overrides
from pytorch_lightning.utilities.apply_func import apply_to_collection
from torch.utils.data.dataloader import default_collate
from aligner.encoder.video_text_encoder import TYPE_TOKENIZER
# Derived from `default_collate`.
def batch_tokenize_collate(batch: Sequence[Any], tokenizer: TYPE_TOKENIZER) -> Any:
elem = batch[0]
elem_type = type(elem)
if isinstance(elem, (str, bytes)):
return tokenizer(batch)
elif isinstance(elem, collections.abc.Mapping):
return {k: batch_tokenize_collate([d[k] for d in batch], tokenizer) for k in elem}
elif isinstance(elem, tuple) and hasattr(elem, '_fields'): # namedtuple
return elem_type(*(batch_tokenize_collate(samples, tokenizer) for samples in zip(*batch)))
elif isinstance(elem, collections.abc.Sequence):
# check to make sure that the elements in batch have consistent size
it = iter(batch)
elem_size = len(next(it))
if not all(len(elem) == elem_size for elem in it):
raise RuntimeError("Each element in sequence of batch should be of equal size.")
transposed = zip(*batch)
return [batch_tokenize_collate(samples, tokenizer) for samples in transposed]
else:
raise TypeError(f"Batch must contain strings, mappings or sequences; found {elem_type}.")
class TokenizerCollate(ABC):
"""`DataLoader` collate function that batch-tokenizes part of the batch.
The pros of batch-tokenizing during collation are:
1) We can pad at the same time, based on the longest sequence. If we tokenized in the dataset, we wouldn't know
what size to take, and we may take a long one, wasting computing and especially memory. If we batch-tokenize when
iterating through the data_module loader, we are in the main thread and wasting valuable time that could be used for
the GPU.
2) The `tokenizers` library is written in Rust and may have some optimizations for batch-tokenizing (apart from
multi-threading, which is disabled so each data_module loader worker uses one CPU core.)
"""
def __init__(self, tokenizer: Union[TYPE_TOKENIZER, Mapping[str, TYPE_TOKENIZER]], *,
batch_tokenize_collate_fn: Callable[[Sequence[Any], TYPE_TOKENIZER], Any] = batch_tokenize_collate,
default_collate_fn: Callable[[Sequence[Any]], Any] = default_collate) -> None:
super().__init__()
self.tokenizer = tokenizer
self.batch_tokenize_collate_fn = batch_tokenize_collate_fn
self.default_collate_fn = default_collate_fn
@abstractmethod
def _split_uncollated_batch(self, batch: Sequence[Any]) -> Tuple[Sequence[Any], Sequence[Any]]:
"""Splits the batch into a pair where the first element is going to be processed with the default collate
function and each of the elements in the second one are going to be batch-tokenized."""
raise NotImplementedError
@abstractmethod
def _join_collated_batch(self, collated_with_default: Any, collated_with_tokenizer: Any) -> Any:
raise NotImplementedError
def __call__(self, batch: Sequence[Any]) -> Any:
s1, s2 = self._split_uncollated_batch(batch)
batch_tokenized = apply_to_collection(self.tokenizer, Callable, lambda t: self.batch_tokenize_collate_fn(s2, t))
return self._join_collated_batch(self.default_collate_fn(s1), batch_tokenized)
class MappingTokenizerCollate(TokenizerCollate):
def __init__(self, tokenizer: TYPE_TOKENIZER, keys_to_tokenize: Union[str, Iterable[str]], **kwargs) -> None:
super().__init__(tokenizer, **kwargs)
self.keys_to_tokenize = frozenset({keys_to_tokenize} if isinstance(keys_to_tokenize, str) else keys_to_tokenize)
@overrides(check_signature=False)
def _split_uncollated_batch(self,
batch: Sequence[Mapping[str, Any]]) -> Tuple[Sequence[Any], Sequence[Any]]:
return [{k: v for k, v in d.items() if k not in self.keys_to_tokenize} for d in batch], \
[{k: v for k, v in d.items() if k in self.keys_to_tokenize} for d in batch]
@overrides(check_signature=False)
def _join_collated_batch(self, collated_with_default: Any, collated_with_tokenizer: Any) -> Any:
# If the tokenizer is actually composed of many tokenizers, we flatten out the structure.
if isinstance(self.tokenizer, Mapping):
collated_with_tokenizer = {f"{k_child}_{k_parent}": v_child
for k_parent, v_parent in collated_with_tokenizer.items()
for k_child, v_child in v_parent.items()}
return {**collated_with_default, **collated_with_tokenizer}
| 4,865 | 53.066667 | 120 | py |
fitclip | fitclip-main/aligner/data/kinetics.py | import os
from typing import Iterable, Mapping, Optional, Tuple
import pandas as pd
from cached_path import cached_path
from overrides import overrides
from torch.utils.data import DataLoader
from aligner.data.video_data_module import VideoClassificationDataModule
from aligner.data.video_dataset import VideoDataset
from util.typing_utils import TYPE_PATH
from util.video_utils import get_sorted_videos_in_folder
class Kinetics(VideoDataset):
def __init__(self, categories: Mapping[str, int], video_info_file_path: TYPE_PATH, videos_folder: TYPE_PATH,
filter_videos_from_info_file: bool = False, **kwargs) -> None:
self.categories = categories
self.video_info = pd.read_csv(cached_path(video_info_file_path))
self.video_info["video_id"] = \
self.video_info.agg(lambda row: f"{row.youtube_id}_{row.time_start:06}_{row.time_end:06}", axis=1)
self.video_info.set_index("video_id", inplace=True)
if filter_videos_from_info_file:
video_paths = (cached_path(os.path.join(videos_folder, f"{video_id}.mp4"))
for video_id, _ in self.video_info.iterrows())
else:
video_paths = get_sorted_videos_in_folder(cached_path(videos_folder))
super().__init__(video_paths=video_paths, **kwargs)
@overrides
def _get_target(self, video_idx: int) -> Tuple[str, int]:
video_id = self._get_video_id(video_idx)
category = self.video_info.loc[video_id, "label"]
return category, self.categories[category]
class KineticsDataModule(VideoClassificationDataModule): # noqa
categories = {} # Necessary because it's an abstract property. See https://stackoverflow.com/a/42529760/1165181
def __init__(self, categories_file_path: TYPE_PATH, train_video_info_file_path: TYPE_PATH,
train_videos_folder: TYPE_PATH, val_video_info_file_path: TYPE_PATH, val_videos_folder: TYPE_PATH,
test_video_info_file_path: TYPE_PATH, test_videos_folder: TYPE_PATH,
train_filter_videos_from_info_file: bool = False, val_filter_videos_from_info_file: bool = False,
test_filter_videos_from_info_file: bool = False, **kwargs) -> None:
super().__init__(**kwargs)
self.train_video_info_file_path = train_video_info_file_path
self.train_videos_folder = train_videos_folder
self.train_filter_videos_from_info_file = train_filter_videos_from_info_file
self.val_video_info_file_path = val_video_info_file_path
self.val_videos_folder = val_videos_folder
self.val_filter_videos_from_info_file = val_filter_videos_from_info_file
self.test_video_info_file_path = test_video_info_file_path
self.test_videos_folder = test_videos_folder
self.test_filter_videos_from_info_file = test_filter_videos_from_info_file
with open(cached_path(categories_file_path)) as file:
self.categories = {line.strip(): i for i, line in enumerate(file)}
@property
@overrides
def templates(self) -> Optional[Iterable[str]]:
return [ # From https://github.com/openai/CLIP/blob/main/data/prompts.md#kinetics700
"a photo of {}.",
"a photo of a person {}.",
"a photo of a person using {}.",
"a photo of a person doing {}.",
"a photo of a person during {}.",
"a photo of a person performing {}.",
"a photo of a person practicing {}.",
"a video of {}.",
"a video of a person {}.",
"a video of a person using {}.",
"a video of a person doing {}.",
"a video of a person during {}.",
"a video of a person performing {}.",
"a video of a person practicing {}.",
"a example of {}.",
"a example of a person {}.",
"a example of a person using {}.",
"a example of a person doing {}.",
"a example of a person during {}.",
"a example of a person performing {}.",
"a example of a person practicing {}.",
"a demonstration of {}.",
"a demonstration of a person {}.",
"a demonstration of a person using {}.",
"a demonstration of a person doing {}.",
"a demonstration of a person during {}.",
"a demonstration of a person performing {}.",
"a demonstration of a person practicing {}.",
]
def _dataset(self, video_info_file_path: TYPE_PATH, videos_folder: TYPE_PATH,
filter_videos_from_info_file: bool, train: bool) -> VideoDataset:
return Kinetics(self.categories, video_info_file_path=video_info_file_path, videos_folder=videos_folder,
filter_videos_from_info_file=filter_videos_from_info_file,
**self._create_dataset_encoder_kwargs(train=train))
@overrides
def train_dataloader(self) -> DataLoader:
dataset = self._dataset(video_info_file_path=self.train_video_info_file_path,
videos_folder=self.train_videos_folder,
filter_videos_from_info_file=self.train_filter_videos_from_info_file, train=True)
return self._create_dataloader(dataset, train=True)
@overrides
def val_dataloader(self) -> DataLoader:
dataset = self._dataset(video_info_file_path=self.val_video_info_file_path,
videos_folder=self.val_videos_folder,
filter_videos_from_info_file=self.val_filter_videos_from_info_file, train=False)
return self._create_dataloader(dataset, train=False)
@overrides
def test_dataloader(self) -> DataLoader:
dataset = self._dataset(video_info_file_path=self.test_video_info_file_path,
videos_folder=self.test_videos_folder,
filter_videos_from_info_file=self.test_filter_videos_from_info_file, train=False)
return self._create_dataloader(dataset, train=False)
| 6,115 | 49.131148 | 116 | py |
fitclip | fitclip-main/aligner/data/msrvtt.py | import json
import os
import random
from typing import Literal
import pandas as pd
from cached_path import cached_path
from overrides import overrides
from torch.utils.data import DataLoader
from aligner.data.video_data_module import VideoTextDataModule
from aligner.data.video_dataset import VideoDataset
from aligner.data.video_text_dataset import VideoTextDataset
from util.typing_utils import TYPE_PATH
from util.video_utils import get_sorted_videos_in_folder
TYPE_CAPTION_SAMPLING_STRATEGY = Literal["first", "random"]
class MsrVtt(VideoTextDataset):
def __init__(self, videos_folder: TYPE_PATH, file_list_path: TYPE_PATH, annotations_path: TYPE_PATH,
caption_sampling_strategy: TYPE_CAPTION_SAMPLING_STRATEGY, **kwargs) -> None:
with open(cached_path(file_list_path)) as file:
video_ids = {stripped_line for line in file if (stripped_line := line.strip())} # noqa
video_paths = (path
for path in get_sorted_videos_in_folder(cached_path(videos_folder))
if os.path.basename(path).split(".", maxsplit=1)[0] in video_ids)
super().__init__(video_paths=video_paths, **kwargs)
self.caption_sampling_strategy = caption_sampling_strategy
with open(cached_path(annotations_path)) as file:
metadata = json.load(file)
self.video_info = pd.DataFrame(metadata["annotations"])
self.video_info.set_index("image_id", inplace=True)
@overrides
def _get_target(self, video_idx: int) -> str:
video_id = self._get_video_id(video_idx)
captions = self.video_info.loc[video_id, "caption"]
if self.caption_sampling_strategy == "first":
return captions[0]
elif self.caption_sampling_strategy == "random":
return random.choice(captions)
else:
raise ValueError(f"Invalid choice of caption sampling strategy: {self.caption_sampling_strategy}")
class MsrVttDataModule(VideoTextDataModule): # noqa
def __init__(self,
base_path: TYPE_PATH = "https://www.robots.ox.ac.uk/~maxbain/frozen-in-time/data/MSRVTT.zip!MSRVTT/",
train_file_list_rel_path: TYPE_PATH = "train_list_jsfusion.txt", # 1K-A split
val_file_list_rel_path: TYPE_PATH = "val_list_jsfusion.txt", **kwargs) -> None:
super().__init__(**kwargs)
base_path = cached_path(base_path)
self.videos_folder = os.path.join(base_path, "videos/all")
self.annotation_path = os.path.join(base_path, "annotation/MSR_VTT.json")
self.train_file_list_path = os.path.join(base_path, "structured-symlinks", train_file_list_rel_path)
self.val_file_list_path = os.path.join(base_path, "structured-symlinks", val_file_list_rel_path)
def _dataset(self, file_list_path: TYPE_PATH, caption_sampling_strategy: TYPE_CAPTION_SAMPLING_STRATEGY,
train: bool) -> VideoDataset:
return MsrVtt(videos_folder=self.videos_folder, file_list_path=file_list_path,
annotations_path=self.annotation_path, caption_sampling_strategy=caption_sampling_strategy,
**self._create_dataset_encoder_kwargs(train=train))
@overrides
def train_dataloader(self) -> DataLoader:
dataset = self._dataset(file_list_path=self.train_file_list_path, caption_sampling_strategy="random",
train=True)
return self._create_dataloader(dataset, train=True)
@overrides
def val_dataloader(self) -> DataLoader:
dataset = self._dataset(file_list_path=self.val_file_list_path, caption_sampling_strategy="first", train=False)
return self._create_dataloader(dataset, train=False)
| 3,743 | 45.8 | 119 | py |
fitclip | fitclip-main/aligner/data/didemo.py | import json
import os
from collections import defaultdict
from cached_path import CACHE_DIR, _find_latest_cached, cached_path
from overrides import overrides
from torch.utils.data import DataLoader
from aligner.data.video_data_module import VideoTextDataModule
from aligner.data.video_text_dataset import VideoTextDataset
from util.typing_utils import TYPE_PATH
HASH_LIST_PATH = "https://raw.githubusercontent.com/LisaAnne/LocalizingMoments/master/data/yfcc100m_hash.txt"
VAL_ANNOTATION_PATH = "https://raw.githubusercontent.com/LisaAnne/LocalizingMoments/master/data/val_data.json"
VIDEOS_FOLDER = "https://multimedia-commons.s3-us-west-2.amazonaws.com/data/videos/mp4/"
class Didemo(VideoTextDataset):
def __init__(self, videos_folder: TYPE_PATH, hash_list_path: TYPE_PATH, annotations_path: TYPE_PATH,
**kwargs) -> None:
with open(cached_path(annotations_path)) as file:
description_list_by_id = defaultdict(list)
for video in json.load(file):
description_list_by_id[video["video"]].append(video["description"])
self.description_paragraph_by_id = {video_id: " ".join(descriptions)
for video_id, descriptions in description_list_by_id.items()}
with open(cached_path(hash_list_path)) as file:
hash_by_flickr_id = {}
for line in file:
flickr_id, hash_ = line.strip().split("\t")
hash_by_flickr_id[flickr_id] = hash_
self.video_ids_by_path = {}
for video_id in self.description_paragraph_by_id:
flickr_id = video_id.split("_")[1]
hash_ = hash_by_flickr_id[flickr_id]
video_path_or_url = os.path.join(videos_folder, hash_[:3], hash_[3:6], f"{hash_}.mp4")
# We only download some videos and not the whole folder.
# But if it's already cached, we avoid sending a HEAD request. This is an issue if the file is updated,
# but we assume it won't happen.
video_path = _find_latest_cached(video_path_or_url, CACHE_DIR) or cached_path(video_path_or_url)
self.video_ids_by_path[video_path] = video_id
super().__init__(video_paths=self.video_ids_by_path.keys(), **kwargs)
@overrides
def _get_target(self, video_idx: int) -> str:
video_path = self.video_paths[video_idx]
video_id = self.video_ids_by_path[video_path]
return self.description_paragraph_by_id[video_id]
class DidemoDataModule(VideoTextDataModule): # noqa
def __init__(self, videos_folder: TYPE_PATH = VIDEOS_FOLDER, hash_list_path: TYPE_PATH = HASH_LIST_PATH,
val_annotation_path: TYPE_PATH = VAL_ANNOTATION_PATH, **kwargs) -> None:
super().__init__(**kwargs)
self.videos_folder = videos_folder
self.hash_list_path = hash_list_path
self.val_annotation_path = val_annotation_path
@overrides
def val_dataloader(self) -> DataLoader:
dataset = Didemo(videos_folder=self.videos_folder, hash_list_path=self.hash_list_path,
annotations_path=self.val_annotation_path, **self._create_dataset_encoder_kwargs(train=False))
return self._create_dataloader(dataset, train=False)
| 3,269 | 47.088235 | 119 | py |
fitclip | fitclip-main/aligner/data/conceptual_captions.py | import functools
import os
import pandas as pd
from cached_path import cached_path
from overrides import overrides
from torch.utils.data import DataLoader
from torchvision.datasets.folder import IMG_EXTENSIONS
from aligner.data.video_data_module import VideoTextDataModule
from aligner.data.video_dataset import VideoDataset
from aligner.data.video_text_dataset import VideoTextDataset
from util.typing_utils import TYPE_PATH
from util.video_utils import get_videos_in_folder
class ConceptualCaptions(VideoTextDataset):
def __init__(self, video_info_file_path: TYPE_PATH, videos_folder: TYPE_PATH, **kwargs) -> None:
self.video_info = pd.read_csv(cached_path(video_info_file_path), names=["name", "url", "video_id"],
index_col="video_id")
# The version of CC3M used here was downloaded by keeping the original filenames. The issue is that the
# filenames repeat, and only one of the files was kept, but we don't know which one it is from the
# information file with the captions. So as a workaround, we remove the duplicate video IDs:
self.video_info = self.video_info[~self.video_info.index.duplicated(keep=False)]
video_paths = sorted(path
for path in get_videos_in_folder(cached_path(videos_folder), extensions=IMG_EXTENSIONS)
if os.path.basename(path) in self.video_info.index)
super().__init__(video_paths=video_paths, **kwargs)
@functools.lru_cache
@overrides
def _get_video_id(self, video_idx: int) -> str:
return os.path.basename(self.video_paths[video_idx])
@overrides
def _get_target(self, video_idx: int) -> str:
video_id = self._get_video_id(video_idx)
return self.video_info.loc[video_id, "name"]
class ConceptualCaptionsDataModule(VideoTextDataModule): # noqa
def __init__(self, train_video_info_file_path: TYPE_PATH, train_videos_folder: TYPE_PATH,
val_video_info_file_path: TYPE_PATH, val_videos_folder: TYPE_PATH, **kwargs) -> None:
super().__init__(**kwargs)
self.train_video_info_file_path = train_video_info_file_path
self.train_videos_folder = train_videos_folder
self.val_video_info_file_path = val_video_info_file_path
self.val_videos_folder = val_videos_folder
def _dataset(self, video_info_file_path: TYPE_PATH, videos_folder: TYPE_PATH, train: bool) -> VideoDataset:
return ConceptualCaptions(video_info_file_path=video_info_file_path, videos_folder=videos_folder,
**self._create_dataset_encoder_kwargs(train=train))
@overrides
def train_dataloader(self) -> DataLoader:
dataset = self._dataset(video_info_file_path=self.train_video_info_file_path,
videos_folder=self.train_videos_folder, train=True)
return self._create_dataloader(dataset, train=True)
@overrides
def val_dataloader(self) -> DataLoader:
dataset = self._dataset(video_info_file_path=self.val_video_info_file_path,
videos_folder=self.val_videos_folder, train=False)
return self._create_dataloader(dataset, train=False)
| 3,241 | 48.121212 | 116 | py |
fitclip | fitclip-main/aligner/data/ucf.py | import functools
import os
import re
from typing import Iterable, Mapping, Optional, Tuple
from cached_path import cached_path
from overrides import overrides
from torch.utils.data import DataLoader
from aligner.data.video_data_module import VideoClassificationDataModule
from aligner.data.video_dataset import VideoDataset
from util.typing_utils import TYPE_PATH
CATEGORIES_FILE_PATH = ("https://www.crcv.ucf.edu/data/UCF101/UCF101TrainTestSplits-RecognitionTask.zip!"
"ucfTrainTestlist/classInd.txt")
VAL_FILE_LIST_PATH = ("https://www.crcv.ucf.edu/data/UCF101/UCF101TrainTestSplits-RecognitionTask.zip!"
"ucfTrainTestlist/testlist01.txt")
VAL_VIDEOS_FOLDER = "https://www.crcv.ucf.edu/data/UCF101/UCF101.rar!UCF-101"
RE_CAPITALIZED_WORDS = re.compile(r"[a-zA-Z][^A-Z]*")
UCF_101_TEMPLATES = [ # From https://github.com/openai/CLIP/blob/main/data/prompts.md#ucf101
"a photo of a person {}.",
"a video of a person {}.",
"a example of a person {}.",
"a demonstration of a person {}.",
"a photo of the person {}.",
"a video of the person {}.",
"a example of the person {}.",
"a demonstration of the person {}.",
"a photo of a person using {}.",
"a video of a person using {}.",
"a example of a person using {}.",
"a demonstration of a person using {}.",
"a photo of the person using {}.",
"a video of the person using {}.",
"a example of the person using {}.",
"a demonstration of the person using {}.",
"a photo of a person doing {}.",
"a video of a person doing {}.",
"a example of a person doing {}.",
"a demonstration of a person doing {}.",
"a photo of the person doing {}.",
"a video of the person doing {}.",
"a example of the person doing {}.",
"a demonstration of the person doing {}.",
"a photo of a person during {}.",
"a video of a person during {}.",
"a example of a person during {}.",
"a demonstration of a person during {}.",
"a photo of the person during {}.",
"a video of the person during {}.",
"a example of the person during {}.",
"a demonstration of the person during {}.",
"a photo of a person performing {}.",
"a video of a person performing {}.",
"a example of a person performing {}.",
"a demonstration of a person performing {}.",
"a photo of the person performing {}.",
"a video of the person performing {}.",
"a example of the person performing {}.",
"a demonstration of the person performing {}.",
"a photo of a person practicing {}.",
"a video of a person practicing {}.",
"a example of a person practicing {}.",
"a demonstration of a person practicing {}.",
"a photo of the person practicing {}.",
"a video of the person practicing {}.",
"a example of the person practicing {}.",
"a demonstration of the person practicing {}.",
]
def _folder_name_to_category(folder_name: str) -> str:
return " ".join(RE_CAPITALIZED_WORDS.findall(folder_name))
class Ucf(VideoDataset):
def __init__(self, categories: Mapping[str, int], file_list_path: TYPE_PATH, videos_folder: TYPE_PATH,
**kwargs) -> None:
self.categories = categories
videos_folder = cached_path(videos_folder)
with open(cached_path(file_list_path)) as file:
video_ids = (stripped_line for line in file if (stripped_line := line.strip()))
super().__init__(video_paths=(os.path.join(videos_folder, path) for path in video_ids), **kwargs)
@functools.lru_cache
@overrides
def _get_video_id(self, video_idx: int) -> str:
path = self.video_paths[video_idx]
folder_path, filename = os.path.split(path)
folder_name = os.path.basename(folder_path)
return os.path.join(folder_name, filename)
@functools.lru_cache
@overrides
def _get_target(self, video_idx: int) -> Tuple[str, int]:
video_id = self._get_video_id(video_idx)
folder_name = os.path.dirname(video_id)
category = _folder_name_to_category(folder_name)
return category, self.categories[category]
class UcfDataModule(VideoClassificationDataModule): # noqa
categories = {} # Necessary because it's an abstract property. See https://stackoverflow.com/a/42529760/1165181
def __init__(self, categories_file_path: TYPE_PATH = CATEGORIES_FILE_PATH,
val_file_list_path: TYPE_PATH = VAL_FILE_LIST_PATH,
val_videos_folder: TYPE_PATH = VAL_VIDEOS_FOLDER, **kwargs) -> None:
super().__init__(**kwargs)
self.val_file_list_path = val_file_list_path
self.val_videos_folder = val_videos_folder
with open(cached_path(categories_file_path)) as file:
self.categories = {}
for line in file:
id_, folder_name = line.strip().split()
self.categories[_folder_name_to_category(folder_name)] = int(id_) - 1
@property
@overrides
def templates(self) -> Optional[Iterable[str]]:
return UCF_101_TEMPLATES
@overrides
def val_dataloader(self) -> DataLoader:
dataset = Ucf(categories=self.categories, file_list_path=self.val_file_list_path,
videos_folder=self.val_videos_folder, **self._create_dataset_encoder_kwargs(train=False))
return self._create_dataloader(dataset, train=False)
| 5,400 | 40.229008 | 116 | py |
VQ-Diffusion | VQ-Diffusion-main/train.py | # VQ-Diffusion
import argparse
import os
import warnings
import time
import torch
from image_synthesis.modeling.build import build_model
from image_synthesis.data.build import build_dataloader
from image_synthesis.utils.misc import seed_everything, merge_opts_to_config, modify_config_for_debug
from image_synthesis.utils.io import load_yaml_config
from image_synthesis.engine.logger import Logger
from image_synthesis.engine.solver import Solver
from image_synthesis.distributed.launch import launch
# environment variables
NODE_RANK = os.environ['AZ_BATCHAI_TASK_INDEX'] if 'AZ_BATCHAI_TASK_INDEX' in os.environ else 0
NODE_RANK = int(NODE_RANK)
MASTER_ADDR, MASTER_PORT = os.environ['AZ_BATCH_MASTER_NODE'].split(':') if 'AZ_BATCH_MASTER_NODE' in os.environ else ("127.0.0.1", 29500)
MASTER_PORT = int(MASTER_PORT)
DIST_URL = 'tcp://%s:%s' % (MASTER_ADDR, MASTER_PORT)
def get_args():
parser = argparse.ArgumentParser(description='PyTorch Training script')
parser.add_argument('--config_file', type=str, default='configs/vqvae_celeba_attribute_cond.yaml',
help='path of config file')
parser.add_argument('--name', type=str, default='',
help='the name of this experiment, if not provided, set to'
'the name of config file')
parser.add_argument('--output', type=str, default='OUTPUT',
help='directory to save the results')
parser.add_argument('--log_frequency', type=int, default=100,
help='print frequency (default: 100)')
parser.add_argument('--load_path', type=str, default=None,
help='path to model that need to be loaded, '
'used for loading pretrained model')
parser.add_argument('--resume_name', type=str, default=None,
help='resume one experiment with the given name')
parser.add_argument('--auto_resume', action='store_true',
help='automatically resume the training')
# args for ddp
parser.add_argument('--num_node', type=int, default=1,
help='number of nodes for distributed training')
parser.add_argument('--node_rank', type=int, default=NODE_RANK,
help='node rank for distributed training')
parser.add_argument('--dist_url', type=str, default=DIST_URL,
help='url used to set up distributed training')
parser.add_argument('--gpu', type=int, default=None,
help='GPU id to use. If given, only the specific gpu will be'
' used, and ddp will be disabled')
parser.add_argument('--sync_bn', action='store_true',
help='use sync BN layer')
parser.add_argument('--tensorboard', action='store_true',
help='use tensorboard for logging')
parser.add_argument('--timestamp', action='store_true', # default=True,
help='use tensorboard for logging')
# args for random
parser.add_argument('--seed', type=int, default=None,
help='seed for initializing training. ')
parser.add_argument('--cudnn_deterministic', action='store_true',
help='set cudnn.deterministic True')
parser.add_argument('--amp', action='store_true', # default=True,
help='automatic mixture of precesion')
parser.add_argument('--debug', action='store_true', default=False,
help='set as debug mode')
# args for modify config
parser.add_argument(
"opts",
help="Modify config options using the command-line",
default=None,
nargs=argparse.REMAINDER,
)
args = parser.parse_args()
args.cwd = os.path.abspath(os.path.dirname(__file__))
if args.resume_name is not None:
args.name = args.resume_name
args.config_file = os.path.join(args.output, args.resume_name, 'configs', 'config.yaml')
args.auto_resume = True
else:
if args.name == '':
args.name = os.path.basename(args.config_file).replace('.yaml', '')
if args.timestamp:
assert not args.auto_resume, "for timstamp, auto resume is hard to find the save directory"
time_str = time.strftime('%Y-%m-%d-%H-%M')
args.name = time_str + '-' + args.name
# modify args for debugging
if args.debug:
args.name = 'debug'
if args.gpu is None:
args.gpu = 0
args.save_dir = os.path.join(args.output, args.name)
return args
def main():
args = get_args()
if args.seed is not None or args.cudnn_deterministic:
seed_everything(args.seed, args.cudnn_deterministic)
if args.gpu is not None:
warnings.warn('You have chosen a specific GPU. This will completely disable ddp.')
torch.cuda.set_device(args.gpu)
args.ngpus_per_node = 1
args.world_size = 1
else:
if args.num_node == 1:
args.dist_url == "auto"
else:
assert args.num_node > 1
args.ngpus_per_node = torch.cuda.device_count()
args.world_size = args.ngpus_per_node * args.num_node
launch(main_worker, args.ngpus_per_node, args.num_node, args.node_rank, args.dist_url, args=(args,))
def main_worker(local_rank, args):
args.local_rank = local_rank
args.global_rank = args.local_rank + args.node_rank * args.ngpus_per_node
args.distributed = args.world_size > 1
# load config
config = load_yaml_config(args.config_file)
config = merge_opts_to_config(config, args.opts)
if args.debug:
config = modify_config_for_debug(config)
# get logger
logger = Logger(args)
logger.save_config(config)
# get model
model = build_model(config, args)
# print(model)
if args.sync_bn:
model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
# get dataloader
dataloader_info = build_dataloader(config, args)
# get solver
solver = Solver(config=config, args=args, model=model, dataloader=dataloader_info, logger=logger)
# resume
if args.load_path is not None: # only load the model paramters
solver.resume(path=args.load_path,
# load_model=True,
load_optimizer_and_scheduler=False,
load_others=False)
if args.auto_resume:
solver.resume()
# with torch.autograd.set_detect_anomaly(True):
# solver.train()
solver.train()
if __name__ == '__main__':
main()
| 6,809 | 39.058824 | 138 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/distributed/launch.py | import os
import torch
from torch import distributed as dist
from torch import multiprocessing as mp
# import distributed as dist_fn
import image_synthesis.distributed.distributed as dist_fn
def find_free_port():
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("", 0))
port = sock.getsockname()[1]
sock.close()
return port
def launch(fn, n_gpu_per_machine, n_machine=1, machine_rank=0, dist_url=None, args=()):
world_size = n_machine * n_gpu_per_machine
if world_size > 1:
# if "OMP_NUM_THREADS" not in os.environ:
# os.environ["OMP_NUM_THREADS"] = "1"
if dist_url == "auto":
if n_machine != 1:
raise ValueError('dist_url="auto" not supported in multi-machine jobs')
port = find_free_port()
dist_url = f"tcp://127.0.0.1:{port}"
if n_machine > 1 and dist_url.startswith("file://"):
raise ValueError(
"file:// is not a reliable init method in multi-machine jobs. Prefer tcp://"
)
mp.spawn(
distributed_worker,
nprocs=n_gpu_per_machine,
args=(fn, world_size, n_gpu_per_machine, machine_rank, dist_url, args),
daemon=False,
)
else:
local_rank = 0
fn(local_rank, *args)
def distributed_worker(
local_rank, fn, world_size, n_gpu_per_machine, machine_rank, dist_url, args
):
if not torch.cuda.is_available():
raise OSError("CUDA is not available. Please check your environments")
global_rank = machine_rank * n_gpu_per_machine + local_rank
try:
dist.init_process_group(
backend="NCCL",
init_method=dist_url,
world_size=world_size,
rank=global_rank,
)
except Exception:
raise OSError("failed to initialize NCCL groups")
dist_fn.synchronize()
if n_gpu_per_machine > torch.cuda.device_count():
raise ValueError(
f"specified n_gpu_per_machine larger than available device ({torch.cuda.device_count()})"
)
torch.cuda.set_device(local_rank)
if dist_fn.LOCAL_PROCESS_GROUP is not None:
raise ValueError("torch.distributed.LOCAL_PROCESS_GROUP is not None")
n_machine = world_size // n_gpu_per_machine
for i in range(n_machine):
ranks_on_i = list(range(i * n_gpu_per_machine, (i + 1) * n_gpu_per_machine))
pg = dist.new_group(ranks_on_i)
if i == machine_rank:
dist_fn.LOCAL_PROCESS_GROUP = pg
fn(local_rank, *args)
| 2,604 | 26.712766 | 101 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/distributed/distributed.py | import math
import pickle
import torch
from torch import distributed as dist
from torch.utils import data
LOCAL_PROCESS_GROUP = None
def is_primary():
return get_rank() == 0
def get_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank()
def get_local_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
if LOCAL_PROCESS_GROUP is None:
raise ValueError("tensorfn.distributed.LOCAL_PROCESS_GROUP is None")
return dist.get_rank(group=LOCAL_PROCESS_GROUP)
def synchronize():
if not dist.is_available():
return
if not dist.is_initialized():
return
world_size = dist.get_world_size()
if world_size == 1:
return
dist.barrier()
def get_world_size():
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size()
def is_distributed():
raise RuntimeError('Please debug this function!')
return get_world_size() > 1
def all_reduce(tensor, op=dist.ReduceOp.SUM, async_op=False):
world_size = get_world_size()
if world_size == 1:
return tensor
dist.all_reduce(tensor, op=op, async_op=async_op)
return tensor
def all_gather(data):
world_size = get_world_size()
if world_size == 1:
return [data]
buffer = pickle.dumps(data)
storage = torch.ByteStorage.from_buffer(buffer)
tensor = torch.ByteTensor(storage).to("cuda")
local_size = torch.IntTensor([tensor.numel()]).to("cuda")
size_list = [torch.IntTensor([1]).to("cuda") for _ in range(world_size)]
dist.all_gather(size_list, local_size)
size_list = [int(size.item()) for size in size_list]
max_size = max(size_list)
tensor_list = []
for _ in size_list:
tensor_list.append(torch.ByteTensor(size=(max_size,)).to("cuda"))
if local_size != max_size:
padding = torch.ByteTensor(size=(max_size - local_size,)).to("cuda")
tensor = torch.cat((tensor, padding), 0)
dist.all_gather(tensor_list, tensor)
data_list = []
for size, tensor in zip(size_list, tensor_list):
buffer = tensor.cpu().numpy().tobytes()[:size]
data_list.append(pickle.loads(buffer))
return data_list
def reduce_dict(input_dict, average=True):
world_size = get_world_size()
if world_size < 2:
return input_dict
with torch.no_grad():
keys = []
values = []
for k in sorted(input_dict.keys()):
keys.append(k)
values.append(input_dict[k])
values = torch.stack(values, 0)
dist.reduce(values, dst=0)
if dist.get_rank() == 0 and average:
values /= world_size
reduced_dict = {k: v for k, v in zip(keys, values)}
return reduced_dict
def data_sampler(dataset, shuffle, distributed):
if distributed:
return data.distributed.DistributedSampler(dataset, shuffle=shuffle)
if shuffle:
return data.RandomSampler(dataset)
else:
return data.SequentialSampler(dataset)
| 3,169 | 20.418919 | 76 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/engine/lr_scheduler.py | import torch
import math
# from torch.optim import AdamW, Adam
from torch._six import inf
from torch.optim.optimizer import Optimizer
from torch.optim.lr_scheduler import _LRScheduler, CosineAnnealingLR
class ReduceLROnPlateauWithWarmup(object):
"""Reduce learning rate when a metric has stopped improving.
Models often benefit from reducing the learning rate by a factor
of 2-10 once learning stagnates. This scheduler reads a metrics
quantity and if no improvement is seen for a 'patience' number
of epochs, the learning rate is reduced.
Args:
optimizer (Optimizer): Wrapped optimizer.
mode (str): One of `min`, `max`. In `min` mode, lr will
be reduced when the quantity monitored has stopped
decreasing; in `max` mode it will be reduced when the
quantity monitored has stopped increasing. Default: 'min'.
factor (float): Factor by which the learning rate will be
reduced. new_lr = lr * factor. Default: 0.1.
patience (int): Number of epochs with no improvement after
which learning rate will be reduced. For example, if
`patience = 2`, then we will ignore the first 2 epochs
with no improvement, and will only decrease the LR after the
3rd epoch if the loss still hasn't improved then.
Default: 10.
threshold (float): Threshold for measuring the new optimum,
to only focus on significant changes. Default: 1e-4.
threshold_mode (str): One of `rel`, `abs`. In `rel` mode,
dynamic_threshold = best * ( 1 + threshold ) in 'max'
mode or best * ( 1 - threshold ) in `min` mode.
In `abs` mode, dynamic_threshold = best + threshold in
`max` mode or best - threshold in `min` mode. Default: 'rel'.
cooldown (int): Number of epochs to wait before resuming
normal operation after lr has been reduced. Default: 0.
min_lr (float or list): A scalar or a list of scalars. A
lower bound on the learning rate of all param groups
or each group respectively. Default: 0.
eps (float): Minimal decay applied to lr. If the difference
between new and old lr is smaller than eps, the update is
ignored. Default: 1e-8.
verbose (bool): If ``True``, prints a message to stdout for
each update. Default: ``False``.
warmup_lr: float or None, the learning rate to be touched after warmup
warmup: int, the number of steps to warmup
"""
def __init__(self, optimizer, mode='min', factor=0.1, patience=10,
threshold=1e-4, threshold_mode='rel', cooldown=0,
min_lr=0, eps=1e-8, verbose=False, warmup_lr=None,
warmup=0):
if factor >= 1.0:
raise ValueError('Factor should be < 1.0.')
self.factor = factor
# Attach optimizer
if not isinstance(optimizer, Optimizer):
raise TypeError('{} is not an Optimizer'.format(
type(optimizer).__name__))
self.optimizer = optimizer
if isinstance(min_lr, list) or isinstance(min_lr, tuple):
if len(min_lr) != len(optimizer.param_groups):
raise ValueError("expected {} min_lrs, got {}".format(
len(optimizer.param_groups), len(min_lr)))
self.min_lrs = list(min_lr)
else:
self.min_lrs = [min_lr] * len(optimizer.param_groups)
self.patience = patience
self.verbose = verbose
self.cooldown = cooldown
self.cooldown_counter = 0
self.mode = mode
self.threshold = threshold
self.threshold_mode = threshold_mode
self.warmup_lr = warmup_lr
self.warmup = warmup
self.best = None
self.num_bad_epochs = None
self.mode_worse = None # the worse value for the chosen mode
self.eps = eps
self.last_epoch = 0
self._init_is_better(mode=mode, threshold=threshold,
threshold_mode=threshold_mode)
self._reset()
def _prepare_for_warmup(self):
if self.warmup_lr is not None:
if isinstance(self.warmup_lr, (list, tuple)):
if len(self.warmup_lr) != len(self.optimizer.param_groups):
raise ValueError("expected {} warmup_lrs, got {}".format(
len(self.optimizer.param_groups), len(self.warmup_lr)))
self.warmup_lrs = list(self.warmup_lr)
else:
self.warmup_lrs = [self.warmup_lr] * len(self.optimizer.param_groups)
else:
self.warmup_lrs = None
if self.warmup > self.last_epoch:
curr_lrs = [group['lr'] for group in self.optimizer.param_groups]
self.warmup_lr_steps = [max(0, (self.warmup_lrs[i] - curr_lrs[i])/float(self.warmup)) for i in range(len(curr_lrs))]
else:
self.warmup_lr_steps = None
def _reset(self):
"""Resets num_bad_epochs counter and cooldown counter."""
self.best = self.mode_worse
self.cooldown_counter = 0
self.num_bad_epochs = 0
def step(self, metrics):
# convert `metrics` to float, in case it's a zero-dim Tensor
current = float(metrics)
epoch = self.last_epoch + 1
self.last_epoch = epoch
if epoch <= self.warmup:
self._increase_lr(epoch)
else:
if self.is_better(current, self.best):
self.best = current
self.num_bad_epochs = 0
else:
self.num_bad_epochs += 1
if self.in_cooldown:
self.cooldown_counter -= 1
self.num_bad_epochs = 0 # ignore any bad epochs in cooldown
if self.num_bad_epochs > self.patience:
self._reduce_lr(epoch)
self.cooldown_counter = self.cooldown
self.num_bad_epochs = 0
self._last_lr = [group['lr'] for group in self.optimizer.param_groups]
def _reduce_lr(self, epoch):
for i, param_group in enumerate(self.optimizer.param_groups):
old_lr = float(param_group['lr'])
new_lr = max(old_lr * self.factor, self.min_lrs[i])
if old_lr - new_lr > self.eps:
param_group['lr'] = new_lr
if self.verbose:
print('Epoch {:5d}: reducing learning rate'
' of group {} to {:.4e}.'.format(epoch, i, new_lr))
def _increase_lr(self, epoch):
# used for warmup
for i, param_group in enumerate(self.optimizer.param_groups):
old_lr = float(param_group['lr'])
new_lr = max(old_lr + self.warmup_lr_steps[i], self.min_lrs[i])
param_group['lr'] = new_lr
if self.verbose:
print('Epoch {:5d}: increasing learning rate'
' of group {} to {:.4e}.'.format(epoch, i, new_lr))
@property
def in_cooldown(self):
return self.cooldown_counter > 0
def is_better(self, a, best):
if self.mode == 'min' and self.threshold_mode == 'rel':
rel_epsilon = 1. - self.threshold
return a < best * rel_epsilon
elif self.mode == 'min' and self.threshold_mode == 'abs':
return a < best - self.threshold
elif self.mode == 'max' and self.threshold_mode == 'rel':
rel_epsilon = self.threshold + 1.
return a > best * rel_epsilon
else: # mode == 'max' and epsilon_mode == 'abs':
return a > best + self.threshold
def _init_is_better(self, mode, threshold, threshold_mode):
if mode not in {'min', 'max'}:
raise ValueError('mode ' + mode + ' is unknown!')
if threshold_mode not in {'rel', 'abs'}:
raise ValueError('threshold mode ' + threshold_mode + ' is unknown!')
if mode == 'min':
self.mode_worse = inf
else: # mode == 'max':
self.mode_worse = -inf
self.mode = mode
self.threshold = threshold
self.threshold_mode = threshold_mode
self._prepare_for_warmup()
def state_dict(self):
return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}
def load_state_dict(self, state_dict):
self.__dict__.update(state_dict)
self._init_is_better(mode=self.mode, threshold=self.threshold, threshold_mode=self.threshold_mode)
class CosineAnnealingLRWithWarmup(object):
"""
adjust lr:
args:
warmup_lr: float or None, the learning rate to be touched after warmup
warmup: int, the number of steps to warmup
"""
def __init__(self, optimizer, T_max, last_epoch=-1, verbose=False,
min_lr=0, warmup_lr=None, warmup=0):
self.optimizer = optimizer
self.T_max = T_max
self.last_epoch = last_epoch
self.verbose = verbose
self.warmup_lr = warmup_lr
self.warmup = warmup
if isinstance(min_lr, list) or isinstance(min_lr, tuple):
if len(min_lr) != len(optimizer.param_groups):
raise ValueError("expected {} min_lrs, got {}".format(
len(optimizer.param_groups), len(min_lr)))
self.min_lrs = list(min_lr)
else:
self.min_lrs = [min_lr] * len(optimizer.param_groups)
self.max_lrs = [lr for lr in self.min_lrs]
self._prepare_for_warmup()
def step(self):
epoch = self.last_epoch + 1
self.last_epoch = epoch
if epoch <= self.warmup:
self._increase_lr(epoch)
else:
self._reduce_lr(epoch)
def _reduce_lr(self, epoch):
for i, param_group in enumerate(self.optimizer.param_groups):
progress = float(epoch - self.warmup) / float(max(1, self.T_max - self.warmup))
factor = max(0.0, 0.5 * (1.0 + math.cos(math.pi * progress)))
old_lr = float(param_group['lr'])
new_lr = max(self.max_lrs[i] * factor, self.min_lrs[i])
param_group['lr'] = new_lr
if self.verbose:
print('Epoch {:5d}: reducing learning rate'
' of group {} to {:.4e}.'.format(epoch, i, new_lr))
def _increase_lr(self, epoch):
# used for warmup
for i, param_group in enumerate(self.optimizer.param_groups):
old_lr = float(param_group['lr'])
new_lr = old_lr + self.warmup_lr_steps[i]
param_group['lr'] = new_lr
self.max_lrs[i] = max(self.max_lrs[i], new_lr)
if self.verbose:
print('Epoch {:5d}: increasing learning rate'
' of group {} to {:.4e}.'.format(epoch, i, new_lr))
def _prepare_for_warmup(self):
if self.warmup_lr is not None:
if isinstance(self.warmup_lr, (list, tuple)):
if len(self.warmup_lr) != len(self.optimizer.param_groups):
raise ValueError("expected {} warmup_lrs, got {}".format(
len(self.optimizer.param_groups), len(self.warmup_lr)))
self.warmup_lrs = list(self.warmup_lr)
else:
self.warmup_lrs = [self.warmup_lr] * len(self.optimizer.param_groups)
else:
self.warmup_lrs = None
if self.warmup > self.last_epoch:
curr_lrs = [group['lr'] for group in self.optimizer.param_groups]
self.warmup_lr_steps = [max(0, (self.warmup_lrs[i] - curr_lrs[i])/float(self.warmup)) for i in range(len(curr_lrs))]
else:
self.warmup_lr_steps = None
def state_dict(self):
return {key: value for key, value in self.__dict__.items() if key != 'optimizer'}
def load_state_dict(self, state_dict):
self.__dict__.update(state_dict)
self._prepare_for_warmup() | 11,992 | 40.071918 | 128 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/engine/clip_grad_norm.py | from torch.nn.utils import clip_grad_norm_
class ClipGradNorm(object):
def __init__(self,
start_iteration=0,
end_iteration=-1, # if negative, the norm will be always clipped
max_norm=0.5):
self.start_iteration = start_iteration
self.end_iteration = end_iteration
self.max_norm = max_norm
self.last_epoch = -1
def __call__(self, parameters):
self.last_epoch += 1
clip = False
if self.last_epoch >= self.start_iteration:
clip = True
if self.end_iteration > 0 and self.last_epoch < self.end_iteration:
clip = True
if clip:
clip_grad_norm_(parameters, max_norm=self.max_norm)
def state_dict(self):
return {key: value for key, value in self.__dict__.items()}
def load_state_dict(self, state_dict):
self.__dict__.update(state_dict) | 935 | 29.193548 | 81 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/engine/logger.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
import sys
import torch
from image_synthesis.utils.io import write_args, save_config_to_yaml
from image_synthesis.distributed.distributed import is_primary
import torch.utils.tensorboard as tensorboard
# USE_TENSORBOARD = True
# try:
# import tensorboard
# except:
# USE_TENSORBOARD = False
class Logger(object):
def __init__(self, args):
self.args = args
self.save_dir = args.save_dir
self.is_primary = is_primary()
if self.is_primary:
os.makedirs(self.save_dir, exist_ok=True)
# save the args and config
self.config_dir = os.path.join(self.save_dir, 'configs')
os.makedirs(self.config_dir, exist_ok=True)
file_name = os.path.join(self.config_dir, 'args.txt')
write_args(args, file_name)
log_dir = os.path.join(self.save_dir, 'logs')
if not os.path.exists(log_dir):
os.makedirs(log_dir, exist_ok=True)
self.text_writer = open(os.path.join(log_dir, 'log.txt'), 'a') # 'w')
if args.tensorboard:
self.log_info('using tensorboard')
self.tb_writer = torch.utils.tensorboard.SummaryWriter(log_dir=log_dir) # tensorboard.SummaryWriter(log_dir=log_dir)
else:
self.tb_writer = None
def save_config(self, config):
if self.is_primary:
save_config_to_yaml(config, os.path.join(self.config_dir, 'config.yaml'))
def log_info(self, info, check_primary=True):
if self.is_primary or (not check_primary):
print(info)
if self.is_primary:
info = str(info)
time_str = time.strftime('%Y-%m-%d-%H-%M')
info = '{}: {}'.format(time_str, info)
if not info.endswith('\n'):
info += '\n'
self.text_writer.write(info)
self.text_writer.flush()
def add_scalar(self, **kargs):
"""Log a scalar variable."""
if self.is_primary:
if self.tb_writer is not None:
self.tb_writer.add_scalar(**kargs)
def add_scalars(self, **kargs):
"""Log a scalar variable."""
if self.is_primary:
if self.tb_writer is not None:
self.tb_writer.add_scalars(**kargs)
def add_image(self, **kargs):
"""Log a scalar variable."""
if self.is_primary:
if self.tb_writer is not None:
self.tb_writer.add_image(**kargs)
def add_images(self, **kargs):
"""Log a scalar variable."""
if self.is_primary:
if self.tb_writer is not None:
self.tb_writer.add_images(**kargs)
def close(self):
if self.is_primary:
self.text_writer.close()
self.tb_writer.close()
| 3,005 | 32.4 | 132 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/engine/ema.py | import torch
import copy
class EMA(object):
def __init__(self,
model,
decay=0.99,
update_interval=1,
device=torch.device('cpu')):
self.decay = decay
self.update_iterval = update_interval
self.device = device
self.model = model
with torch.no_grad():
if hasattr(model, 'get_ema_model') and callable(model.get_ema_model):
self.ema_model = copy.deepcopy(model.get_ema_model())
self.cur_state_dict = model.get_ema_model().state_dict()
else:
self.ema_model = copy.deepcopy(model)
self.cur_state_dict = model.state_dict()
self.ema_model.to(self.device)
self.cur_state_dict = {k: v.clone().to(self.device) for k, v in self.cur_state_dict.items()}
def update(self, iteration):
if (iteration + 1) % self.update_iterval == 0:
# print('{} Update ema'.format(iteration))
if hasattr(self.model, 'get_ema_model') and callable(self.model.get_ema_model):
cur_state_dict = self.model.get_ema_model().state_dict()
else:
cur_state_dict = self.model.state_dict()
ema_state_dict = self.ema_model.state_dict()
for k in ema_state_dict.keys():
ema_state_dict[k] = ema_state_dict[k] * self.decay + cur_state_dict[k].clone().to(self.device) * (1-self.decay)
self.ema_model.load_state_dict(ema_state_dict)
def state_dict(self):
return self.ema_model.state_dict()
def load_state_dict(self, state_dict, strict=True):
state_dict_ = {k: v.clone().to(self.device) for k, v in state_dict.items()}
self.ema_model.load_state_dict(state_dict_, strict=strict)
def modify_to_inference(self):
# get current model
if hasattr(self.model, 'get_ema_model') and callable(self.model.get_ema_model):
self.cur_state_dict = self.model.get_ema_model().state_dict()
else:
self.cur_state_dict = self.model.state_dict()
self.cur_state_dict = {k: v.clone().to(self.device) for k, v in self.cur_state_dict.items()}
ema_state_dict = self.ema_model.state_dict()
ema_state_dict = {k: v.to(self.model.device) for k, v in ema_state_dict.items()}
if hasattr(self.model, 'get_ema_model') and callable(self.model.get_ema_model):
self.model.get_ema_model().load_state_dict(ema_state_dict)
else:
self.model.load_state_dict(ema_state_dict)
def modify_to_train(self):
self.cur_state_dict = {k: v.clone().to(self.model.device) for k, v in self.cur_state_dict.items()}
if hasattr(self.model, 'get_ema_model') and callable(self.model.get_ema_model):
self.model.get_ema_model().load_state_dict(self.cur_state_dict)
else:
self.model.load_state_dict(self.cur_state_dict)
| 2,968 | 42.028986 | 127 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/utils/misc.py | import importlib
import random
import numpy as np
import torch
import warnings
import os
def seed_everything(seed, cudnn_deterministic=False):
"""
Function that sets seed for pseudo-random number generators in:
pytorch, numpy, python.random
Args:
seed: the integer value seed for global random state
"""
if seed is not None:
print(f"Global seed set to {seed}")
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
if cudnn_deterministic:
torch.backends.cudnn.deterministic = True
warnings.warn('You have chosen to seed training. '
'This will turn on the CUDNN deterministic setting, '
'which can slow down your training considerably! '
'You may see unexpected behavior when restarting '
'from checkpoints.')
def merge_opts_to_config(config, opts):
def modify_dict(c, nl, v):
if len(nl) == 1:
c[nl[0]] = type(c[nl[0]])(v)
else:
# print(nl)
c[nl[0]] = modify_dict(c[nl[0]], nl[1:], v)
return c
if opts is not None and len(opts) > 0:
assert len(opts) % 2 == 0, "each opts should be given by the name and values! The length shall be even number!"
for i in range(len(opts) // 2):
name = opts[2*i]
value = opts[2*i+1]
config = modify_dict(config, name.split('.'), value)
return config
def modify_config_for_debug(config):
config['dataloader']['num_workers'] = 0
config['dataloader']['batch_size'] = 1
return config
def get_model_parameters_info(model):
# for mn, m in model.named_modules():
parameters = {'overall': {'trainable': 0, 'non_trainable': 0, 'total': 0}}
for child_name, child_module in model.named_children():
parameters[child_name] = {'trainable': 0, 'non_trainable': 0}
for pn, p in child_module.named_parameters():
if p.requires_grad:
parameters[child_name]['trainable'] += p.numel()
else:
parameters[child_name]['non_trainable'] += p.numel()
parameters[child_name]['total'] = parameters[child_name]['trainable'] + parameters[child_name]['non_trainable']
parameters['overall']['trainable'] += parameters[child_name]['trainable']
parameters['overall']['non_trainable'] += parameters[child_name]['non_trainable']
parameters['overall']['total'] += parameters[child_name]['total']
# format the numbers
def format_number(num):
K = 2**10
M = 2**20
G = 2**30
if num > G: # K
uint = 'G'
num = round(float(num)/G, 2)
elif num > M:
uint = 'M'
num = round(float(num)/M, 2)
elif num > K:
uint = 'K'
num = round(float(num)/K, 2)
else:
uint = ''
return '{}{}'.format(num, uint)
def format_dict(d):
for k, v in d.items():
if isinstance(v, dict):
format_dict(v)
else:
d[k] = format_number(v)
format_dict(parameters)
return parameters
def format_seconds(seconds):
h = int(seconds // 3600)
m = int(seconds // 60 - h * 60)
s = int(seconds % 60)
d = int(h // 24)
h = h - d * 24
if d == 0:
if h == 0:
if m == 0:
ft = '{:02d}s'.format(s)
else:
ft = '{:02d}m:{:02d}s'.format(m, s)
else:
ft = '{:02d}h:{:02d}m:{:02d}s'.format(h, m, s)
else:
ft = '{:d}d:{:02d}h:{:02d}m:{:02d}s'.format(d, h, m, s)
return ft
def instantiate_from_config(config):
if config is None:
return None
if not "target" in config:
raise KeyError("Expected key `target` to instantiate.")
module, cls = config["target"].rsplit(".", 1)
cls = getattr(importlib.import_module(module, package=None), cls)
return cls(**config.get("params", dict()))
def class_from_string(class_name):
module, cls = class_name.rsplit(".", 1)
cls = getattr(importlib.import_module(module, package=None), cls)
return cls
def get_all_file(dir, end_with='.h5'):
if isinstance(end_with, str):
end_with = [end_with]
filenames = []
for root, dirs, files in os.walk(dir):
for f in files:
for ew in end_with:
if f.endswith(ew):
filenames.append(os.path.join(root, f))
break
return filenames
def get_sub_dirs(dir, abs=True):
sub_dirs = os.listdir(dir)
if abs:
sub_dirs = [os.path.join(dir, s) for s in sub_dirs]
return sub_dirs
def get_model_buffer(model):
state_dict = model.state_dict()
buffers_ = {}
params_ = {n: p for n, p in model.named_parameters()}
for k in state_dict:
if k not in params_:
buffers_[k] = state_dict[k]
return buffers_
| 5,066 | 29.160714 | 119 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/utils/io.py | import sys
import yaml
import torch
import json
def load_yaml_config(path):
with open(path) as f:
config = yaml.full_load(f)
return config
def save_config_to_yaml(config, path):
assert path.endswith('.yaml')
with open(path, 'w') as f:
f.write(yaml.dump(config))
f.close()
def save_dict_to_json(d, path, indent=None):
json.dump(d, open(path, 'w'), indent=indent)
def load_dict_from_json(path):
return json.load(open(path, 'r'))
def write_args(args, path):
args_dict = dict((name, getattr(args, name)) for name in dir(args)if not name.startswith('_'))
with open(path, 'a') as args_file:
args_file.write('==> torch version: {}\n'.format(torch.__version__))
args_file.write('==> cudnn version: {}\n'.format(torch.backends.cudnn.version()))
args_file.write('==> Cmd:\n')
args_file.write(str(sys.argv))
args_file.write('\n==> args:\n')
for k, v in sorted(args_dict.items()):
args_file.write(' %s: %s\n' % (str(k), str(v)))
args_file.close() | 1,067 | 28.666667 | 98 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/data/cub200_dataset.py | from torch.utils.data import Dataset
import numpy as np
import io
from PIL import Image
import os
import json
import random
from image_synthesis.utils.misc import instantiate_from_config
from tqdm import tqdm
import pickle
def load_img(filepath):
img = Image.open(filepath).convert('RGB')
return img
class Cub200Dataset(Dataset):
def __init__(self, data_root, phase = 'train', im_preprocessor_config=None, drop_caption_rate=0.0):
self.transform = instantiate_from_config(im_preprocessor_config)
self.image_folder = os.path.join(data_root, 'images')
self.root = os.path.join(data_root, phase)
pickle_path = os.path.join(self.root, "filenames.pickle")
self.name_list = pickle.load(open(pickle_path, 'rb'), encoding="bytes")
self.num = len(self.name_list)
# load all caption file to dict in memory
self.caption_dict = {}
for index in tqdm(range(self.num)):
name = self.name_list[index]
this_text_path = os.path.join(data_root, 'text', 'text', name+'.txt')
with open(this_text_path, 'r') as f:
caption = f.readlines()
self.caption_dict[name] = caption
print("load caption file done")
self.drop_rate = drop_caption_rate
self.phase = phase
def __len__(self):
return self.num
def __getitem__(self, index):
name = self.name_list[index]
image_path = os.path.join(self.image_folder, name+'.jpg')
image = load_img(image_path)
image = np.array(image).astype(np.uint8)
image = self.transform(image = image)['image']
caption_list = self.caption_dict[name]
caption = random.choice(caption_list).replace('\n', '').lower()
data = {
'image': np.transpose(image.astype(np.float32), (2, 0, 1)),
'text': caption if (self.phase != 'train' or self.drop_rate < 1e-6 or random.random() >= self.drop_rate) else '',
}
return data
| 2,040 | 33.016667 | 129 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/data/mscoco_dataset.py | from torch.utils.data import Dataset
import numpy as np
import io
from PIL import Image
import os
import json
import random
from image_synthesis.utils.misc import instantiate_from_config
def load_img(filepath):
img = Image.open(filepath).convert('RGB')
return img
class CocoDataset(Dataset):
def __init__(self, data_root, phase = 'train', im_preprocessor_config=None, drop_caption_rate=0.0):
self.transform = instantiate_from_config(im_preprocessor_config)
self.root = os.path.join(data_root, phase)
# input_file = os.path.join(data_root, input_file)
caption_file = "captions_"+phase+"2014.json"
caption_file = os.path.join(data_root, "annotations", caption_file)
self.json_file = json.load(open(caption_file, 'r'))
print("length of the dataset is ")
print(len(self.json_file['annotations']))
self.num = len(self.json_file['annotations'])
self.image_prename = "COCO_" + phase + "2014_"
self.folder_path = os.path.join(data_root, phase+'2014', phase+'2014')
self.drop_rate = drop_caption_rate
self.phase = phase
def __len__(self):
return self.num
def __getitem__(self, index):
this_item = self.json_file['annotations'][index]
caption = this_item['caption'].lower()
image_name = str(this_item['image_id']).zfill(12)
image_path = os.path.join(self.folder_path, self.image_prename+image_name+'.jpg')
image = load_img(image_path)
image = np.array(image).astype(np.uint8)
image = self.transform(image = image)['image']
data = {
'image': np.transpose(image.astype(np.float32), (2, 0, 1)),
'text': caption if (self.phase != 'train' or self.drop_rate < 1e-6 or random.random() >= self.drop_rate) else '',
}
return data
| 1,873 | 36.48 | 129 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/data/imagenet_dataset.py | from torch.utils.data import Dataset
import numpy as np
import io
from PIL import Image
import os
import json
import random
from image_synthesis.utils.misc import instantiate_from_config
def load_img(filepath):
img = Image.open(filepath).convert('RGB')
return img
class ImageNetDataset(Dataset):
def __init__(self, data_root, input_file, phase = 'train', im_preprocessor_config=None, drop_caption_rate=0.0):
self.transform = instantiate_from_config(im_preprocessor_config)
self.root = os.path.join(data_root, phase)
input_file = os.path.join(data_root, input_file)
temp_label = json.load(open('image_synthesis/data/imagenet_class_index.json', 'r'))
self.labels = {}
for i in range(1000):
self.labels[temp_label[str(i)][0]] = i
self.A_paths = []
self.A_labels = []
with open(input_file, 'r') as f:
temp_path = f.readlines()
for path in temp_path:
label = self.labels[path.split('/')[0]]
self.A_paths.append(os.path.join(self.root, path.strip()))
self.A_labels.append(label)
self.num = len(self.A_paths)
self.A_size = len(self.A_paths)
self.drop_rate = drop_caption_rate
self.phase = phase
def __len__(self):
return self.num
def __getitem__(self, index):
try:
return self.load_img(index)
except:
return self.__getitem__(random.randint(0, self.__len__()-1))
def load_img(self, index):
A_path = self.A_paths[index % self.A_size]
A = load_img(A_path)
# if self.transform is not None:
A = self.transform(A)['image']
A_label = self.A_labels[index % self.A_size]
data = {
'image': np.transpose(A.astype(np.float32), (2, 0, 1)),
'label': A_label if (self.phase != 'train' or self.drop_rate < 1e-6 or random.random() >= self.drop_rate) else 1000,
}
return data
| 2,016 | 33.775862 | 132 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/data/ffhq_dataset.py | from torch.utils.data import Dataset
import numpy as np
import io
from PIL import Image
import os
import json
import random
from image_synthesis.utils.misc import instantiate_from_config
import torchvision.datasets as datasets
class FFHQDataset(datasets.ImageFolder):
def __init__(self, data_root, im_preprocessor_config):
self.img_preprocessor = instantiate_from_config(im_preprocessor_config)
super(FFHQDataset, self).__init__(root=data_root)
def __getitem__(self, index):
# image_name = self.imgs[index][0].split('/')[-1]
image = super(FFHQDataset, self).__getitem__(index)[0]
image = self.img_preprocessor(image=np.array(image).astype(np.uint8))['image']
data = {
'image': np.transpose(image.astype(np.float32), (2, 0, 1)),
}
return data
| 848 | 31.653846 | 86 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/data/build.py | import torch
# from image_synthesis.data.base_dataset import ConcatDatasetWithIndex as ConcatDataset
from torch.utils.data import ConcatDataset
from image_synthesis.utils.misc import instantiate_from_config
from image_synthesis.distributed.distributed import is_distributed
def build_dataloader(config, args=None, return_dataset=False):
dataset_cfg = config['dataloader']
train_dataset = []
for ds_cfg in dataset_cfg['train_datasets']:
ds_cfg['params']['data_root'] = dataset_cfg.get('data_root', '')
ds = instantiate_from_config(ds_cfg)
train_dataset.append(ds)
if len(train_dataset) > 1:
train_dataset = ConcatDataset(train_dataset)
else:
train_dataset = train_dataset[0]
val_dataset = []
for ds_cfg in dataset_cfg['validation_datasets']:
ds_cfg['params']['data_root'] = dataset_cfg.get('data_root', '')
ds = instantiate_from_config(ds_cfg)
val_dataset.append(ds)
if len(val_dataset) > 1:
val_dataset = ConcatDataset(val_dataset)
else:
val_dataset = val_dataset[0]
if args is not None and args.distributed:
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset, shuffle=True)
val_sampler = torch.utils.data.distributed.DistributedSampler(val_dataset, shuffle=False)
train_iters = len(train_sampler) // dataset_cfg['batch_size']
val_iters = len(val_sampler) // dataset_cfg['batch_size']
else:
train_sampler = None
val_sampler = None
train_iters = len(train_dataset) // dataset_cfg['batch_size']
val_iters = len(val_dataset) // dataset_cfg['batch_size']
# if args is not None and not args.debug:
# num_workers = max(2*dataset_cfg['batch_size'], dataset_cfg['num_workers'])
# num_workers = min(64, num_workers)
# else:
# num_workers = dataset_cfg['num_workers']
num_workers = dataset_cfg['num_workers']
train_loader = torch.utils.data.DataLoader(train_dataset,
batch_size=dataset_cfg['batch_size'],
shuffle=(train_sampler is None),
num_workers=num_workers,
pin_memory=True,
sampler=train_sampler,
drop_last=True,
persistent_workers=True)
val_loader = torch.utils.data.DataLoader(val_dataset,
batch_size=dataset_cfg['batch_size'],
shuffle=False, #(val_sampler is None),
num_workers=num_workers,
pin_memory=True,
sampler=val_sampler,
drop_last=True,
persistent_workers=True)
dataload_info = {
'train_loader': train_loader,
'validation_loader': val_loader,
'train_iterations': train_iters,
'validation_iterations': val_iters
}
if return_dataset:
dataload_info['train_dataset'] = train_dataset
dataload_info['validation_dataset'] = val_dataset
return dataload_info
| 3,454 | 44.460526 | 100 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/data/utils/image_preprocessor.py | import albumentations
import random
import numpy as np
from PIL import Image
import cv2
from io import BytesIO
from torchvision import transforms as trans
class DalleTransformerPreprocessor(object):
def __init__(self,
size=256,
phase='train',
additional_targets=None):
self.size = size
self.phase = phase
# ddc: following dalle to use randomcrop
self.train_preprocessor = albumentations.Compose([albumentations.RandomCrop(height=size, width=size)],
additional_targets=additional_targets)
self.val_preprocessor = albumentations.Compose([albumentations.CenterCrop(height=size, width=size)],
additional_targets=additional_targets)
def __call__(self, image, **kargs):
"""
image: PIL.Image
"""
if isinstance(image, np.ndarray):
image = Image.fromarray(image.astype(np.uint8))
w, h = image.size
s_min = min(h, w)
if self.phase == 'train':
off_h = int(random.uniform(3*(h-s_min)//8, max(3*(h-s_min)//8+1, 5*(h-s_min)//8)))
off_w = int(random.uniform(3*(w-s_min)//8, max(3*(w-s_min)//8+1, 5*(w-s_min)//8)))
# import pdb; pdb.set_trace()
image = image.crop((off_w, off_h, off_w + s_min, off_h + s_min))
# resize image
t_max = min(s_min, round(9/8*self.size))
t_max = max(t_max, self.size)
t = int(random.uniform(self.size, t_max+1))
image = image.resize((t, t))
image = np.array(image).astype(np.uint8)
image = self.train_preprocessor(image=image) #randomcrop (size,size)
else:
if w < h:
w_ = self.size
h_ = int(h * w_/w)
else:
h_ = self.size
w_ = int(w * h_/h)
image = image.resize((w_, h_))
image = np.array(image).astype(np.uint8)
image = self.val_preprocessor(image=image)
return image
class ImageNetTransformerPreprocessor(object):
def __init__(self,
size=256,
phase='train',
additional_targets=None):
self.size = size
self.phase = phase
# ddc: following dalle to use randomcrop
self.train_preprocessor = albumentations.Compose([albumentations.RandomCrop(height=size, width=size)],
additional_targets=additional_targets)
self.val_preprocessor = albumentations.Compose([albumentations.CenterCrop(height=size, width=size)],
additional_targets=additional_targets)
def __call__(self, image, **kargs):
"""
image: PIL.Image
"""
if isinstance(image, np.ndarray):
image = Image.fromarray(image.astype(np.uint8))
w, h = image.size
s_min = min(h, w)
if self.phase == 'train':
if w < h:
w_ = self.size
h_ = int(h * w_/w)
else:
h_ = self.size
w_ = int(w * h_/h)
image = image.resize((w_, h_))
image = np.array(image).astype(np.uint8)
image = self.train_preprocessor(image=image)
else:
if w < h:
w_ = self.size
h_ = int(h * w_/w)
else:
h_ = self.size
w_ = int(w * h_/h)
image = image.resize((w_, h_))
image = np.array(image).astype(np.uint8)
image = self.val_preprocessor(image=image)
return image
| 3,890 | 35.364486 | 140 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/data/utils/comm.py | """
This file contains primitives for multi-gpu communication.
This is useful when doing distributed training.
"""
import pickle
import torch
import torch.distributed as dist
# from diffdist.functional import all_gather as better_all_gather
class Comm(object):
def __init__(self, local_rank=0):
self.local_rank = 0
@property
def world_size(self):
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_world_size()
@property
def rank(self):
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank()
@property
def local_rank(self):
if not dist.is_available():
print("****************** yes1")
return 0
if not dist.is_initialized():
print("****************** yes2")
return 0
print("****************** yes3", self._local_rank)
return self._local_rank
@local_rank.setter
def local_rank(self, value):
if not dist.is_available():
self._local_rank = 0
if not dist.is_initialized():
self._local_rank = 0
self._local_rank = value
@property
def head(self):
return 'Rank[{}/{}]'.format(self.rank, self.world_size)
def is_main_process(self):
return self.rank == 0
def synchronize(self):
"""
Helper function to synchronize (barrier) among all processes when
using distributed training
"""
if self.world_size == 1:
return
dist.barrier()
comm = Comm()
def all_gather(data):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors)
Args:
data: any picklable object
Returns:
list[data]: list of data gathered from each rank
"""
world_size = comm.world_size
if world_size == 1:
return [data]
# serialized to a Tensor
buffer = pickle.dumps(data)
storage = torch.ByteStorage.from_buffer(buffer)
tensor = torch.ByteTensor(storage).to("cuda")
# obtain Tensor size of each rank
local_size = torch.LongTensor([tensor.numel()]).to("cuda")
size_list = [torch.LongTensor([0]).to("cuda") for _ in range(world_size)]
dist.all_gather(size_list, local_size)
size_list = [int(size.item()) for size in size_list]
max_size = max(size_list)
# receiving Tensor from all ranks
# we pad the tensor because torch all_gather does not support
# gathering tensors of different shapes
tensor_list = []
for _ in size_list:
tensor_list.append(torch.ByteTensor(size=(max_size,)).to("cuda"))
if local_size != max_size:
padding = torch.ByteTensor(size=(max_size - local_size,)).to("cuda")
tensor = torch.cat((tensor, padding), dim=0)
dist.all_gather(tensor_list, tensor)
data_list = []
for size, tensor in zip(size_list, tensor_list):
buffer = tensor.cpu().numpy().tobytes()[:size]
data_list.append(pickle.loads(buffer))
return data_list
def reduce_dict(input_dict, average=True):
"""
Args:
input_dict (dict): all the values will be reduced
average (bool): whether to do average or sum
Reduce the values in the dictionary from all processes so that process with rank
0 has the averaged results. Returns a dict with the same fields as
input_dict, after reduction.
"""
world_size = comm.world_size
if world_size < 2:
return input_dict
with torch.no_grad():
names = []
values = []
# sort the keys so that they are consistent across processes
for k in sorted(input_dict.keys()):
names.append(k)
values.append(input_dict[k])
values = torch.stack(values, dim=0)
dist.reduce(values, dst=0)
if dist.get_rank() == 0 and average:
# only main process gets accumulated, so only divide by
# world_size in this case
values /= world_size
reduced_dict = {k: v for k, v in zip(names, values)}
return reduced_dict
def gather_tensors(tensor):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
tensors_gather = [
torch.ones_like(tensor)
for _ in range(comm.world_size)
]
dist.all_gather(tensors_gather, tensor, async_op=False)
# need to do this to restore propagation of the gradients
tensors_gather[comm.rank] = tensor
output = torch.cat(tensors_gather, dim=0)
return output
def gather_tensors_fake(tensor):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
tensors_gather = [
torch.ones_like(tensor)
for _ in range(comm.world_size)
]
dist.all_gather(tensors_gather, tensor, async_op=False)
# need to do this to restore propagation of the gradients
tensors_gather[comm.rank] = tensor
output = torch.cat(tensors_gather, dim=0)
output = torch.cat([output,output.detach()],0)
return output
def gather_nearby_tensors(tensor):
"""
Performs all_gather operation on the provided tensors.
*** Warning ***: torch.distributed.all_gather has no gradient.
"""
step=comm.rank//2
if comm.rank%2==0:
nearby_rank=step*2+1
else:
nearby_rank=step*2
cpu_tensor=tensor
tensors_gather = [
torch.ones_like(cpu_tensor)
for _ in range(comm.world_size)
]
dist.all_gather(tensors_gather, cpu_tensor, async_op=False)
# need to do this to restore propagation of the gradients
tensors_gather=[tensors_gather[nearby_rank].to(tensor.device),tensor]
output = torch.cat(tensors_gather, dim=0)
return output
def gather_tensors_with_gradient(x):
""" collect all tensor from all GPUs
args:
x: shape (mini_batch, ...)
returns:
shape (mini_batch * num_gpu, ...)
"""
x = x.contiguous()
out_list = [torch.zeros_like(x, device=x.device, dtype=x.dtype) for _ in range(comm.world_size)]
out_list = better_all_gather(out_list, x)
return torch.cat(out_list, dim=0)
gather_funcs={
"ALL":gather_tensors,
"NEAR":gather_nearby_tensors,
"GRAD":gather_tensors_with_gradient,
"FAKE":gather_tensors_fake
}
from contextlib import contextmanager
@contextmanager
def torch_distributed_zero_first():
"""
Decorator to make all processes in distributed training wait for each local_master to do something.
"""
local_rank=comm.local_rank
if local_rank not in [-1, 0]:
dist.barrier(device_ids=[local_rank])
yield
if local_rank == 0:
dist.barrier(device_ids=[0])
| 6,860 | 28.701299 | 103 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/data/utils/manage.py | from sys import stdout
import zipfile
import os.path as osp
import lmdb
import logging
from PIL import Image
import pickle
import io
import glob
import os
from pathlib import Path
import time
from threading import Thread
from queue import Queue,Empty
import subprocess
def func_wrapper(func):
def sub_func(queue,kwargs):
while True:
try:
key=queue.get(False)
ret=func(key,**kwargs)
except Empty:
break
return sub_func
class ThreadPool:
def __init__(self,n):
self.threads=[]
self.n=n
def run(self,func,array,**kwargs):
queue=Queue()
for val in array:
queue.put(val)
threads=[]
target=func_wrapper(func)
# hold_thread=subprocess.Popen("exec "+"python /mnt/blob/datasets/holder.py",shell=True,stdout=subprocess.DEVNULL)
time.sleep(1)
print(f"start loading queue {queue.qsize()}")
logging.info(f"start loading queue {queue.qsize()}")
for i in range(self.n):
print(i)
thread=Thread(target=target, args=(queue,kwargs))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
# hold_thread.kill()
home = str(Path.home())
abs_blob_path=os.path.realpath("/mnt/blob/")
CACHE_FOLDER=os.path.join(home,"caching")
USE_CACHE=True
def norm(path):
assert "*" not in path
return os.path.realpath(os.path.abspath(path))
def in_blob(file):
if abs_blob_path in file:
return True
else:
return False
def map_name(file):
path=norm(file)
path=path.lstrip(abs_blob_path+"/")
path=path.replace("/","_")
assert len(path)<250
return path
def preload(db,sync=True,load=True):
if not load:
return
print(f"loading {db.db_path}")
logging.info(f"loading {db.db_path}")
if sync:
db.initialize()
else:
p = Thread(target=db.initialize)
p.start()
def get_keys_from_lmdb(db):
with db.begin(write=False) as txn:
return list(txn.cursor().iternext(values=False))
def decode_img(byteflow):
img=Image.open(io.BytesIO(byteflow)).convert("RGB")
img.load()
return img
def decode_text(byteflow):
return pickle.loads(byteflow)
decode_funcs={
"image": decode_img,
"text": decode_text
}
class MultipleZipManager:
def __init__(self, files: list):
raise
def remove_prefix(text, prefix):
return text[len(prefix):] if text.startswith(prefix) else text
class ZipManager:
def __init__(self, db_path,data_type,prefix=None,load=True) -> None:
self.decode_func=decode_funcs[data_type]
self.db_path=db_path
cache_file=os.path.join(CACHE_FOLDER,map_name(db_path))
if USE_CACHE and os.path.exists(cache_file):
logging.info(f"using local cache {cache_file}")
self.db_path=cache_file
if prefix is None:
self.prefix = None
else:
self.prefix=f"{prefix}_"
self._init=False
preload(self,load=load)
def deinitialze(self):
self.zip_fd.close()
del self.zip_fd
self._init = False
def initialize(self,close=True):
self.zip_fd = zipfile.ZipFile(self.db_path, mode="r")
if not hasattr(self,"_keys"):
self._keys = self.zip_fd.namelist()
if self.prefix is not None:
self._keys=[self.prefix+key for key in self._keys]
self._init = True
if close:
self.deinitialze()
@property
def keys(self):
while not hasattr(self,"_keys"):
time.sleep(0.1)
return self._keys
def get(self, name):
if not self._init:
self.initialize(close=False) # https://discuss.pytorch.org/t/dataloader-stucks/14087/3
byteflow = self.zip_fd.read(name)
return self.decode_func(byteflow)
class DBManager:
def __init__(self, db_path,data_type,prefix=None,load=True) -> None:
self.decode_func=decode_funcs[data_type]
self.db_path=db_path
cache_file=os.path.join(CACHE_FOLDER,map_name(db_path))
if USE_CACHE and os.path.exists(cache_file):
logging.info(f"using local cache {cache_file}")
self.db_path=cache_file
if prefix is None:
self.prefix = None
else:
self.prefix=f"{prefix}_"
self._init=False
preload(self,load=load)
def initialize(self):
self.env = lmdb.open(
self.db_path,
subdir=osp.isdir(self.db_path),
readonly=True,
lock=False,
readahead=False,
meminit=False,
max_readers=10000
)
self._init=True
@property
def keys(self):
while not self._init:
time.sleep(0.1)
if self.prefix is not None:
_keys=[self.prefix+key.decode() for key in get_keys_from_lmdb(self.env)]
else:
_keys=[key.decode() for key in get_keys_from_lmdb(self.env)]
return _keys
def get(self, name):
env = self.env
if self.prefix is not None:
name=remove_prefix(name,self.prefix)
with env.begin(write=False) as txn:
byteflow = txn.get(name.encode())
if byteflow is None:
print("fuck",name)
raise name
return self.decode_func(byteflow)
def __exit__(self, exc_type, exc_value, traceback):
del self.env
import json
class KVReader:
def __init__(self,db_path,data_type,prefix=None,load=True):
assert data_type=="text"
if prefix is None:
self.prefix = None
else:
self.prefix=f"{prefix}_"
self.db_path=db_path
preload(self,load=load)
self._init=False
self._opened=False
def initialize(self):
f=open(self.db_path,"r")
start=int(f.read(1000).strip())
f.seek(start)
self.mp=json.load(f)
if self.prefix is not None:
self.mp={self.prefix+k:v for k,v in self.mp.items()}
f.close()
self._init=True
def open(self):
self.f=open(self.db_path,"r")
self._opened=True
@property
def keys(self):
while not self._init:
time.sleep(0.1)
return list(self.mp.keys())
def get(self,key):
if not self._opened:
self.open()
idx=self.mp[key]
self.f.seek(idx)
text=self.f.readline().strip()
return {"alt_text":text}
def __len__(self):
return len(self.mp)
@staticmethod
def create(file,keys,values):
assert len(keys)==len(values)
f=open(file,"w")
f.write("\n"*1000)
idx=[]
for val in values:
idx.append(f.tell())
f.write(val)
f.write("\n")
start=f.tell()
ki={k:i for i,k in zip(idx,keys)}
json.dump(ki, f, ensure_ascii=False)
f.seek(0)
f.write(str(start))
f.close()
class MultipleLMDBManager:
def __init__(self, files: list, data_type,get_key=False,sync=True):
self.files = files
self._is_init = False
self.data_type=data_type
assert data_type in decode_funcs
self.get_key=get_key
if sync:
print("sync",files)
self.initialize()
else:
print("async",files)
preload(self)
def keep_subset(self,subset):
mapping={key:self.mapping[key] for key in subset}
del self.mapping
self.mapping=mapping
def initialize(self):
self.mapping={}
self.managers={}
new_files=[]
for old_file in self.files:
items=old_file.split("|")
file=items[0]
if len(items)>1:
prefix = items[1]
else:
prefix = None
if not file.startswith("glob-"):
new_files.append(old_file)
else:
desc=remove_prefix(file,"glob-")
sub_files = glob.glob(desc)
sub_files = sorted(sub_files)
if prefix is not None:
sub_files = [f"{f}|{prefix}" for f in sub_files]
new_files.extend(sub_files)
self.files=new_files
for i,old_file in enumerate(self.files):
items=old_file.split("|")
file=items[0]
if len(items)>1:
prefix = items[1]
else:
prefix = None
if file.endswith(".lmdb"):
Manager = DBManager
elif file.endswith(".zip"):
Manager = ZipManager
elif file.endswith(".kv"):
Manager = KVReader
else:
raise
self.managers[i] = Manager(file,self.data_type,prefix=prefix,load=False)
print(file, " done")
ThreadPool(4).run(preload,self.managers.values())
if self.get_key:
self._keys=[]
for index,manager in self.managers.items():
file=manager.db_path
print(f"{file} loading")
logging.info(f"{file} loading")
keys=manager.keys
self._keys.extend(keys)
for key in keys:
self.mapping[key]=index
logging.info(f"{file} loaded, size = {len(keys)}")
print(f"{file} loaded, size = {len(keys)}")
self._is_init=True
@property
def keys(self):
while not self._is_init:
time.sleep(0.1)
return self._keys
def cleanup(self):
del self._keys
del self.mapping
def get(self, name,source=None):
if source is None:
source=self.mapping[name]
data = self.managers[source].get(name)
return data
class MetaDB:
def __init__(self, path, readonly=True, size=None):
self.readonly = readonly
if readonly:
self.db = lmdb.open(
path, readonly=readonly, max_readers=10000, subdir=False, lock=False
)
else:
assert size is not None
self.db = lmdb.open(
path,
readonly=readonly,
max_readers=10000,
subdir=False,
map_size=int(1073741824 * size),
)
def keys(self):
with self.db.begin(write=False) as txn:
keys = list(txn.cursor().iternext(values=False))
return keys
def encode_int(self,num):
return num.to_bytes(4,"big")
def decode_int(self,num_bytes):
return int.from_bytes(num_bytes,"big")
def get(self, key, func=None):
with self.db.begin(write=False) as txn:
val = txn.get(key)
if val is None:
raise
if func:
val = func(val)
return val
| 11,184 | 25.630952 | 122 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/modeling/build.py | from image_synthesis.utils.misc import instantiate_from_config
def build_model(config, args=None):
return instantiate_from_config(config['model'])
| 153 | 24.666667 | 62 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/modeling/modules/clip/simple_tokenizer.py | import gzip
import html
import os
from functools import lru_cache
import ftfy
import regex as re
@lru_cache()
def default_bpe():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
@lru_cache()
def bytes_to_unicode():
"""
Returns list of utf-8 byte and a corresponding list of unicode strings.
The reversible bpe codes work on unicode strings.
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
This is a signficant percentage of your normal, say, 32K bpe vocab.
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
And avoids mapping to whitespace/control characters the bpe code barfs on.
"""
bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
cs = bs[:]
n = 0
for b in range(2**8):
if b not in bs:
bs.append(b)
cs.append(2**8+n)
n += 1
cs = [chr(n) for n in cs]
return dict(zip(bs, cs))
def get_pairs(word):
"""Return set of symbol pairs in a word.
Word is represented as tuple of symbols (symbols being variable-length strings).
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs
def basic_clean(text):
text = ftfy.fix_text(text)
text = html.unescape(html.unescape(text))
return text.strip()
def whitespace_clean(text):
text = re.sub(r'\s+', ' ', text)
text = text.strip()
return text
class SimpleTokenizer(object):
def __init__(self, end_idx=49152, bpe_path: str = default_bpe()):
self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
# merges = merges[1:49152-256-2+1]
# end_idx can be 49152 for CLIP
# or 16384 for DALL-E
merges = merges[1:end_idx-256-2+1]
merges = [tuple(merge.split()) for merge in merges]
vocab = list(bytes_to_unicode().values())
vocab = vocab + [v+'</w>' for v in vocab] # with length 256
for merge in merges:
vocab.append(''.join(merge))
vocab.extend(['<|startoftext|>', '<|endoftext|>']) # with length = end_idx+256
self.encoder = dict(zip(vocab, range(len(vocab))))
self.decoder = {v: k for k, v in self.encoder.items()}
self.bpe_ranks = dict(zip(merges, range(len(merges))))
self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
def bpe(self, token):
if token in self.cache:
return self.cache[token]
word = tuple(token[:-1]) + (token[-1] + '</w>',)
pairs = get_pairs(word)
if not pairs:
return token + '</w>'
while True:
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf')))
if bigram not in self.bpe_ranks:
break
first, second = bigram
new_word = []
i = 0
while i < len(word):
try:
j = word.index(first, i)
new_word.extend(word[i:j])
i = j
except:
new_word.extend(word[i:])
break
if word[i] == first and i < len(word) - 1 and word[i+1] == second:
new_word.append(first+second)
i += 2
else:
new_word.append(word[i])
i += 1
new_word = tuple(new_word)
word = new_word
if len(word) == 1:
break
else:
pairs = get_pairs(word)
word = ' '.join(word)
self.cache[token] = word
return word
def encode(self, text):
bpe_tokens = []
text = whitespace_clean(basic_clean(text)).lower()
for token in re.findall(self.pat, text):
token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
return bpe_tokens
def decode(self, tokens):
text = ''.join([self.decoder[token] for token in tokens])
text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
return text
| 4,806 | 34.087591 | 144 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/modeling/modules/clip/clip.py | import hashlib
import os
import urllib
import warnings
from typing import Union, List
import torch
from PIL import Image
from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
from tqdm import tqdm
from .model import build_model
from .simple_tokenizer import SimpleTokenizer as _Tokenizer
__all__ = ["available_models", "load", "tokenize"]
_tokenizer = _Tokenizer()
_MODELS = {
"RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt",
"ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt",
}
def _download(url: str, root: str = os.path.expanduser("~/.cache/image-synthesis")):
os.makedirs(root, exist_ok=True)
filename = os.path.basename(url)
expected_sha256 = url.split("/")[-2]
# download_target = os.path.join(root, filename)
download_target = "OUTPUT/pretrained_model/ViT-B-32.pt"
if os.path.exists(download_target) and not os.path.isfile(download_target):
raise RuntimeError(f"{download_target} exists and is not a regular file")
if os.path.isfile(download_target):
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256:
return download_target
else:
warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file")
with urllib.request.urlopen(url) as source, open(download_target, "wb") as output:
with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop:
while True:
buffer = source.read(8192)
if not buffer:
break
output.write(buffer)
loop.update(len(buffer))
if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256:
raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match")
return download_target
def _transform(n_px):
return Compose([
Resize(n_px, interpolation=Image.BICUBIC),
CenterCrop(n_px),
lambda image: image.convert("RGB"),
ToTensor(),
Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)),
])
def available_models() -> List[str]:
"""Returns the names of available CLIP models"""
return list(_MODELS.keys())
def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit=True):
"""Load a CLIP model
Parameters
----------
name : str
A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
device : Union[str, torch.device]
The device to put the loaded model
jit : bool
Whether to load the optimized JIT model (default) or more hackable non-JIT model.
Returns
-------
model : torch.nn.Module
The CLIP model
preprocess : Callable[[PIL.Image], torch.Tensor]
A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
"""
if name in _MODELS:
# model_path = _download(_MODELS[name])
model_path = "OUTPUT/pretrained_model/ViT-B-32.pt"
elif os.path.isfile(name):
model_path = name
else:
raise RuntimeError(f"Model {name} not found; available models = {available_models()}")
try:
# loading JIT archive
model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval()
state_dict = None
except RuntimeError:
# loading saved state dict
if jit:
warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead")
jit = False
state_dict = torch.load(model_path, map_location="cpu")
if not jit:
model = build_model(state_dict or model.state_dict()).to(device)
if str(device) == "cpu":
model.float()
return model, _transform(model.visual.input_resolution)
# patch the device names
device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[])
device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1]
def patch_device(module):
graphs = [module.graph] if hasattr(module, "graph") else []
if hasattr(module, "forward1"):
graphs.append(module.forward1.graph)
for graph in graphs:
for node in graph.findAllNodes("prim::Constant"):
if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"):
node.copyAttributes(device_node)
model.apply(patch_device)
patch_device(model.encode_image)
patch_device(model.encode_text)
# patch dtype to float32 on CPU
if str(device) == "cpu":
float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[])
float_input = list(float_holder.graph.findNode("aten::to").inputs())[1]
float_node = float_input.node()
def patch_float(module):
graphs = [module.graph] if hasattr(module, "graph") else []
if hasattr(module, "forward1"):
graphs.append(module.forward1.graph)
for graph in graphs:
for node in graph.findAllNodes("aten::to"):
inputs = list(node.inputs())
for i in [1, 2]: # dtype can be the second or third argument to aten::to()
if inputs[i].node()["value"] == 5:
inputs[i].node().copyAttributes(float_node)
model.apply(patch_float)
patch_float(model.encode_image)
patch_float(model.encode_text)
model.float()
return model, _transform(model.input_resolution.item())
def tokenize(texts: Union[str, List[str]], context_length: int = 77,
add_start_and_end: bool = True, with_mask: bool = True,
pad_value: int = 0, tokenizer=None, just_token: bool = False) -> torch.LongTensor:
"""
Returns the tokenized representation of given input string(s)
Parameters
----------
texts : Union[str, List[str]]
An input string or a list of input strings to tokenize
context_length : int
The context length to use; all CLIP models use 77 as the context length
just_token: bool
If True, just return the token of text
Returns
-------
A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length]
"""
if isinstance(texts, str):
texts = [texts]
if tokenizer is None:
tokenizer = _tokenizer
sot_token = [tokenizer.encoder["<|startoftext|>"]] if add_start_and_end else []
eot_token = [tokenizer.encoder["<|endoftext|>"]] if add_start_and_end else []
all_tokens = [sot_token + tokenizer.encode(text.lower()) + eot_token for text in texts]
if just_token:
return all_tokens
result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) + pad_value
if with_mask:
mask = torch.zeros(len(all_tokens), context_length, dtype=torch.bool)
for i, tokens in enumerate(all_tokens):
if len(tokens) > context_length:
temp = tokens[-1]
tokens = tokens[:context_length]
tokens[-1] = temp
assert len(tokens) == context_length
# raise RuntimeError("Input text {} is too long for context length {}".format(texts[i], context_length))
result[i, :len(tokens)] = torch.tensor(tokens)
if with_mask:
mask[i, :len(tokens)] = True
results = {
'token': result,
}
if with_mask:
results['mask'] = mask
return results
| 7,962 | 35.360731 | 142 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/modeling/modules/clip/model.py | from collections import OrderedDict
from typing import Tuple, Union
import torch
import torch.nn.functional as F
from torch import nn
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1):
super().__init__()
# all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1
self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity()
self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False)
self.bn3 = nn.BatchNorm2d(planes * self.expansion)
self.relu = nn.ReLU(inplace=True)
self.downsample = None
self.stride = stride
if stride > 1 or inplanes != planes * Bottleneck.expansion:
# downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1
self.downsample = nn.Sequential(OrderedDict([
("-1", nn.AvgPool2d(stride)),
("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)),
("1", nn.BatchNorm2d(planes * self.expansion))
]))
def forward(self, x: torch.Tensor):
identity = x
out = self.relu(self.bn1(self.conv1(x)))
out = self.relu(self.bn2(self.conv2(out)))
out = self.avgpool(out)
out = self.bn3(self.conv3(out))
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class AttentionPool2d(nn.Module):
def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
super().__init__()
self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5)
self.k_proj = nn.Linear(embed_dim, embed_dim)
self.q_proj = nn.Linear(embed_dim, embed_dim)
self.v_proj = nn.Linear(embed_dim, embed_dim)
self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
self.num_heads = num_heads
def forward(self, x):
x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC
x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC
x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC
x, _ = F.multi_head_attention_forward(
query=x, key=x, value=x,
embed_dim_to_check=x.shape[-1],
num_heads=self.num_heads,
q_proj_weight=self.q_proj.weight,
k_proj_weight=self.k_proj.weight,
v_proj_weight=self.v_proj.weight,
in_proj_weight=None,
in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
bias_k=None,
bias_v=None,
add_zero_attn=False,
dropout_p=0,
out_proj_weight=self.c_proj.weight,
out_proj_bias=self.c_proj.bias,
use_separate_proj_weight=True,
training=self.training,
need_weights=False
)
return x[0]
class ModifiedResNet(nn.Module):
"""
A ResNet class that is similar to torchvision's but contains the following changes:
- There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool.
- Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1
- The final pooling layer is a QKV attention instead of an average pool
"""
def __init__(self, layers, output_dim, heads, input_resolution=224, width=64):
super().__init__()
self.output_dim = output_dim
self.input_resolution = input_resolution
# the 3-layer stem
self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(width // 2)
self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(width // 2)
self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False)
self.bn3 = nn.BatchNorm2d(width)
self.avgpool = nn.AvgPool2d(2)
self.relu = nn.ReLU(inplace=True)
# residual layers
self._inplanes = width # this is a *mutable* variable used during construction
self.layer1 = self._make_layer(width, layers[0])
self.layer2 = self._make_layer(width * 2, layers[1], stride=2)
self.layer3 = self._make_layer(width * 4, layers[2], stride=2)
self.layer4 = self._make_layer(width * 8, layers[3], stride=2)
embed_dim = width * 32 # the ResNet feature dimension
self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim)
def _make_layer(self, planes, blocks, stride=1):
layers = [Bottleneck(self._inplanes, planes, stride)]
self._inplanes = planes * Bottleneck.expansion
for _ in range(1, blocks):
layers.append(Bottleneck(self._inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
def stem(x):
for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]:
x = self.relu(bn(conv(x)))
x = self.avgpool(x)
return x
x = x.type(self.conv1.weight.dtype)
x = stem(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.attnpool(x)
return x
class LayerNorm(nn.LayerNorm):
"""Subclass torch's LayerNorm to handle fp16."""
def forward(self, x: torch.Tensor):
orig_type = x.dtype
ret = super().forward(x.type(torch.float32))
return ret.type(orig_type)
class QuickGELU(nn.Module):
def forward(self, x: torch.Tensor):
return x * torch.sigmoid(1.702 * x)
class ResidualAttentionBlock(nn.Module):
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
super().__init__()
self.attn = nn.MultiheadAttention(d_model, n_head)
self.ln_1 = LayerNorm(d_model)
self.mlp = nn.Sequential(OrderedDict([
("c_fc", nn.Linear(d_model, d_model * 4)),
("gelu", QuickGELU()),
("c_proj", nn.Linear(d_model * 4, d_model))
]))
self.ln_2 = LayerNorm(d_model)
self.attn_mask = attn_mask
def attention(self, x: torch.Tensor):
self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
def forward(self, x: torch.Tensor):
x = x + self.attention(self.ln_1(x))
x = x + self.mlp(self.ln_2(x))
return x
class Transformer(nn.Module):
def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None):
super().__init__()
self.width = width
self.layers = layers
self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)])
def forward(self, x: torch.Tensor):
return self.resblocks(x)
class VisualTransformer(nn.Module):
def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int):
super().__init__()
self.input_resolution = input_resolution
self.output_dim = output_dim
self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False)
scale = width ** -0.5
self.class_embedding = nn.Parameter(scale * torch.randn(width))
self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width))
self.ln_pre = LayerNorm(width)
self.transformer = Transformer(width, layers, heads)
self.ln_post = LayerNorm(width)
self.proj = nn.Parameter(scale * torch.randn(width, output_dim))
def forward(self, x: torch.Tensor):
x = self.conv1(x) # shape = [*, width, grid, grid]
x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2]
x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width]
x = torch.cat([self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), x], dim=1) # shape = [*, grid ** 2 + 1, width]
x = x + self.positional_embedding.to(x.dtype)
x = self.ln_pre(x)
x = x.permute(1, 0, 2) # NLD -> LND
x = self.transformer(x)
x = x.permute(1, 0, 2) # LND -> NLD
x = self.ln_post(x[:, 0, :])
if self.proj is not None:
x = x @ self.proj
return x
class CLIP(nn.Module):
def __init__(self,
embed_dim: int,
# vision
image_resolution: int,
vision_layers: Union[Tuple[int, int, int, int], int],
vision_width: int,
vision_patch_size: int,
# text
context_length: int,
vocab_size: int,
transformer_width: int,
transformer_heads: int,
transformer_layers: int
):
super().__init__()
self.context_length = context_length
if isinstance(vision_layers, (tuple, list)):
vision_heads = vision_width * 32 // 64
self.visual = ModifiedResNet(
layers=vision_layers,
output_dim=embed_dim,
heads=vision_heads,
input_resolution=image_resolution,
width=vision_width
)
else:
vision_heads = vision_width // 64
self.visual = VisualTransformer(
input_resolution=image_resolution,
patch_size=vision_patch_size,
width=vision_width,
layers=vision_layers,
heads=vision_heads,
output_dim=embed_dim
)
self.transformer = Transformer(
width=transformer_width,
layers=transformer_layers,
heads=transformer_heads,
attn_mask=self.build_attention_mask()
)
self.vocab_size = vocab_size
self.token_embedding = nn.Embedding(vocab_size, transformer_width)
self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width))
self.ln_final = LayerNorm(transformer_width)
self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim))
self.logit_scale = nn.Parameter(torch.ones([]))
self.initialize_parameters()
def initialize_parameters(self):
nn.init.normal_(self.token_embedding.weight, std=0.02)
nn.init.normal_(self.positional_embedding, std=0.01)
if isinstance(self.visual, ModifiedResNet):
if self.visual.attnpool is not None:
std = self.visual.attnpool.c_proj.in_features ** -0.5
nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std)
nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std)
nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std)
nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std)
for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]:
for name, param in resnet_block.named_parameters():
if name.endswith("bn3.weight"):
nn.init.zeros_(param)
proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5)
attn_std = self.transformer.width ** -0.5
fc_std = (2 * self.transformer.width) ** -0.5
for block in self.transformer.resblocks:
nn.init.normal_(block.attn.in_proj_weight, std=attn_std)
nn.init.normal_(block.attn.out_proj.weight, std=proj_std)
nn.init.normal_(block.mlp.c_fc.weight, std=fc_std)
nn.init.normal_(block.mlp.c_proj.weight, std=proj_std)
if self.text_projection is not None:
nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5)
def build_attention_mask(self):
# lazily create causal attention mask, with full attention between the vision tokens
# pytorch uses additive attention mask; fill with -inf
mask = torch.empty(self.context_length, self.context_length)
mask.fill_(float("-inf"))
mask.triu_(1) # zero out the lower diagonal
return mask
@property
def dtype(self):
if hasattr(self, 'visual'):
return self.visual.conv1.weight.dtype
else:
return self.transformer.resblocks[0].attn.in_proj_weight.dtype
def encode_image(self, image):
return self.visual(image.type(self.dtype))
def encode_text(self, text):
x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model]
x = x + self.positional_embedding.type(self.dtype)
x = x.permute(1, 0, 2) # NLD -> LND
x = self.transformer(x)
x = x.permute(1, 0, 2) # LND -> NLD
x = self.ln_final(x).type(self.dtype)
# x.shape = [batch_size, n_ctx, transformer.width]
# take features from the eot embedding (eot_token is the highest number in each sequence)
x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection
return x
def forward(self, image, text):
image_features = self.encode_image(image)
text_features = self.encode_text(text)
# normalized features
image_features = image_features / image_features.norm(dim=-1, keepdim=True)
text_features = text_features / text_features.norm(dim=-1, keepdim=True)
# cosine similarity as logits
logit_scale = self.logit_scale.exp()
logits_per_image = logit_scale * image_features @ text_features.t()
logits_per_text = logit_scale * text_features @ image_features.t()
# shape = [global_batch_size, global_batch_size]
return logits_per_image, logits_per_text
def convert_weights(model: nn.Module):
"""Convert applicable model parameters to fp16"""
def _convert_weights_to_fp16(l):
if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)):
l.weight.data = l.weight.data.half()
if l.bias is not None:
l.bias.data = l.bias.data.half()
if isinstance(l, nn.MultiheadAttention):
for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]:
tensor = getattr(l, attr)
if tensor is not None:
tensor.data = tensor.data.half()
for name in ["text_projection", "proj"]:
if hasattr(l, name):
attr = getattr(l, name)
if attr is not None:
attr.data = attr.data.half()
model.apply(_convert_weights_to_fp16)
def build_model(state_dict: dict):
vit = "visual.proj" in state_dict
if vit:
vision_width = state_dict["visual.conv1.weight"].shape[0]
vision_layers = len([k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")])
vision_patch_size = state_dict["visual.conv1.weight"].shape[-1]
grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5)
image_resolution = vision_patch_size * grid_size
else:
counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in [1, 2, 3, 4]]
vision_layers = tuple(counts)
vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0]
output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5)
vision_patch_size = None
assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0]
image_resolution = output_width * 32
embed_dim = state_dict["text_projection"].shape[1]
context_length = state_dict["positional_embedding"].shape[0]
vocab_size = state_dict["token_embedding.weight"].shape[0]
transformer_width = state_dict["ln_final.weight"].shape[0]
transformer_heads = transformer_width // 64
transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks")))
model = CLIP(
embed_dim,
image_resolution, vision_layers, vision_width, vision_patch_size,
context_length, vocab_size, transformer_width, transformer_heads, transformer_layers
)
for key in ["input_resolution", "context_length", "vocab_size"]:
if key in state_dict:
del state_dict[key]
convert_weights(model)
model.load_state_dict(state_dict)
return model.eval()
| 17,333 | 38.848276 | 178 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/modeling/modules/clip/clip_tokenizer.py | import gzip
import html
import os
from functools import lru_cache
import ftfy
import regex as re
@lru_cache()
def default_bpe():
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz")
@lru_cache()
def bytes_to_unicode():
"""
Returns list of utf-8 byte and a corresponding list of unicode strings.
The reversible bpe codes work on unicode strings.
This means you need a large # of unicode characters in your vocab if you want to avoid UNKs.
When you're at something like a 10B token dataset you end up needing around 5K for decent coverage.
This is a signficant percentage of your normal, say, 32K bpe vocab.
To avoid that, we want lookup tables between utf-8 bytes and unicode strings.
And avoids mapping to whitespace/control characters the bpe code barfs on.
"""
bs = list(range(ord("!"), ord("~")+1))+list(range(ord("¡"), ord("¬")+1))+list(range(ord("®"), ord("ÿ")+1))
cs = bs[:]
n = 0
for b in range(2**8):
if b not in bs:
bs.append(b)
cs.append(2**8+n)
n += 1
cs = [chr(n) for n in cs]
return dict(zip(bs, cs))
def get_pairs(word):
"""Return set of symbol pairs in a word.
Word is represented as tuple of symbols (symbols being variable-length strings).
"""
pairs = set()
prev_char = word[0]
for char in word[1:]:
pairs.add((prev_char, char))
prev_char = char
return pairs
def basic_clean(text):
text = ftfy.fix_text(text)
text = html.unescape(html.unescape(text))
return text.strip()
def whitespace_clean(text):
text = re.sub(r'\s+', ' ', text)
text = text.strip()
return text
class SimpleTokenizer(object):
def __init__(self, end_idx=49152, bpe_path: str = default_bpe()):
self.byte_encoder = bytes_to_unicode()
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
merges = gzip.open(bpe_path).read().decode("utf-8").split('\n')
# merges = merges[1:49152-256-2+1]
# end_idx can be 49152 for CLIP
# or 16384 for DALL-E
merges = merges[1:end_idx-256-2+1]
merges = [tuple(merge.split()) for merge in merges]
vocab = list(bytes_to_unicode().values())
vocab = vocab + [v+'</w>' for v in vocab] # with length 256
for merge in merges:
vocab.append(''.join(merge))
vocab.extend(['<|startoftext|>', '<|endoftext|>']) # with length = end_idx+256
self.encoder = dict(zip(vocab, range(len(vocab))))
self.decoder = {v: k for k, v in self.encoder.items()}
self.bpe_ranks = dict(zip(merges, range(len(merges))))
self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'}
self.pat = re.compile(r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", re.IGNORECASE)
def bpe(self, token):
if token in self.cache:
return self.cache[token]
word = tuple(token[:-1]) + (token[-1] + '</w>',)
pairs = get_pairs(word)
if not pairs:
return token + '</w>'
while True:
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf')))
if bigram not in self.bpe_ranks:
break
first, second = bigram
new_word = []
i = 0
while i < len(word):
try:
j = word.index(first, i)
new_word.extend(word[i:j])
i = j
except:
new_word.extend(word[i:])
break
if word[i] == first and i < len(word) - 1 and word[i+1] == second:
new_word.append(first+second)
i += 2
else:
new_word.append(word[i])
i += 1
new_word = tuple(new_word)
word = new_word
if len(word) == 1:
break
else:
pairs = get_pairs(word)
word = ' '.join(word)
self.cache[token] = word
return word
def encode(self, text):
bpe_tokens = []
text = whitespace_clean(basic_clean(text)).lower()
for token in re.findall(self.pat, text):
token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8'))
bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' '))
return bpe_tokens
def decode(self, tokens):
text = ''.join([self.decoder[token] for token in tokens])
text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('</w>', ' ')
return text
| 4,806 | 34.087591 | 144 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/modeling/codecs/base_codec.py | import torch
from torch import nn
class BaseCodec(nn.Module):
def get_tokens(self, x, **kwargs):
"""
Input:
x: input data
Return:
indices: B x L, the codebook indices, where L is the length
of flattened feature map size
"""
raise NotImplementedError
def get_number_of_tokens(self):
"""
Return: int, the number of tokens
"""
raise NotImplementedError
def encode(self, img):
raise NotImplementedError
def decode(self, img_seq):
raise NotImplementedError
def forward(self, **kwargs):
raise NotImplementedError
def train(self, mode=True):
self.training = mode
if self.trainable and mode:
return super().train(True)
else:
return super().train(False)
def _set_trainable(self):
if not self.trainable:
for pn, p in self.named_parameters():
p.requires_grad = False
self.eval() | 1,046 | 23.348837 | 72 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/modeling/codecs/image_codec/taming_gumbel_vqvae.py | import torch
import torch.nn as nn
from omegaconf import OmegaConf
import sys
sys.path.append("..")
# sys.path.append("../image_synthesis")
from image_synthesis.utils.misc import instantiate_from_config
from image_synthesis.taming.models.vqgan import GumbelVQ, VQModel
from image_synthesis.taming.models.cond_transformer import Net2NetTransformer
import os
import torchvision.transforms.functional as TF
import PIL
from image_synthesis.modeling.codecs.base_codec import BaseCodec
from einops import rearrange
import math
class Encoder(nn.Module):
def __init__(self, encoder, quant_conv, quantize):
super().__init__()
self.encoder = encoder
self.quant_conv = quant_conv
self.quantize = quantize
@torch.no_grad()
def forward(self, x):
x = 2*x - 1
h = self.encoder(x)
h = self.quant_conv(h)
quant, _, [_, _, indices] = self.quantize(h)
return indices.view(x.shape[0], -1)
class Decoder(nn.Module):
def __init__(self, decoder, post_quant_conv, quantize, w=16, h=16):
super().__init__()
self.decoder = decoder
self.post_quant_conv = post_quant_conv
self.quantize = quantize
self.w = w
self.h = h
@torch.no_grad()
def forward(self, indices):
z = self.quantize.get_codebook_entry(indices.view(-1), shape=(indices.shape[0], self.h, self.w, -1))
quant = self.post_quant_conv(z)
dec = self.decoder(quant)
x = torch.clamp(dec, -1., 1.)
x = (x + 1.)/2.
return x
class TamingFFHQVQVAE(BaseCodec):
def __init__(
self,
trainable=False,
token_shape=[16,16],
config_path='OUTPUT/pretrained_model/taming_dvae/vqgan_ffhq_f16_1024.yaml',
ckpt_path='OUTPUT/pretrained_model/taming_dvae/vqgan_ffhq_f16_1024.pth',
num_tokens=1024,
quantize_number=0,
mapping_path=None,
):
super().__init__()
model = self.LoadModel(config_path, ckpt_path)
self.enc = Encoder(model.encoder, model.quant_conv, model.quantize)
self.dec = Decoder(model.decoder, model.post_quant_conv, model.quantize, token_shape[0], token_shape[1])
self.num_tokens = num_tokens
self.quantize_number = quantize_number
if self.quantize_number != 0 and mapping_path!=None:
self.full_to_quantize = torch.load(mapping_path)
self.quantize_to_full = torch.zeros(self.quantize_number)-1
for idx, i in enumerate(self.full_to_quantize):
if self.quantize_to_full[i] == -1:
self.quantize_to_full[i] = idx
self.quantize_to_full = self.quantize_to_full.long()
self.trainable = trainable
self.token_shape = token_shape
self._set_trainable()
def LoadModel(self, config_path, ckpt_path):
config = OmegaConf.load(config_path)
# model = instantiate_from_config(config.model)
model = Net2NetTransformer(**config.model.params)
sd = torch.load(ckpt_path, map_location="cpu")["state_dict"]
model.load_state_dict(sd, strict=False)
if (isinstance(model, Net2NetTransformer)):
model = model.first_stage_model
return model
@property
def device(self):
# import pdb; pdb.set_trace()
return self.enc.quant_conv.weight.device
def preprocess(self, imgs):
"""
imgs: B x C x H x W, in the range 0-255
"""
imgs = imgs.div(255) # map to 0 - 1
return imgs
# return map_pixels(imgs)
def postprocess(self, imgs):
"""
imgs: B x C x H x W, in the range 0-1
"""
imgs = imgs * 255
return imgs
def get_tokens(self, imgs, **kwargs):
imgs = self.preprocess(imgs)
code = self.enc(imgs)
if self.quantize_number != 0:
code = self.full_to_quantize[code]
output = {'token': code}
# output = {'token': rearrange(code, 'b h w -> b (h w)')}
return output
def decode(self, img_seq):
if self.quantize_number != 0:
img_seq=self.quantize_to_full[img_seq].type_as(img_seq)
b, n = img_seq.shape
img_seq = rearrange(img_seq, 'b (h w) -> b h w', h = int(math.sqrt(n)))
x_rec = self.dec(img_seq)
x_rec = self.postprocess(x_rec)
return x_rec
class TamingVQVAE(BaseCodec):
def __init__(
self,
trainable=False,
token_shape=[16,16],
config_path='OUTPUT/pretrained_model/taming_dvae/vqgan_imagenet_f16_16384.yaml',
ckpt_path='OUTPUT/pretrained_model/taming_dvae/vqgan_imagenet_f16_16384.pth',
num_tokens=16384,
quantize_number=974,
mapping_path='./help_folder/statistics/taming_vqvae_974.pt',
):
super().__init__()
model = self.LoadModel(config_path, ckpt_path)
self.enc = Encoder(model.encoder, model.quant_conv, model.quantize)
self.dec = Decoder(model.decoder, model.post_quant_conv, model.quantize, token_shape[0], token_shape[1])
self.num_tokens = num_tokens
self.quantize_number = quantize_number
if self.quantize_number != 0 and mapping_path!=None:
self.full_to_quantize = torch.load(mapping_path)
self.quantize_to_full = torch.zeros(self.quantize_number)-1
for idx, i in enumerate(self.full_to_quantize):
if self.quantize_to_full[i] == -1:
self.quantize_to_full[i] = idx
self.quantize_to_full = self.quantize_to_full.long()
self.trainable = trainable
self.token_shape = token_shape
self._set_trainable()
def LoadModel(self, config_path, ckpt_path):
config = OmegaConf.load(config_path)
model = VQModel(**config.model.params)
sd = torch.load(ckpt_path, map_location="cpu")["state_dict"]
model.load_state_dict(sd, strict=False)
return model
@property
def device(self):
# import pdb; pdb.set_trace()
return self.enc.quant_conv.weight.device
def preprocess(self, imgs):
"""
imgs: B x C x H x W, in the range 0-255
"""
imgs = imgs.div(255) # map to 0 - 1
return imgs
# return map_pixels(imgs)
def postprocess(self, imgs):
"""
imgs: B x C x H x W, in the range 0-1
"""
imgs = imgs * 255
return imgs
def get_tokens(self, imgs, **kwargs):
imgs = self.preprocess(imgs)
code = self.enc(imgs)
if self.quantize_number != 0:
code = self.full_to_quantize[code]
output = {'token': code}
# output = {'token': rearrange(code, 'b h w -> b (h w)')}
return output
def decode(self, img_seq):
if self.quantize_number != 0:
img_seq=self.quantize_to_full[img_seq].type_as(img_seq)
b, n = img_seq.shape
img_seq = rearrange(img_seq, 'b (h w) -> b h w', h = int(math.sqrt(n)))
x_rec = self.dec(img_seq)
x_rec = self.postprocess(x_rec)
return x_rec
class TamingGumbelVQVAE(BaseCodec):
def __init__(
self,
trainable=False,
token_shape=[32,32],
config_path='OUTPUT/pretrained_model/taming_dvae/taming_f8_8192_openimages.yaml',
ckpt_path='OUTPUT/pretrained_model/taming_dvae/taming_f8_8192_openimages_last.pth',
num_tokens=8192,
quantize_number=2887,
mapping_path='./help_folder/statistics/taming_vqvae_2887.pt',
):
super().__init__()
model = self.LoadModel(config_path, ckpt_path)
self.enc = Encoder(model.encoder, model.quant_conv, model.quantize)
self.dec = Decoder(model.decoder, model.post_quant_conv, model.quantize, token_shape[0], token_shape[1])
self.num_tokens = num_tokens
self.quantize_number = quantize_number
if self.quantize_number != 0 and mapping_path!=None:
self.full_to_quantize = torch.load(mapping_path)
self.quantize_to_full = torch.zeros(self.quantize_number)-1
for idx, i in enumerate(self.full_to_quantize):
if self.quantize_to_full[i] == -1:
self.quantize_to_full[i] = idx
self.quantize_to_full = self.quantize_to_full.long()
self.trainable = trainable
self.token_shape = token_shape
self._set_trainable()
def LoadModel(self, config_path, ckpt_path):
config = OmegaConf.load(config_path)
model = GumbelVQ(**config.model.params)
sd = torch.load(ckpt_path, map_location="cpu")["state_dict"]
model.load_state_dict(sd, strict=False)
return model
@property
def device(self):
# import pdb; pdb.set_trace()
return self.enc.quant_conv.weight.device
def preprocess(self, imgs):
"""
imgs: B x C x H x W, in the range 0-255
"""
imgs = imgs.div(255) # map to 0 - 1
return imgs
# return map_pixels(imgs)
def postprocess(self, imgs):
"""
imgs: B x C x H x W, in the range 0-1
"""
imgs = imgs * 255
return imgs
def get_tokens(self, imgs, **kwargs):
imgs = self.preprocess(imgs)
code = self.enc(imgs)
if self.quantize_number != 0:
code = self.full_to_quantize[code]
output = {'token': code}
# output = {'token': rearrange(code, 'b h w -> b (h w)')}
return output
def decode(self, img_seq):
if self.quantize_number != 0:
img_seq=self.quantize_to_full[img_seq].type_as(img_seq)
b, n = img_seq.shape
img_seq = rearrange(img_seq, 'b (h w) -> b h w', h = int(math.sqrt(n)))
x_rec = self.dec(img_seq)
x_rec = self.postprocess(x_rec)
return x_rec
| 10,011 | 33.885017 | 112 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/modeling/codecs/image_codec/patch_vqgan.py | from numpy.core.shape_base import block
from numpy.lib import stride_tricks
import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import random
from torch.nn.modules.linear import Linear
from image_synthesis.utils.misc import instantiate_from_config
from image_synthesis.modeling.codecs.base_codec import BaseCodec
# from image_synthesis.modeling.modules.vqgan_loss.vqperceptual import VQLPIPSWithDiscriminator
from image_synthesis.modeling.utils.misc import mask_with_top_k, logits_top_k, get_token_type
from image_synthesis.distributed.distributed import all_reduce
# class for quantization
# class for quantization
class EMAVectorQuantizer(nn.Module):
"""
see https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.py
____________________________________________
Discretization bottleneck part of the VQ-VAE.
Inputs:
- n_e : number of embeddings
- e_dim : dimension of embedding
- beta : commitment cost used in loss term, beta * ||z_e(x)-sg[e]||^2
_____________________________________________
"""
def __init__(self, n_e, e_dim, beta,
masked_n_e_ratio=0,#1.0/4,
embed_init_scale=1.0,
decay = 0.99,
embed_ema=True,
get_embed_type='retrive',
distance_type='euclidean',
):
super(EMAVectorQuantizer, self).__init__()
self.n_e = n_e
self.masked_n_e_ratio = masked_n_e_ratio
self.e_dim = e_dim
self.beta = beta
self.decay = decay
self.embed_ema = embed_ema
self.get_embed_type = get_embed_type
self.distance_type = distance_type
if self.embed_ema:
self.eps = 1.0e-5
embed = torch.randn(n_e, e_dim)
# embed = torch.zeros(n_e, e_dim)
# embed.data.uniform_(-embed_init_scale / self.n_e, embed_init_scale / self.n_e)
self.register_buffer("embedding", embed)
self.register_buffer("cluster_size", torch.zeros(n_e))
self.register_buffer("embedding_avg", embed.clone())
else:
self.embedding = nn.Embedding(self.n_e, self.e_dim)
self.embedding.weight.data.uniform_(-embed_init_scale / self.n_e, embed_init_scale / self.n_e)
self.masked_embed_start = self.n_e - int(self.masked_n_e_ratio * self.n_e)
if self.distance_type == 'learned':
self.distance_fc = nn.Linear(self.e_dim, self.n_e)
@property
def norm_feat(self):
return self.distance_type in ['cosine', 'sinkhorn']
@property
def embed_weight(self):
if isinstance(self.embedding, nn.Embedding):
return self.embedding.weight
else:
return self.embedding
def norm_embedding(self):
if self.training:
with torch.no_grad():
w = self.embed_weight.data.clone()
w = F.normalize(w, dim=1, p=2)
if isinstance(self.embedding, nn.Embedding):
self.embedding.weight.copy_(w)
else:
self.embedding.copy_(w)
def _quantize(self, z, token_type=None):
"""
z: L x D
token_type: L, 1 denote unmasked token, other masked token
"""
if self.distance_type == 'euclidean':
d = torch.sum(z ** 2, dim=1, keepdim=True) + \
torch.sum(self.embed_weight**2, dim=1) - 2 * \
torch.matmul(z, self.embed_weight.t())
elif self.distance_type == 'cosine':
d = 0 - torch.einsum('ld,nd->ln', z, self.embed_weight) # BHW x N
else:
raise NotImplementedError('distance not implemented for {}'.format(self.distance_type))
# find closest encodings
# import pdb; pdb.set_trace()
if token_type is None or self.masked_embed_start == self.n_e:
min_encoding_indices = torch.argmin(d, dim=1) # L
else:
min_encoding_indices = torch.zeros(z.shape[0]).long().to(z.device)
idx = token_type == 1
if idx.sum() > 0:
d_ = d[idx][:, :self.masked_embed_start] # l x n
indices_ = torch.argmin(d_, dim=1)
min_encoding_indices[idx] = indices_
idx = token_type != 1
if idx.sum() > 0:
d_ = d[idx][:, self.masked_embed_start:] # l x n
indices_ = torch.argmin(d_, dim=1) + self.masked_embed_start
min_encoding_indices[idx] = indices_
if self.get_embed_type == 'matmul':
min_encodings = torch.zeros(min_encoding_indices.shape[0], self.n_e).to(z)
min_encodings.scatter_(1, min_encoding_indices.unsqueeze(1), 1)
# import pdb; pdb.set_trace()
z_q = torch.matmul(min_encodings, self.embed_weight)#.view(z.shape)
elif self.get_embed_type == 'retrive':
z_q = F.embedding(min_encoding_indices, self.embed_weight)#.view(z.shape)
else:
raise NotImplementedError
return z_q, min_encoding_indices
def forward(self, z, token_type=None):
"""
z: B x C x H x W
token_type: B x 1 x H x W
"""
if self.distance_type in ['sinkhorn', 'cosine']:
# need to norm feat and weight embedding
self.norm_embedding()
z = F.normalize(z, dim=1, p=2)
# reshape z -> (batch, height, width, channel) and flatten
batch_size, _, height, width = z.shape
# import pdb; pdb.set_trace()
z = z.permute(0, 2, 3, 1).contiguous() # B x H x W x C
z_flattened = z.view(-1, self.e_dim) # BHW x C
if token_type is not None:
token_type_flattened = token_type.view(-1)
else:
token_type_flattened = None
z_q, min_encoding_indices = self._quantize(z_flattened, token_type_flattened)
z_q = z_q.view(batch_size, height, width, -1) #.permute(0, 2, 3, 1).contiguous()
if self.training and self.embed_ema:
# import pdb; pdb.set_trace()
assert self.distance_type in ['euclidean', 'cosine']
indices_onehot = F.one_hot(min_encoding_indices, self.n_e).to(z_flattened.dtype) # L x n_e
indices_onehot_sum = indices_onehot.sum(0) # n_e
z_sum = (z_flattened.transpose(0, 1) @ indices_onehot).transpose(0, 1) # n_e x D
all_reduce(indices_onehot_sum)
all_reduce(z_sum)
self.cluster_size.data.mul_(self.decay).add_(indices_onehot_sum, alpha=1 - self.decay)
self.embedding_avg.data.mul_(self.decay).add_(z_sum, alpha=1 - self.decay)
n = self.cluster_size.sum()
cluster_size = (self.cluster_size + self.eps) / (n + self.n_e * self.eps) * n
embed_normalized = self.embedding_avg / cluster_size.unsqueeze(1)
self.embedding.data.copy_(embed_normalized)
# print((self.embed > 1.0e-20).abs().sum())
if self.embed_ema:
loss = (z_q.detach() - z).pow(2).mean()
else:
# compute loss for embedding
loss = torch.mean((z_q.detach()-z).pow(2)) + self.beta * torch.mean((z_q - z.detach()).pow(2))
# preserve gradients
z_q = z + (z_q - z).detach()
# reshape back to match original input shape
z_q = z_q.permute(0, 3, 1, 2).contiguous()
# used_quantize_embed = torch.zeros_like(loss) + min_encoding_indices.unique().shape[0]
# used_quantize_embed = all_reduce(used_quantize_embed) / get_world_size()
output = {
'quantize': z_q,
'used_quantize_embed': torch.zeros_like(loss) + min_encoding_indices.unique().shape[0],
'quantize_loss': loss,
'index': min_encoding_indices.view(batch_size, height, width)
}
if token_type_flattened is not None:
unmasked_num_token = all_reduce((token_type_flattened == 1).sum())
masked_num_token = all_reduce((token_type_flattened != 1).sum())
output['unmasked_num_token'] = unmasked_num_token
output['masked_num_token'] = masked_num_token
return output
def only_get_indices(self, z, token_type=None):
"""
z: B x C x H x W
token_type: B x 1 x H x W
"""
if self.distance_type in ['sinkhorn', 'cosine']:
# need to norm feat and weight embedding
self.norm_embedding()
z = F.normalize(z, dim=1, p=2)
# reshape z -> (batch, height, width, channel) and flatten
batch_size, _, height, width = z.shape
# import pdb; pdb.set_trace()
z = z.permute(0, 2, 3, 1).contiguous() # B x H x W x C
z_flattened = z.view(-1, self.e_dim) # BHW x C
if token_type is not None:
token_type_flattened = token_type.view(-1)
else:
token_type_flattened = None
_, min_encoding_indices = self._quantize(z_flattened, token_type_flattened)
min_encoding_indices = min_encoding_indices.view(batch_size, height, width)
return min_encoding_indices
def get_codebook_entry(self, indices, shape):
# import pdb; pdb.set_trace()
# shape specifying (batch, height, width)
if self.get_embed_type == 'matmul':
min_encodings = torch.zeros(indices.shape[0], self.n_e).to(indices)
min_encodings.scatter_(1, indices[:,None], 1)
# get quantized latent vectors
z_q = torch.matmul(min_encodings.float(), self.embed_weight)
elif self.get_embed_type == 'retrive':
z_q = F.embedding(indices, self.embed_weight)
else:
raise NotImplementedError
if shape is not None:
z_q = z_q.view(*shape, -1) # B x H x W x C
if len(z_q.shape) == 4:
# reshape back to match original input shape
z_q = z_q.permute(0, 3, 1, 2).contiguous()
return z_q
# blocks for encoder and decoder
def Normalize(in_channels):
return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
def nonlinearity(x):
# swish
return x*torch.sigmoid(x)
class Upsample(nn.Module):
def __init__(self, in_channels, with_conv, upsample_type='interpolate'):
super().__init__()
self.upsample_type = upsample_type
self.with_conv = with_conv
if self.upsample_type == 'conv':
self.sample = nn.ConvTranspose2d(in_channels, in_channels, kernel_size=4, stride=2, padding=1),
if self.with_conv:
self.conv = torch.nn.Conv2d(in_channels,
in_channels,
kernel_size=3,
stride=1,
padding=1)
def forward(self, x):
if self.upsample_type == 'conv':
x = self.sample(x)
else:
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
if self.with_conv:
x = self.conv(x)
return x
class ResnetBlock(nn.Module):
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
dropout=0.0, temb_channels=512):
super().__init__()
self.in_channels = in_channels
out_channels = in_channels if out_channels is None else out_channels
self.out_channels = out_channels
self.use_conv_shortcut = conv_shortcut
self.norm1 = Normalize(in_channels)
self.conv1 = torch.nn.Conv2d(in_channels,
out_channels,
kernel_size=3,
stride=1,
padding=1)
if temb_channels > 0:
self.temb_proj = torch.nn.Linear(temb_channels,
out_channels)
self.norm2 = Normalize(out_channels)
self.dropout = torch.nn.Dropout(dropout)
self.conv2 = torch.nn.Conv2d(out_channels,
out_channels,
kernel_size=3,
stride=1,
padding=1)
if self.in_channels != self.out_channels:
if self.use_conv_shortcut:
self.conv_shortcut = torch.nn.Conv2d(in_channels,
out_channels,
kernel_size=3,
stride=1,
padding=1)
else:
self.nin_shortcut = torch.nn.Conv2d(in_channels,
out_channels,
kernel_size=1,
stride=1,
padding=0)
def forward(self, x, temb):
h = x
h = self.norm1(h)
h = nonlinearity(h)
h = self.conv1(h)
if temb is not None:
h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
h = self.norm2(h)
h = nonlinearity(h)
h = self.dropout(h)
h = self.conv2(h)
if self.in_channels != self.out_channels:
if self.use_conv_shortcut:
x = self.conv_shortcut(x)
else:
x = self.nin_shortcut(x)
return x+h
class AttnBlock(nn.Module):
def __init__(self, in_channels):
super().__init__()
self.in_channels = in_channels
self.norm = Normalize(in_channels)
self.q = torch.nn.Conv2d(in_channels,
in_channels,
kernel_size=1,
stride=1,
padding=0)
self.k = torch.nn.Conv2d(in_channels,
in_channels,
kernel_size=1,
stride=1,
padding=0)
self.v = torch.nn.Conv2d(in_channels,
in_channels,
kernel_size=1,
stride=1,
padding=0)
self.proj_out = torch.nn.Conv2d(in_channels,
in_channels,
kernel_size=1,
stride=1,
padding=0)
def forward(self, x):
h_ = x
h_ = self.norm(h_)
q = self.q(h_)
k = self.k(h_)
v = self.v(h_)
# compute attention
b,c,h,w = q.shape
q = q.reshape(b,c,h*w)
q = q.permute(0,2,1) # b,hw,c
k = k.reshape(b,c,h*w) # b,c,hw
w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
w_ = w_ * (int(c)**(-0.5))
w_ = torch.nn.functional.softmax(w_, dim=2)
# attend to values
v = v.reshape(b,c,h*w)
w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
h_ = h_.reshape(b,c,h,w)
h_ = self.proj_out(h_)
return x+h_
class Downsample(nn.Module):
def __init__(self, in_channels, with_conv):
super().__init__()
self.with_conv = with_conv
if self.with_conv:
# no asymmetric padding in torch conv, must do it ourselves
self.conv = torch.nn.Conv2d(in_channels,
in_channels,
kernel_size=3,
stride=2,
padding=0)
def forward(self, x):
if self.with_conv:
pad = (0,1,0,1)
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
x = self.conv(x)
else:
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
return x
class Encoder(nn.Module):
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), scale_by_2=None, num_res_blocks,
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
resolution, z_channels, double_z=False, **ignore_kwargs):
super().__init__()
if isinstance(resolution, int):
resolution = [resolution, resolution] # H, W
elif isinstance(resolution, (tuple, list)):
resolution = list(resolution)
else:
raise ValueError('Unknown type of resolution:', resolution)
attn_resolutions_ = []
for ar in attn_resolutions:
if isinstance(ar, (list, tuple)):
attn_resolutions_.append(list(ar))
else:
attn_resolutions_.append([ar, ar])
attn_resolutions = attn_resolutions_
self.ch = ch
self.temb_ch = 0
self.num_resolutions = len(ch_mult)
self.num_res_blocks = num_res_blocks
self.resolution = resolution
self.in_channels = in_channels
# downsampling
self.conv_in = torch.nn.Conv2d(in_channels,
self.ch,
kernel_size=3,
stride=1,
padding=1)
curr_res = resolution
in_ch_mult = (1,)+tuple(ch_mult)
self.down = nn.ModuleList()
for i_level in range(self.num_resolutions):
block = nn.ModuleList()
attn = nn.ModuleList()
block_in = ch*in_ch_mult[i_level]
block_out = ch*ch_mult[i_level]
for i_block in range(self.num_res_blocks):
block.append(ResnetBlock(in_channels=block_in,
out_channels=block_out,
temb_channels=self.temb_ch,
dropout=dropout))
block_in = block_out
if curr_res in attn_resolutions:
attn.append(AttnBlock(block_in))
down = nn.Module()
down.block = block
down.attn = attn
if scale_by_2 is None:
if i_level != self.num_resolutions-1:
down.downsample = Downsample(block_in, resamp_with_conv)
curr_res = [r // 2 for r in curr_res]
else:
if scale_by_2[i_level]:
down.downsample = Downsample(block_in, resamp_with_conv)
curr_res = [r // 2 for r in curr_res]
self.down.append(down)
# middle
self.mid = nn.Module()
self.mid.block_1 = ResnetBlock(in_channels=block_in,
out_channels=block_in,
temb_channels=self.temb_ch,
dropout=dropout)
self.mid.attn_1 = AttnBlock(block_in)
self.mid.block_2 = ResnetBlock(in_channels=block_in,
out_channels=block_in,
temb_channels=self.temb_ch,
dropout=dropout)
# end
self.norm_out = Normalize(block_in)
self.conv_out = torch.nn.Conv2d(block_in,
2*z_channels if double_z else z_channels,
kernel_size=3,
stride=1,
padding=1)
def forward(self, x):
#assert x.shape[2] == self.resolution[0] and x.shape[3] == self.resolution[1], "{}, {}, {}".format(x.shape[2], x.shape[3], self.resolution)
# timestep embedding
temb = None
# downsampling
hs = [self.conv_in(x)]
for i_level in range(self.num_resolutions):
for i_block in range(self.num_res_blocks):
h = self.down[i_level].block[i_block](hs[-1], temb)
if len(self.down[i_level].attn) > 0:
h = self.down[i_level].attn[i_block](h)
hs.append(h)
if getattr(self.down[i_level], 'downsample', None) is not None:
h = self.down[i_level].downsample(hs[-1])
if i_level != self.num_resolutions-1:
# hs.append(self.down[i_level].downsample(hs[-1]))
hs.append(h)
# middle
h = hs[-1]
h = self.mid.block_1(h, temb)
h = self.mid.attn_1(h)
h = self.mid.block_2(h, temb)
# end
h = self.norm_out(h)
h = nonlinearity(h)
h = self.conv_out(h)
return h
class Decoder(nn.Module):
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), scale_by_2=None, num_res_blocks,
attn_resolutions, dropout=0.0, resamp_with_conv=True,
resolution, z_channels, **ignorekwargs):
super().__init__()
if isinstance(resolution, int):
resolution = [resolution, resolution] # H, W
elif isinstance(resolution, (tuple, list)):
resolution = list(resolution)
else:
raise ValueError('Unknown type of resolution:', resolution)
attn_resolutions_ = []
for ar in attn_resolutions:
if isinstance(ar, (list, tuple)):
attn_resolutions_.append(list(ar))
else:
attn_resolutions_.append([ar, ar])
attn_resolutions = attn_resolutions_
self.ch = ch
self.temb_ch = 0
self.num_resolutions = len(ch_mult)
self.num_res_blocks = num_res_blocks
self.resolution = resolution
self.requires_image = False
# compute in_ch_mult, block_in and curr_res at lowest res
in_ch_mult = (1,)+tuple(ch_mult)
block_in = ch*ch_mult[self.num_resolutions-1]
if scale_by_2 is None:
curr_res = [r // 2**(self.num_resolutions-1) for r in self.resolution]
else:
scale_factor = sum([int(s) for s in scale_by_2])
curr_res = [r // 2**scale_factor for r in self.resolution]
self.z_shape = (1, z_channels, curr_res[0], curr_res[1])
print("Working with z of shape {} = {} dimensions.".format(self.z_shape, np.prod(self.z_shape)))
# z to block_in
self.conv_in = torch.nn.Conv2d(z_channels,
block_in,
kernel_size=3,
stride=1,
padding=1)
# middle
self.mid = nn.Module()
self.mid.block_1 = ResnetBlock(in_channels=block_in,
out_channels=block_in,
temb_channels=self.temb_ch,
dropout=dropout)
self.mid.attn_1 = AttnBlock(block_in)
self.mid.block_2 = ResnetBlock(in_channels=block_in,
out_channels=block_in,
temb_channels=self.temb_ch,
dropout=dropout)
# upsampling
self.up = nn.ModuleList()
for i_level in reversed(range(self.num_resolutions)):
block = nn.ModuleList()
attn = nn.ModuleList()
block_out = ch*ch_mult[i_level]
for i_block in range(self.num_res_blocks+1):
block.append(ResnetBlock(in_channels=block_in,
out_channels=block_out,
temb_channels=self.temb_ch,
dropout=dropout))
block_in = block_out
if curr_res in attn_resolutions:
attn.append(AttnBlock(block_in))
up = nn.Module()
up.block = block
up.attn = attn
if scale_by_2 is None:
if i_level != 0:
up.upsample = Upsample(block_in, resamp_with_conv)
curr_res = [r * 2 for r in curr_res]
else:
if scale_by_2[i_level]:
up.upsample = Upsample(block_in, resamp_with_conv)
curr_res = [r * 2 for r in curr_res]
self.up.insert(0, up) # prepend to get consistent order
# end
self.norm_out = Normalize(block_in)
self.conv_out = torch.nn.Conv2d(block_in,
out_ch,
kernel_size=3,
stride=1,
padding=1)
def forward(self, z, **kwargs):
#assert z.shape[1:] == self.z_shape[1:]
self.last_z_shape = z.shape
# timestep embedding
temb = None
# z to block_in
h = self.conv_in(z)
# middle
h = self.mid.block_1(h, temb)
h = self.mid.attn_1(h)
h = self.mid.block_2(h, temb)
# upsampling
for i_level in reversed(range(self.num_resolutions)):
for i_block in range(self.num_res_blocks+1):
h = self.up[i_level].block[i_block](h, temb)
if len(self.up[i_level].attn) > 0:
h = self.up[i_level].attn[i_block](h)
# if i_level != 0:
if getattr(self.up[i_level], 'upsample', None) is not None:
h = self.up[i_level].upsample(h)
h = self.norm_out(h)
h = nonlinearity(h)
h = self.conv_out(h)
return h
class PatchVQGAN(BaseCodec):
def __init__(self,
*,
encoder_config,
decoder_config,
lossconfig=None,
n_embed,
embed_dim,
ignore_keys=[],
data_info={'key': 'image'},
quantizer_type='VQ',
quantizer_dis_type='euclidean',
decay = 0.99,
trainable=False,
ckpt_path=None,
token_shape=None
):
super().__init__()
self.encoder = instantiate_from_config(encoder_config) # Encoder(**encoder_config)
self.decoder = instantiate_from_config(decoder_config) # Decoder(**decoder_config)
if quantizer_type == 'EMAVQ':
self.quantize = EMAVectorQuantizer(n_embed, embed_dim, beta=0.25, decay = decay, distance_type=quantizer_dis_type)
print('using EMA vector Quantizer')
elif quantizer_type == 'PQEMAVQ':
self.quantize = PQEMAVectorQuantizer(n_embed, embed_dim, beta=0.25,decay = decay, distance_type=quantizer_dis_type)
print('using PQ EMA vector Quantizer')
elif quantizer_type == 'VQ':
self.quantize = VectorQuantizer(n_embed, embed_dim, beta=0.25)
else:
raise NotImplementedError
# import pdb; pdb.set_trace()
self.quant_conv = torch.nn.Conv2d(encoder_config['params']["z_channels"], embed_dim, 1)
self.post_quant_conv = torch.nn.Conv2d(embed_dim, decoder_config['params']["z_channels"], 1)
self.data_info = data_info
if lossconfig is not None and trainable:
self.loss = instantiate_from_config(lossconfig)
else:
self.loss = None
if ckpt_path is not None:
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys)
self.trainable = trainable
self._set_trainable()
self.token_shape = token_shape
def init_from_ckpt(self, path, ignore_keys=list()):
sd = torch.load(path, map_location="cpu")
if 'model' in sd:
sd = sd['model']
else:
sd = sd["state_dict"]
keys = list(sd.keys())
for k in keys:
for ik in ignore_keys:
if k.startswith(ik):
print("VQGAN: Deleting key {} from state_dict.".format(k))
del sd[k]
self.load_state_dict(sd, strict=False)
print(f"VQGAN: Restored from {path}")
@property
def device(self):
return self.quant_conv.weight.device
def pre_process(self, data):
data = data.to(self.device)
data = data / 127.5 - 1.0
return data
def multi_pixels_with_mask(self, data, mask):
if data.max() > 1:
raise ValueError('The data need to be preprocessed!')
mask = mask.to(self.device)
data = data * mask
data[~mask.repeat(1,3,1,1)] = -1.0
return data
def post_process(self, data):
data = (data + 1.0) * 127.5
data = torch.clamp(data, min=0.0, max=255.0)
return data
def get_number_of_tokens(self):
return self.quantize.n_e
def get_tokens(self, data, mask=None, return_token_index=False, **kwargs):
data = self.pre_process(data)
x = self.encoder(data)
x = self.quant_conv(x)
idx = self.quantize(x)['index']
if self.token_shape is None:
self.token_shape = idx.shape[1:3]
if self.decoder.requires_image:
self.mask_im_tmp = self.multi_pixels_with_mask(data, mask)
output = {}
output['token'] = idx.view(idx.shape[0], -1)
# import pdb; pdb.set_trace()
if mask is not None: # mask should be B x 1 x H x W
# downsampling
# mask = F.interpolate(mask.float(), size=idx_mask.shape[-2:]).to(torch.bool)
token_type = get_token_type(mask, self.token_shape) # B x 1 x H x W
mask = token_type == 1
output = {
'target': idx.view(idx.shape[0], -1).clone(),
'mask': mask.view(mask.shape[0], -1),
'token': idx.view(idx.shape[0], -1),
'token_type': token_type.view(token_type.shape[0], -1),
}
else:
output = {
'token': idx.view(idx.shape[0], -1)
}
# get token index
# used for computing token frequency
if return_token_index:
token_index = output['token'] #.view(-1)
output['token_index'] = token_index
return output
def decode(self, token):
assert self.token_shape is not None
# import pdb; pdb.set_trace()
bhw = (token.shape[0], self.token_shape[0], self.token_shape[1])
quant = self.quantize.get_codebook_entry(token.view(-1), shape=bhw)
quant = self.post_quant_conv(quant)
if self.decoder.requires_image:
rec = self.decoder(quant, self.mask_im_tmp)
self.mask_im_tmp = None
else:
rec = self.decoder(quant)
rec = self.post_process(rec)
return rec
def get_rec_loss(self, input, rec):
if input.max() > 1:
input = self.pre_process(input)
if rec.max() > 1:
rec = self.pre_process(rec)
rec_loss = F.mse_loss(rec, input)
return rec_loss
@torch.no_grad()
def sample(self, batch):
data = self.pre_process(batch[self.data_info['key']])
x = self.encoder(data)
x = self.quant_conv(x)
quant = self.quantize(x)['quantize']
quant = self.post_quant_conv(quant)
if self.decoder.requires_image:
mask_im = self.multi_pixels_with_mask(data, batch['mask'])
rec = self.decoder(quant, mask_im)
else:
rec = self.decoder(quant)
rec = self.post_process(rec)
out = {'input': batch[self.data_info['key']], 'reconstruction': rec}
if self.decoder.requires_image:
out['mask_input'] = self.post_process(mask_im)
out['mask'] = batch['mask'] * 255
# import pdb; pdb.set_trace()
return out
def get_last_layer(self):
if isinstance(self.decoder, Decoder):
return self.decoder.conv_out.weight
elif isinstance(self.decoder, PatchDecoder):
return self.decoder.post_layer.weight
elif isinstance(self.decoder, Patch8x8Decoder):
return self.decoder.post_layer.weight
else:
return self.decoder.patch_de_embed.proj.weight
def parameters(self, recurse=True, name=None):
if name is None or name == 'none':
return super().parameters(recurse=recurse)
else:
if name == 'generator':
params = list(self.encoder.parameters())+ \
list(self.decoder.parameters())+\
list(self.quantize.parameters())+\
list(self.quant_conv.parameters())+\
list(self.post_quant_conv.parameters())
elif name == 'discriminator':
params = self.loss.discriminator.parameters()
else:
raise ValueError("Unknown type of name {}".format(name))
return params
def forward(self, batch, name='none', return_loss=True, step=0, **kwargs):
if name == 'generator':
input = self.pre_process(batch[self.data_info['key']])
x = self.encoder(input)
x = self.quant_conv(x)
quant_out = self.quantize(x)
quant = quant_out['quantize']
emb_loss = quant_out['quantize_loss']
# recconstruction
quant = self.post_quant_conv(quant)
if self.decoder.requires_image:
rec = self.decoder(quant, self.multi_pixels_with_mask(input, batch['mask']))
else:
rec = self.decoder(quant)
# save some tensors for
self.input_tmp = input
self.rec_tmp = rec
if isinstance(self.loss, VQLPIPSWithDiscriminator):
output = self.loss(codebook_loss=emb_loss,
inputs=input,
reconstructions=rec,
optimizer_name=name,
global_step=step,
last_layer=self.get_last_layer())
else:
raise NotImplementedError('{}'.format(type(self.loss)))
elif name == 'discriminator':
if isinstance(self.loss, VQLPIPSWithDiscriminator):
output = self.loss(codebook_loss=None,
inputs=self.input_tmp,
reconstructions=self.rec_tmp,
optimizer_name=name,
global_step=step,
last_layer=self.get_last_layer())
else:
raise NotImplementedError('{}'.format(type(self.loss)))
else:
raise NotImplementedError('{}'.format(name))
return output
| 35,439 | 38.116998 | 147 | py |
VQ-Diffusion | VQ-Diffusion-main/image_synthesis/modeling/codecs/image_codec/ema_vqvae.py | import torch
import torch.nn as nn
from omegaconf import OmegaConf
import sys
sys.path.append("..")
# sys.path.append("../image_synthesis")
import os
import torchvision.transforms.functional as TF
import PIL
from image_synthesis.modeling.codecs.base_codec import BaseCodec
from einops import rearrange
import math
import yaml
from image_synthesis.utils.misc import instantiate_from_config
class Encoder(nn.Module):
def __init__(self, encoder, quant_conv, quantize):
super().__init__()
self.encoder = encoder
self.quant_conv = quant_conv
self.quantize = quantize
@torch.no_grad()
def forward(self, x):
x = 2*x - 1
h = self.encoder(x)
h = self.quant_conv(h)
# quant, _, [_, _, indices] = self.quantize(h)
# return indices.view(x.shape[0], -1)
indices = self.quantize.only_get_indices(h)
return indices.view(x.shape[0], -1)
class Decoder(nn.Module):
def __init__(self, decoder, post_quant_conv, quantize, w=16, h=16):
super().__init__()
self.decoder = decoder
self.post_quant_conv = post_quant_conv
self.quantize = quantize
self.w = w
self.h = h
@torch.no_grad()
def forward(self, indices):
z = self.quantize.get_codebook_entry(indices.view(-1), shape=(indices.shape[0], self.h, self.w))
quant = self.post_quant_conv(z)
dec = self.decoder(quant)
x = torch.clamp(dec, -1., 1.)
x = (x + 1.)/2.
return x
class PatchVQVAE(BaseCodec):
def __init__(
self,
trainable=False,
token_shape=[16,16],
):
super().__init__()
config_path = "OUTPUT/pretrained_model/taming_dvae/config.yaml"
ckpt_path="OUTPUT/pretrained_model/taming_dvae/ithq_vqvae.pth"
model = self.LoadModel(config_path, ckpt_path)
self.enc = Encoder(model.encoder, model.quant_conv, model.quantize)
self.dec = Decoder(model.decoder, model.post_quant_conv, model.quantize, token_shape[0], token_shape[1])
self.num_tokens = 4096
self.trainable = trainable
self.token_shape = token_shape
self._set_trainable()
def LoadModel(self, config_path, ckpt_path):
with open(config_path) as f:
config = yaml.full_load(f)
model = instantiate_from_config(config['model'])
sd = torch.load(ckpt_path, map_location="cpu")["model"]
model.load_state_dict(sd, strict=False)
return model
def half(self): # not sure if it's right
"""
overwrite this function
"""
from dall_e.utils import Conv2d
for n, m in self.named_modules():
if isinstance(m, Conv2d) and m.use_float16:
print(n)
m._apply(lambda t: t.half() if t.is_floating_point() else t)
return self
@property
def device(self):
# import pdb; pdb.set_trace()
return self.enc.quant_conv.weight.device
def preprocess(self, imgs):
"""
imgs: B x C x H x W, in the range 0-255
"""
imgs = imgs.div(255) # map to 0 - 1
return imgs
# return map_pixels(imgs)
def postprocess(self, imgs):
"""
imgs: B x C x H x W, in the range 0-1
"""
imgs = imgs * 255
return imgs
def get_tokens(self, imgs, **kwargs):
imgs = self.preprocess(imgs)
code = self.enc(imgs)
output = {'token': code}
# output = {'token': rearrange(code, 'b h w -> b (h w)')}
return output
def decode(self, img_seq):
b, n = img_seq.shape
# if self.token_shape is not None:
# img_seq = img_seq.view(b, self.token_shape[0], self.token_shape[1])
# else:
# img_seq = rearrange(img_seq, 'b (h w) -> b h w', h = int(sqrt(n)))
img_seq = rearrange(img_seq, 'b (h w) -> b h w', h = int(math.sqrt(n)))
x_rec = self.dec(img_seq)
x_rec = self.postprocess(x_rec)
return x_rec
| 4,083 | 29.706767 | 112 | py |