Skip to content

Commit d47a219

Browse files
committed
commit
1 parent 125d4f5 commit d47a219

17 files changed

+404
-70
lines changed

cifar.py

+54-20
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from collections import namedtuple
22
import os
3+
import sys
34
import cv2
45
import time
56
import math
@@ -11,7 +12,7 @@
1112
from glob import glob
1213
from PIL import Image
1314

14-
from comet_ml import Experiment as CometExperiment
15+
from comet_ml import Experiment as CometExperiment, OfflineExperiment
1516
import torch
1617
import torch.nn as nn
1718
import torch.optim as optim
@@ -34,7 +35,18 @@
3435

3536
parser = argparse.ArgumentParser()
3637
parser.add_argument("--mode", default="run", help="run, array, or job")
38+
parser.add_argument(
39+
'--time',
40+
type=float,
41+
default=10,
42+
help='the number of hours',
43+
)
3744
parser.add_argument("--not_pretrain", action="store_true", default=False)
45+
parser.add_argument('--local_comet_dir',
46+
type=str,
47+
default=None,
48+
help='local dir to process comet locally only. '
49+
'primarily for fb, will stop remote calls.')
3850
parser.add_argument('--name',
3951
type=str,
4052
help='the identifying name of this experiment.',
@@ -334,31 +346,47 @@ def forward(self, x):
334346
def main(args):
335347
print('Pretrain? ', not args.not_pretrain)
336348
print(args.model)
337-
338-
comet_exp = CometExperiment(api_key="hIXq6lDzWzz24zgKv7RYz6blo",
339-
project_name="selfcifar",
340-
workspace="cinjon",
341-
auto_metric_logging=True,
342-
auto_output_logging=None,
343-
auto_param_logging=False)
349+
start_time = time.time()
350+
351+
if opt['local_comet_dir']:
352+
comet_exp = OfflineExperiment(
353+
api_key="hIXq6lDzWzz24zgKv7RYz6blo",
354+
project_name="selfcifar",
355+
workspace="cinjon",
356+
auto_metric_logging=True,
357+
auto_output_logging=None,
358+
auto_param_logging=False,
359+
offline_directory=opt['local_comet_dir'])
360+
else:
361+
comet_exp = CometExperiment(
362+
api_key="hIXq6lDzWzz24zgKv7RYz6blo",
363+
project_name="selfcifar",
364+
workspace="cinjon",
365+
auto_metric_logging=True,
366+
auto_output_logging=None,
367+
auto_param_logging=False)
344368
comet_exp.log_parameters(vars(args))
345369
comet_exp.set_name(args.name)
346370

347371
# Build model
348-
path = "/misc/kcgscratch1/ChoGroup/resnick/spaceofmotion/zeping/bsn"
372+
# path = "/misc/kcgscratch1/ChoGroup/resnick/spaceofmotion/zeping/bsn"
349373
if args.model == "amdim":
350-
hparams = load_hparams_from_tags_csv(os.path.join(path, "meta_tags.csv"))
374+
hparams = load_hparams_from_tags_csv('/checkpoint/cinjon/amdim/meta_tags.csv')
375+
# hparams = load_hparams_from_tags_csv(os.path.join(path, "meta_tags.csv"))
351376
model = AMDIMModel(hparams)
352377
if not args.not_pretrain:
353-
model.load_state_dict(
354-
torch.load(os.path.join(path, "_ckpt_epoch_434.ckpt"))["state_dict"])
378+
# _path = os.path.join(path, "_ckpt_epoch_434.ckpt")
379+
_path = '/checkpoint/cinjon/amdim/_ckpt_epoch_434.ckpt'
380+
model.load_state_dict(torch.load(_path)["state_dict"])
355381
else:
356382
print("AMDIM not loading checkpoint") # Debug
357383
linear_model = LinearModel(AMDIM_OUTPUT_DIM, args.num_classes)
358384
elif args.model == "ccc":
359385
model = CCCModel(None)
360386
if not args.not_pretrain:
361-
checkpoint = torch.load(os.path.join(path, "TimeCycleCkpt14.pth"))
387+
# _path = os.path.join(path, "TimeCycleCkpt14.pth")
388+
_path = '/checkpoint/cinjon/spaceofmotion/bsn/TimeCycleCkpt14.pth'
389+
checkpoint = torch.load(_path)
362390
base_dict = {
363391
'.'.join(k.split('.')[1:]): v
364392
for k, v in list(checkpoint['state_dict'].items())}
@@ -369,7 +397,9 @@ def main(args):
369397
elif args.model == "corrflow":
370398
model = CORRFLOWModel(None)
371399
if not args.not_pretrain:
372-
checkpoint = torch.load(os.path.join(path, "corrflow.kineticsmodel.pth"))
400+
_path = '/checkpoint/cinjon/spaceofmotion/supercons/corrflow.kineticsmodel.pth'
401+
# _path = os.path.join(path, "corrflow.kineticsmodel.pth")
402+
checkpoint = torch.load(_path)
373403
base_dict = {
374404
'.'.join(k.split('.')[1:]): v
375405
for k, v in list(checkpoint['state_dict'].items())}
@@ -433,8 +463,7 @@ def main(args):
433463
batch_size = args.batch_size * torch.cuda.device_count()
434464
# CIFAR-10
435465
if args.num_classes == 10:
436-
data_path = ("/misc/kcgscratch1/ChoGroup/resnick/spaceofmotion/zeping/"
437-
"bsn/data/cifar-10-batches-py")
466+
data_path = ("/private/home/cinjon/cifar-data/cifar-10-batches-py")
438467
_train_dataset = CIFAR_dataset(
439468
glob(os.path.join(data_path, "data*")),
440469
args.num_classes,
@@ -484,8 +513,7 @@ def main(args):
484513
# val_dev_dataset, shuffle=False, batch_size=batch_size, num_workers=args.num_workers)
485514
# CIFAR-100
486515
elif args.num_classes == 100:
487-
data_path = ("/misc/kcgscratch1/ChoGroup/resnick/spaceofmotion/zeping/"
488-
"bsn/data/cifar-100-python")
516+
data_path = ("/private/home/cinjon/cifar-data/cifar-100-python")
489517
_train_dataset = CIFAR_dataset(
490518
[os.path.join(data_path, "train")],
491519
args.num_classes,
@@ -529,6 +557,10 @@ def main(args):
529557
train_acc = 0
530558
train_loss_sum = 0.0
531559
for iter, input in enumerate(train_dataloader):
560+
if time.time() - start_time > args.time*3600 - 10 and comet_exp is not None:
561+
comet_exp.end()
562+
sys.exit(-1)
563+
532564
imgs = input[0].to(device)
533565
if args.model != "resnet":
534566
imgs = imgs.unsqueeze(1)
@@ -704,8 +736,10 @@ def main(args):
704736
if val_acc > best_acc:
705737
best_acc = val_acc
706738
best_epoch = epoch
707-
save_path = os.path.join(log_dir, "{}.pth".format(epoch))
708-
torch.save(linear_model.state_dict(), save_path)
739+
linear_save_path = os.path.join(log_dir, "{}.linear.pth".format(epoch))
740+
model_save_path = os.path.join(log_dir, "{}.model.pth".format(epoch))
741+
torch.save(linear_model.state_dict(), linear_save_path)
742+
torch.save(model.state_dict(), model_save_path)
709743

710744
# Check bias and variance
711745
print("Epoch {} lr {} total: train_loss:{} train_acc:{} val_loss:{} val_acc:{}".format(

dataset.py

+12-3
Original file line numberDiff line numberDiff line change
@@ -292,8 +292,10 @@ def __len__(self):
292292
class TEMImages(TEMDataset):
293293
def __init__(self, opt, subset=None, fps=30, image_dir=None, img_loading_func=None, video_info_path=None):
294294
self.do_augment = opt['do_augment'] and subset == 'train'
295+
self.module = opt['representation_module']
296+
self.ccc_img_size = opt.get('ccc_img_size')
295297
self.ext = 'npy'
296-
if '240x426' in opt['gym_image_dir']:
298+
if opt['dataset'] == 'gymnastics' and '240x426' in opt['gym_image_dir']:
297299
self.ext = 'png'
298300
super(TEMImages, self).__init__(opt, subset, feature_dirs=None, fps=fps, image_dir=image_dir, img_loading_func=img_loading_func, video_info_path=video_info_path)
299301

@@ -303,8 +305,15 @@ def _get_video_data(self, data, index):
303305
path = os.path.join(self.image_dir, name)
304306
path = Path(path)
305307
paths = [path / ('%010.4f.%s' % ((i / self.fps), self.ext)) for i in indices]
306-
imgs = [self.img_loading_func(p.absolute(), do_augment=self.do_augment)
307-
for p in paths if p.exists()]
308+
if self.module == 'ccc':
309+
imgs = [
310+
self.img_loading_func(p.absolute(),
311+
do_augment=self.do_augment,
312+
img_size=self.ccc_img_size)
313+
for p in paths if p.exists()]
314+
else:
315+
imgs = [self.img_loading_func(p.absolute(), do_augment=self.do_augment)
316+
for p in paths if p.exists()]
308317
try:
309318
if type(imgs[0]) == np.array:
310319
video_data = np.array(imgs)

gen_pem_results_jobs.py

+8
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,14 @@
5454
3975: 28, 3984: 6,
5555
# TSN RGB 2
5656
4005: 1, 4006: 15, 4003: 17, 4002: 6, 4001: 9,
57+
# TSN RGB 3
58+
4593: 21, 4611: 14, 4599: 14, # 4596 got lost in the shuffle :(
59+
4659: 30, 4656: 23, 4647: 36, 4650: 22,
60+
4623: 30, 4620: 23, 4632: 27, 4617: 28,
61+
# CorrFLow NFC NF:
62+
4802: 1, 4779: 16,
63+
# CCC FT
64+
4560: 34, 4584: 32, 4572: 4, 4575: 3, 4554: 36, 4578: 14
5765
}
5866

5967

gen_postprocessed_results_jobs.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@
3737
c2 = int(c2)
3838
counter = c2
3939

40-
print(c1, c2)
40+
print(pem_results_subdir, c1, c2)
4141
if c1 in fixed:
4242
print('Got from fixed')
4343
job = fixed[c1]

gen_tem_results_jobs.py

+16-2
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,21 @@
5656
# TSN RGB Gym 3 lulz. And a bunch more.
5757
4596: 5, 4593: 14, 4611: 7, 4599: 7, # DFC
5858
4659: 5, 4656: 1, 4647: 5, 4650: 1, # NFC Reg
59-
4623: 3, 4620: 3, 4632: 2, 4617: 3 # NFC NF
59+
4623: 3, 4620: 3, 4632: 2, 4617: 3, # NFC NF
60+
# CCC FT DFC Gym:
61+
4575: 4, 4578: 11, 4584: 4, 4554: 10, 4560: 11, 4572: 14,
62+
# AMDIM NFC:
63+
4440: 1,
64+
# AMDIM NF:
65+
4695: 1,
66+
# Corrflow NF
67+
4793: 14, 4779: 2, 4776: 2, 4802: 14, 4792: 11,
68+
# TSN Thumos NFC Reg
69+
4863: 2, 4872: 1,
70+
# TSN Thumos NFC NF
71+
4908: 8, 4905: 8, 4911: 8, 4926: 8, 4923: 8, 4914: 8,
72+
# TSN Thumos DFC
73+
4881: 1, 4896: 3, 4899: 1, 4902: 3
6074
}
6175

6276

@@ -92,4 +106,4 @@
92106
# print(sorted(_job.items()))
93107
fb_run_batch(_job, counter, email, code_directory)
94108
print('\n')
95-
print(ns)
109+
print(ns+1)

main.py

+4-1
Original file line numberDiff line numberDiff line change
@@ -799,12 +799,15 @@ def main(opt):
799799
print(counter, job, '\n', opt)
800800
opt.update(job)
801801
print(opt, flush=True)
802+
print('\n***\n%s\n***\n' % opt['do_feat_conversion'])
802803
if 'debug' in mode:
803804
opt.update({'num_gpus': 2, 'data_workers': 12,
804805
'name': 'dbg', 'counter': 0,
805806
'tem_batch_size': 1,
806807
# 'gym_image_dir': '/checkpoint/cinjon/spaceofmotion/sep052019/rawframes.426x240.12',
807-
'local_comet_dir': None})
808+
'local_comet_dir': None,
809+
'dataset': 'thumosimages',
810+
'video_info': '/private/home/cinjon/Code/BSN-boundary-sensitive-network.pytorch/data/thumos14_annotations', 'ccc_img_size': 128})
808811

809812
if 'debugrun' not in mode:
810813
main(opt)

models.py

+11
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,9 @@
1313
from representations.ccc.model import transforms_regular_video as ccc_regular_transforms
1414
from representations.ccc.representation import Representation as CCCRepresentation
1515
from representations.ccc.representation import THUMOS_OUTPUT_DIM as CCCThumosDim
16+
from representations.ccc.representation import THUMOS_OUTPUT_DIM_128 as CCCThumosDim128
1617
from representations.ccc.representation import GYMNASTICS_OUTPUT_DIM as CCCGymnasticsDim
18+
from representations.ccc.representation import GYMNASTICS_OUTPUT_DIM_128 as CCCGymnasticsDim128
1719
from representations.ccc.representation import ACTIVITYNET_OUTPUT_DIM as CCCActivitynetDim
1820

1921
from representations.corrflow.model import Model as CorrFlowModel
@@ -48,6 +50,7 @@
4850
from representations.tsn.model import tsn_model as tsn_model_func
4951
from representations.tsn.model import img_loading_func as tsn_img_loading_func
5052
from representations.tsn.model import GYMNASTICS_OUTPUT_DIM as TSNGymDim
53+
from representations.tsn.model import THUMOS_OUTPUT_DIM as TSNThumosDim
5154
from representations.tsn.representation import Representation as TSNRepresentation
5255

5356

@@ -97,6 +100,9 @@ def _get_module(key):
97100
'tsn-gymnastics': (
98101
tsn_model_func, TSNRepresentation, tsn_img_loading_func, TSNGymDim
99102
),
103+
'tsn-thumosimages': (
104+
tsn_model_func, TSNRepresentation, tsn_img_loading_func, TSNThumosDim
105+
),
100106
}.get(key)
101107

102108

@@ -152,6 +158,11 @@ def __init__(self, opt):
152158
if self.do_representation:
153159
key = '%s-%s' % (opt['representation_module'], opt['dataset'])
154160
model, representation, _, representation_dim = _get_module(key)
161+
if opt['representation_module'] == 'ccc' and opt['ccc_img_size'] == 128:
162+
if opt['dataset'] == 'gymnastics':
163+
representation_dim = CCCGymnasticsDim128
164+
elif opt['dataset'] == 'thumosimages':
165+
representation_dim = CCCThumosDim128
155166
tags_csv = opt['representation_tags']
156167
if tags_csv:
157168
hparams = load_hparams_from_tags_csv(tags_csv)

opts.py

+1
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ def parse_opt():
6565
parser.add_argument('--tem_nonlinear_factor', type=float, default=0.01)
6666
parser.add_argument('--tem_reset_params', action='store_true')
6767
parser.add_argument('--gym_image_dir', type=str, default='/checkpoint/cinjon/spaceofmotion/sep052019/rawframes.426x240.12')
68+
parser.add_argument('--ccc_img_size', type=int, default=256)
6869
parser.add_argument('--tsn_config', type=str, default='~/Code/BSN-boundary-sensitive-network.pytorch/representations/tsn/temp_tsn_rgb_bninception.py')
6970

7071
# PEM model settings

pem_jobs.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030

3131

3232
def run(find_counter=None):
33-
counter = 854 # NOTE: adjust each time 451, 715, 750, 782, 814
33+
counter = 950 # NOTE: adjust each time 451, 715, 750, 782, 814, 854
3434

3535
for tem_results_subdir in sorted(os.listdir(tem_results_dir)):
3636
# if counter - start_counter > 100:
@@ -103,7 +103,7 @@ def run(find_counter=None):
103103
func(__job, counter, email, code_directory)
104104
elif counter == find_counter:
105105
return __job
106-
print(counter) # ended w 782, 814, 854, 950
106+
print(counter) # ended w 782, 814, 854, 950, 1054
107107

108108
if __name__ == '__main__':
109109
run()

representations/amdim/representation.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,9 @@ def __init__(self, opts):
7272
self.repr_layer1 = self.make_layer(ResidualBlock, channels, channels, 2, stride=2)
7373
self.repr_layer2 = self.make_layer(ResidualBlock, channels, channels, 2, stride=2)
7474
if opts['dataset'] == 'gymnastics':
75-
self.fc_layer = nn.Linear(2432, 400)
75+
self.fc_layer = nn.Linear(640, 400) # 2432
7676
elif opts['dataset'] == 'thumosimages':
77-
self.fc_layer = nn.Linear(2432, 400)
77+
self.fc_layer = nn.Linear(640, 400)
7878
elif opts['dataset'] == 'activitynet':
7979
self.fc_layer = nn.Linear(2432, 400)
8080

representations/ccc/model.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -99,18 +99,20 @@ def fliplr(x):
9999
return x.astype(float)
100100

101101

102-
def img_loading_func(path, do_augment=False):
102+
def img_loading_func(path, do_augment=False, img_size=None):
103+
img_size = img_size or imgSize
104+
103105
img = load_image(path)
104106
# Ok, so this was fine. It was actually rgb. It was just ... distorted.
105107
ht, wd = img.size(1), img.size(2)
106108
if ht <= wd:
107109
ratio = float(wd) / float(ht)
108110
# width, height
109-
img = resize(img, int(imgSize * ratio), imgSize)
111+
img = resize(img, int(img_size * ratio), img_size)
110112
else:
111113
ratio = float(ht) / float(wd)
112114
# width, height
113-
img = resize(img, imgSize, int(imgSize * ratio))
115+
img = resize(img, img_size, int(img_size * ratio))
114116

115117
if do_augment:
116118
if random.random() > 0.5:

representations/ccc/representation.py

+2
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,9 @@
55

66

77
THUMOS_OUTPUT_DIM = 330752 # 512*32*57 # at imgSize=150 it's 330752
8+
THUMOS_OUTPUT_DIM_128 = 237568 # 512*32*57 # at imgSize=150 it's 330752
89
GYMNASTICS_OUTPUT_DIM = 933888 # 407040 ... at imgSize=150, it's 330752 ... strange?
10+
GYMNASTICS_OUTPUT_DIM_128 = 237568 # imgSize=125
911
ACTIVITYNET_OUTPUT_DIM = 184832 # 524288 ... at imgSize=150, it's 184832
1012

1113

representations/resnet/model.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import copy
22
import random
33

4+
import cv2
45
import numpy as np
56
from PIL import Image
67
import torch
@@ -45,8 +46,14 @@ def to_torch(ndarray):
4546

4647

4748
def load_image(img_path):
48-
img = np.load(img_path)
49-
img = Image.fromarray(img)
49+
img_path = str(img_path)
50+
if img_path.endswith('png'):
51+
img = cv2.imread(img_path)
52+
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
53+
img = Image.fromarray(img)
54+
elif img_path.endswith('npy'):
55+
img = np.load(img_path)
56+
img = Image.fromarray(img)
5057
return img
5158

5259

representations/resnet/representation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def __init__(self, opts):
8484
self.fc_layer = nn.Linear(2048, 400)
8585

8686
def forward(self, representation):
87-
return self.fc_layer(out)
87+
return self.fc_layer(representation)
8888

8989
# # thumosimages shape representation is [800, 64, 44, 80]
9090
# print(representation.shape)

0 commit comments

Comments
 (0)