Spaces:
Running
Running
Elle McFarlane commited on
Commit ·
15d6c34
1
Parent(s): 98de0be
add gitignore etc
Browse filesFiles changed (50)
- .gitattributesAdded+2
- .gitignoreAdded+6
- .python-versionAdded+1
- text2motion/MakefileAdded+131
- text2motion/data/GRAB/grab_all.txtAdded+1335
- text2motion/data/GRAB/grab_test.txtAdded+201
- text2motion/data/GRAB/grab_train.txtAdded+1068
- text2motion/data/GRAB/grab_val.txtAdded+66
- text2motion/data/GRAB/test.txtAdded+1
- text2motion/data/GRAB/train.txtAdded+1068
- text2motion/data/GRAB/train_long.txtAdded+8
- text2motion/data/GRAB/train_short.txtAdded+1
- text2motion/data/GRAB/train_val.txtAdded+1
- text2motion/datasets/__init__.pyAdded+16
- text2motion/datasets/combine_gifs.pyAdded+87
- text2motion/datasets/dataloader.pyAdded+128
- text2motion/datasets/dataset.pyAdded+194
- text2motion/datasets/evaluator.pyAdded+469
- text2motion/datasets/evaluator_models.pyAdded+438
- text2motion/datasets/mean_mesh.pyAdded+231
- text2motion/datasets/motionx_explorer.pyAdded+554
- text2motion/datasets/rendering.pyAdded+126
- text2motion/datasets/statistics_writer.pyAdded+56
- text2motion/datasets/train_explorer.ipynbAdded
- text2motion/datasets/utils.pyAdded+18
- text2motion/dtu_README.mdAdded+58
- text2motion/install.mdAdded+154
- text2motion/jobscript.shAdded+40
- text2motion/models/__init__.pyAdded+4
- text2motion/models/gaussian_diffusion.pyAdded+1147
- text2motion/models/transformer.pyAdded+429
- text2motion/options/base_options.pyAdded+91
- text2motion/options/evaluate_options.pyAdded+27
- text2motion/options/train_options.pyAdded+32
- text2motion/requirements.txtAdded+11
- text2motion/tools/__init__.pyAdded
- text2motion/tools/arguments.pyAdded+37
- text2motion/tools/evaluation.pyAdded+278
- text2motion/tools/inference.pyAdded+105
- text2motion/tools/train.pyAdded+134
- text2motion/utils/__init__.pyAdded
- text2motion/utils/get_opt.pyAdded+102
- text2motion/utils/metrics.pyAdded+146
- text2motion/utils/motion_process.pyAdded+515
- text2motion/utils/paramUtil.pyAdded+63
- text2motion/utils/plot_script.pyAdded+115
- text2motion/utils/quaternion.pyAdded+423
- text2motion/utils/skeleton.pyAdded+199
- text2motion/utils/utils.pyAdded+156
- text2motion/utils/word_vectorizer.pyAdded+80
12*.tar filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text123456**.gif**.pyc**.npz.vscode/demo*.ipynb13.7123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131# get git rootROOT_DIR:=$(shell git rev-parse --show-toplevel)/text2motionPYTHON_BIN:=python3EXP:=motiondiffuseSEED = 42MODEL_DIR:=checkpoints/grab/demo# MODEL_DIR:=checkpoints/grab/md_fulem_2g_excl_196_seed42EPOCH:=latestPROMPT:=a person walking happily# PROMPT:=happiness airplane passGT_FILE=s2/cubesmall_lift # ground-truthFRAMES=60MEAN_EMOTION=surprise
mean-mesh: cd $(ROOT_DIR) && vglrun ${PYTHON_BIN} -m datasets.mean_mesh \ --emotion ${MEAN_EMOTION} \ --file train.txt \
expl-train: cd ${ROOT_DIR} && ${PYTHON_BIN} -m datasets.train_explorer \
eval: cd ${ROOT_DIR} && ${PYTHON_BIN} -m tools.evaluation ${MODEL_DIR}/opt.txt \
# TODO (elmc): increase batch_size from 1 when not debugging!!train: w_stats echo "experiment name md_${EXP}_seed${SEED}" cd ${ROOT_DIR} && ${PYTHON_BIN} -m tools.train \ --name md_${EXP}_seed${SEED} \ --batch_size 128 \ --times 50 \ --num_epochs 50 \ --dataset_name grab \ --num_layers 8 \ --diffusion_steps 1000 \ --data_parallel \ --gpu_id 0 1 \ --wandb_user "elles" \ --experiment_name md_${EXP}_seed${SEED} \ --log_every 50 \ --seed ${SEED} \ --use_wandb \
# get makes model generate seq according to text and writes result to npy filegen-npy:# checkpoints/t2m/t2m_motiondiffuse/opt.txt cd ${ROOT_DIR} && ${PYTHON_BIN} -m tools.inference \ --opt_path ${MODEL_DIR}/opt.txt \ --which_epoch ${EPOCH} \ --text "${PROMPT}" \ --npy_path ${MODEL_DIR}/outputs \ --seed 42 \ --motion_length ${FRAMES} \
# put the model your trained in MODEL_DIR (set at top of file) and generate poses with it conditioned on prompt# smpl-x model then displays poses as meshes# WARNING: make sure to run 'make gen' first to generate the npy files for make genplay-gen-gif: echo "make sure to run on hpc dtu gui with graphics support and that you use 'vglrun' before python3 call!" echo "WARNING: run 'make gen' first to generate the npy files for make gen" cd $(ROOT_DIR) && vglrun ${PYTHON_BIN} -m datasets.motionx_explorer \ --model_path ${MODEL_DIR} \ --which_epoch ${EPOCH} \ --prompt "${PROMPT}" \ --display_mesh \ --save_gif \ --max_t ${FRAMES} \
play-gen-gui: echo "make sure to run on hpc dtu gui with graphics support and that you use 'vglrun' before python3 call!" echo "WARNING: run 'make infer' first to generate the npy files for make gen" cd $(ROOT_DIR) && ${PYTHON_BIN} -m datasets.motionx_explorer \ --model_path ${MODEL_DIR} \ --which_epoch ${EPOCH} \ --prompt "${PROMPT}" \ --display_mesh \ --max_t ${FRAMES} \
# smpl-x displays poses from seq_file as meshesplay-gt-gif: cd $(ROOT_DIR) && vglrun ${PYTHON_BIN} -m datasets.motionx_explorer \ --seq_file ${GT_FILE} \ --display_mesh \ --save_gif \ --max_t ${FRAMES} \
play-gt-gui: cd $(ROOT_DIR) && vglrun ${PYTHON_BIN} -m datasets.motionx_explorer \ --seq_file ${GT_FILE} \ --display_mesh \ --max_t ${FRAMES} \
gen: gen-npy play-gen-gif
aug: cd $(ROOT_DIR) && ${PYTHON_BIN} -m Motion-X.mocap-dataset-process.face_motion_augmentation \
print-data: cd $(ROOT_DIR) && ${PYTHON_BIN} -m datasets.motionx_explorer \
queue: cd ${ROOT_DIR} && bsub < jobscript.sh
w_stats: cd ${ROOT_DIR} && ${PYTHON_BIN} -m datasets.statistics_writer \
w_custom: cd ${ROOT_DIR} && ${PYTHON_BIN} -m datasets.custom_data_writer \
stat: @err_file=$$(ls -v gpu_*.err | tail -n 1); \ out_file=$$(ls -v gpu_*.out | tail -n 1); \ echo "Latest .err file: $$err_file"; \ echo "Latest .out file: $$out_file"; \
# checks gpu utilization of latest jobgpu: @err_file=$$(ls -v gpu_*.err | tail -n 1); \ err_number=$$(echo $$err_file | grep -oP 'gpu_\K\d+(?=\.err)'); \ echo "Latest .err file: $$err_file with number $$err_number"; \ bnvtop $$err_number; \
space: getquota_work3.sh
hog: du -h --max-depth=1 --apparent /work3/s222376/
env_setup: @echo "module load cuda/10.1 cudnn/v7.6.5.32-prod-cuda-10.1 gcc/5.4.0"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335s8/mug_toast_1s3/airplane_pass_1s1/lightbulb_pass_1s10/camera_takepicture_3s1/wineglass_toast_1s1/phone_lifts4/binoculars_see_1s8/teapot_pass_1s9/cubemedium_pass_1s8/elephant_lifts2/gamecontroller_play_1s6/duck_lifts4/stapler_staple_1s8/mug_drink_1s8/train_lifts1/cubesmall_offhand_1s6/cylindermedium_inspect_1s8/cylindersmall_lifts3/waterbottle_drink_1s1/wineglass_offhand_1s5/scissors_pass_1s1/cup_lifts8/binoculars_pass_1s9/hand_pass_1s7/doorknob_lifts8/spherelarge_pass_1s10/alarmclock_see_1s5/waterbottle_shake_1s5/mouse_use_1s2/cubesmall_lifts4/cubelarge_inspect_1s8/apple_eat_1s3/cylinderlarge_lift_Retakes7/mug_drink_1s8/knife_pass_1s1/flute_offhand_1s7/stapler_pass_1s6/flute_play_1s6/stapler_staple_1s3/gamecontroller_lifts9/spheresmall_pass_1s9/camera_takepicture_1s3/apple_offhand_1s4/binoculars_lifts8/fryingpan_lifts7/camera_pass_1s10/hand_shake_1s3/stamp_stamp_1s6/watch_set_2s6/wineglass_drink_1s1/cubelarge_pass_1s6/hand_inspect_1s2/torussmall_lifts1/torussmall_pass_1s3/mug_offhand_1s1/cylinderlarge_offhand_1s2/cylindermedium_inspect_1s4/stamp_stamp_1s4/mouse_use_1s8/spheremedium_lifts8/headphones_pass_1s3/gamecontroller_play_1s2/stanfordbunny_lifts10/fryingpan_cook_2s3/wineglass_pass_1s1/pyramidlarge_offhand_1s6/toothpaste_pass_1s1/mug_lifts10/waterbottle_pass_1s1/flashlight_pass_1s7/banana_lifts6/waterbottle_drink_1s1/stamp_offhand_1s1/camera_takepicture_1s10/cubesmall_inspect_1s7/alarmclock_see_1s7/gamecontroller_pass_1s8/banana_peel_1s2/camera_takepicture_2s2/cubemedium_lifts10/train_pass_1s10/cylindermedium_pass_1s6/spherelarge_lifts8/duck_inspect_1s3/mug_drink_3s6/hand_pass_1s3/headphones_use_1s5/wineglass_drink_1s10/doorknob_use_2s6/spheremedium_pass_1s5/wineglass_toast_1s5/pyramidmedium_inspect_1s10/spheremedium_inspect_1s5/bowl_drink_2s10/pyramidmedium_pass_1s9/watch_set_1s7/pyramidmedium_pass_1s5/stanfordbunny_pass_1s8/stanfordbunny_lifts7/waterbottle_open_1_Retakes9/pyramidmedium_lift_Retakes5/cubelarge_pass_1s2/stapler_staple_1s2/knife_pass_1s5/duck_inspect_1s8/wineglass_pass_1s5/spherelarge_pass_1s2/elephant_pass_1s1/spherelarge_offhand_1s4/doorknob_use_1s4/stanfordbunny_pass_1s5/piggybank_pass_1s5/banana_peel_2s10/spheremedium_lifts9/gamecontroller_pass_1s6/alarmclock_see_1s9/toruslarge_inspect_1s1/waterbottle_pass_1s7/piggybank_use_1s8/toruslarge_pass_1s1/hammer_use_1s6/stapler_offhand_1_Retakes8/toothpaste_pass_1s10/knife_peel_1s4/cylindersmall_pass_1s10/cylinderlarge_inspect_1s7/flashlight_on_2s2/cubelarge_lifts8/fryingpan_cook_1s6/wineglass_lifts1/stapler_lifts4/cup_pass_1s10/piggybank_use_1s10/binoculars_see_1s4/spheremedium_pass_1s9/bowl_drink_1s4/piggybank_use_1s5/cubesmall_inspect_1s7/stamp_stamp_1s3/scissors_use_2s10/torusmedium_inspect_1s7/hand_inspect_1s5/cylindermedium_inspect_1s8/banana_eat_1s7/binoculars_see_1s4/spheresmall_pass_1s4/cylinderlarge_lifts9/waterbottle_shake_1s4/hand_inspect_1s7/spherelarge_lifts2/flashlight_on_1s10/duck_pass_1s9/bowl_pass_1s1/mouse_lifts9/watch_pass_1s2/phone_call_1s6/cylinderlarge_inspect_1s3/wineglass_drink_2s10/toothpaste_pass_1s10/fryingpan_cook_1s8/watch_lifts9/pyramidlarge_inspect_1s2/mouse_use_1s6/pyramidmedium_pass_1s4/mouse_pass_1s6/wineglass_toast_1s1/watch_lifts9/hand_inspect_1s1/airplane_lifts9/mouse_lifts6/eyeglasses_clean_1s4/waterbottle_drink_1s4/torussmall_lifts6/binoculars_lifts8/bowl_offhand_1s2/eyeglasses_pass_1s8/fryingpan_cook_2s8/spherelarge_lifts1/cylindermedium_pass_1s1/banana_eat_1s10/gamecontroller_pass_1s9/camera_browse_1s6/eyeglasses_wear_1s1/stanfordbunny_lifts6/cylindersmall_inspect_1s6/elephant_pass_1s3/torusmedium_inspect_1s8/spheresmall_pass_1s6/apple_offhand_1_Retakes6/stanfordbunny_pass_1s6/mug_drink_2s8/mug_lifts1/binoculars_see_1s1/torussmall_offhand_1s9/duck_pass_1s8/cubemedium_offhand_1s8/spherelarge_inspect_1s7/wineglass_pass_1s9/toothpaste_squeeze_1s10/scissors_pass_1s10/torussmall_inspect_1s4/wineglass_lifts5/binoculars_pass_1s7/stanfordbunny_pass_1s1/mug_drink_1s1/stamp_pass_1s8/piggybank_use_1s10/spheremedium_pass_1s9/torusmedium_pass_1s3/mouse_lifts1/cylindermedium_inspect_1s8/cylindermedium_pass_1s7/cubesmall_pass_1s6/cylindermedium_lifts7/cup_pour_1s9/banana_pass_1s1/camera_browse_1s3/eyeglasses_clean_1s1/doorknob_use_fun_1s1/banana_lifts6/cylindersmall_pass_1s5/elephant_lifts5/elephant_inspect_1s9/waterbottle_lifts6/piggybank_lift_Retakes5/camera_takepicture_3s4/stapler_staple_2s1/cylindersmall_lifts1/airplane_offhand_1s9/apple_pass_1s9/cylindermedium_pass_1s9/hammer_use_3s7/cubemedium_pass_1s6/cubemedium_inspect_1s2/mug_lifts6/phone_lifts4/spherelarge_inspect_1s1/elephant_inspect_1s4/headphones_pass_1s8/binoculars_see_1s7/pyramidmedium_inspect_1s1/toothpaste_lifts4/stamp_lifts8/eyeglasses_pass_1s7/hand_pass_1s10/spherelarge_lifts2/stapler_pass_1s9/banana_peel_1s2/mug_pass_1s6/stapler_pass_1s10/wineglass_drink_1s10/lightbulb_screw_1s7/spheresmall_pass_1s2/stanfordbunny_inspect_1s7/piggybank_pass_1s8/mug_pass_1s10/torussmall_lifts8/cup_pour_1s5/pyramidlarge_pass_1s1/binoculars_pass_1s5/hammer_pass_1s1/flashlight_offhand_1s7/elephant_pass_1s6/hand_lifts1/cubelarge_offhand_1s9/elephant_lifts8/banana_peel_2s8/knife_peel_1s1/teapot_pass_1s10/headphones_pass_1s2/toothbrush_lifts9/knife_pass_1s2/cubemedium_inspect_1s8/teapot_lifts3/pyramidmedium_pass_1s2/cylindermedium_lifts4/mug_pass_1s10/stamp_lifts7/airplane_lift_Retakes10/toruslarge_pass_1s6/fryingpan_pass_1s4/train_play_1s5/pyramidmedium_pass_1s7/binoculars_pass_1s1/phone_call_1s2/spheresmall_inspect_1s3/apple_lifts6/hammer_use_3s8/toothbrush_pass_1s7/spheresmall_inspect_1s10/flashlight_on_1s9/elephant_inspect_1s4/elephant_pass_1s1/bowl_drink_1s6/cubemedium_pass_1s7/eyeglasses_pass_1s8/airplane_fly_1s3/alarmclock_lifts4/doorknob_lifts4/fryingpan_cook_2s4/toothbrush_pass_1s5/cylinderlarge_pass_1s2/banana_eat_1s5/stamp_stamp_1s1/knife_lifts10/hand_pass_1s4/bowl_drink_2s8/cup_pass_1s5/hammer_use_1s3/train_lifts2/cup_pass_1s7/torussmall_pass_1s8/hand_pass_1s10/cup_drink_2s3/toothpaste_lifts2/fryingpan_pass_1s3/cylindersmall_pass_1s5/spheremedium_lifts10/apple_eat_1s4/teapot_pour_2s4/torussmall_pass_1s5/toothpaste_pass_1s7/headphones_pass_1s5/camera_pass_1s9/elephant_pass_1s6/toothpaste_lifts8/flute_pass_1s4/spheremedium_lifts3/binoculars_see_1s10/camera_browse_1s1/banana_pass_1s1/toruslarge_lifts6/cubelarge_inspect_1s1/pyramidlarge_pass_1s2/teapot_pour_1s3/waterbottle_pass_1s2/hammer_lifts9/apple_lifts9/waterbottle_pour_1s4/cubemedium_lifts9/phone_pass_1s5/cubemedium_lifts4/gamecontroller_pass_1s9/cubemedium_inspect_1s3/cup_drink_1s4/stapler_lifts2/apple_pass_1s5/mug_toast_1s5/cylindersmall_inspect_1s3/cup_lifts1/hammer_pass_1s10/hammer_lifts5/elephant_pass_1s1/spheresmall_inspect_1s3/toothbrush_brush_1s7/apple_eat_1s7/pyramidlarge_lifts7/wineglass_drink_1s7/mug_lifts6/cubesmall_offhand_1s2/camera_lifts1/cubemedium_lifts10/gamecontroller_lifts9/cylinderlarge_pass_1s8/cubelarge_inspect_1s1/scissors_pass_1s1/train_play_1s5/stanfordbunny_inspect_1s4/spheresmall_lifts4/watch_lifts9/cylinderlarge_inspect_1s2/hand_inspect_1s8/toothpaste_squeeze_1s8/toothpaste_squeeze_2s8/mouse_use_1s2/teapot_pass_1s7/cup_pass_1s9/spheremedium_inspect_1s10/gamecontroller_play_1s7/apple_lifts6/eyeglasses_lifts10/flute_pass_1s9/airplane_fly_1s5/stamp_pass_1s5/alarmclock_lifts10/hammer_use_3s3/cylindersmall_inspect_1s10/alarmclock_pass_1s9/waterbottle_drink_1s10/banana_pass_1s6/watch_pass_1s1/banana_peel_2s8/pyramidmedium_pass_1s7/cubemedium_lifts6/cup_drink_2s4/cubelarge_pass_1s1/bowl_pass_1s8/wineglass_drink_2s8/phone_call_1s8/torusmedium_lifts4/piggybank_pass_1s9/stamp_pass_1s10/hammer_use_2s9/wineglass_pass_1s8/camera_browse_1s7/airplane_pass_1s6/cup_pass_1s6/airplane_pass_1s9/torussmall_pass_1s8/teapot_pour_2s4/mouse_use_2s10/flashlight_on_2s7/pyramidsmall_pass_1s3/cup_pour_1s1/piggybank_pass_1s5/cubesmall_pass_1s10/airplane_fly_1s8/cylinderlarge_offhand_1s6/gamecontroller_play_1s3/stanfordbunny_pass_1s7/stanfordbunny_lifts9/banana_peel_2s2/apple_lifts10/waterbottle_pour_1s1/alarmclock_pass_1s1/hammer_use_3s1/eyeglasses_clean_1s6/phone_call_1s7/banana_eat_1s4/waterbottle_shake_1s8/waterbottle_pass_1s6/cylinderlarge_lifts9/hand_shake_1s6/camera_browse_1s2/camera_browse_1s4/phone_pass_1s1/stamp_lifts7/torussmall_inspect_1s1/cylindersmall_offhand_1s7/cylinderlarge_lifts2/duck_inspect_1s7/spheremedium_pass_1s8/toruslarge_lifts3/hammer_pass_1s3/cup_offhand_1s2/headphones_use_1s2/train_play_1s10/scissors_use_1s5/cubesmall_lifts10/pyramidsmall_inspect_1s3/mug_drink_4s1/cubemedium_offhand_1s6/apple_eat_1s1/doorknob_use_2s1/cylinderlarge_lifts2/hand_lifts5/gamecontroller_lifts3/waterbottle_lifts3/apple_pass_1s10/flute_play_1s5/spherelarge_inspect_1s7/doorknob_use_1s8/torusmedium_pass_1s4/bowl_pass_1s10/headphones_lifts6/pyramidlarge_pass_1s2/mug_toast_1s4/hammer_use_3s1/stanfordbunny_inspect_1s3/alarmclock_pass_1s8/cylindermedium_inspect_1s1/elephant_lifts6/waterbottle_pass_1s8/cubelarge_lifts3/camera_takepicture_1s5/torussmall_inspect_1s2/airplane_fly_1s7/hammer_use_1s1/spherelarge_lifts1/cubemedium_pass_1s2/headphones_lifts8/piggybank_lifts1/apple_lifts3/spherelarge_inspect_1s8/banana_pass_1s8/stanfordbunny_pass_1s4/flute_play_1s6/banana_eat_1s1/scissors_offhand_1s1/binoculars_lifts10/cup_lifts7/eyeglasses_lifts3/stapler_lifts7/bowl_drink_1s1/cup_drink_1s4/alarmclock_lifts6/headphones_use_1s4/apple_lifts6/mouse_pass_1s7/flashlight_lifts5/torusmedium_inspect_1s10/cup_pour_1s5/toruslarge_lifts10/cup_drink_1s7/cylinderlarge_pass_1s4/wineglass_drink_1s1/stapler_staple_2s10/mug_drink_1s1/flute_pass_1s8/cylinderlarge_lifts10/piggybank_pass_1s7/duck_inspect_1s9/stamp_lifts6/bowl_lifts6/banana_pass_1s9/cubemedium_lifts7/flute_pass_1s8/eyeglasses_wear_1s9/flashlight_lifts9/hammer_use_2s1/cup_pour_1s2/piggybank_lifts8/pyramidlarge_inspect_1s2/teapot_pour_2s6/pyramidsmall_inspect_2s1/toothpaste_pass_1s10/banana_peel_2s1/wineglass_pass_1s5/pyramidlarge_inspect_1s5/cubemedium_inspect_1s7/knife_chop_1s6/mug_toast_1s5/mug_drink_1s6/banana_peel_1s7/cylindermedium_pass_1s10/mug_drink_2s3/elephant_offhand_1s4/stapler_pass_1s1/torussmall_lifts1/duck_lifts5/flute_play_1s1/airplane_fly_1s2/headphones_pass_1s3/lightbulb_screw_1s8/toothbrush_brush_1s10/mouse_use_1s5/flute_play_2s3/waterbottle_pour_2s10/airplane_lifts7/eyeglasses_wear_1s10/stamp_stamp_1s8/cup_drink_1s4/alarmclock_pass_1s3/train_pass_1s2/hammer_use_2s1/pyramidsmall_inspect_1s9/cubesmall_inspect_1s7/camera_browse_1s10/spheresmall_pass_1s1/phone_offhand_1s6/waterbottle_shake_1s1/alarmclock_offhand_1s8/spheresmall_inspect_1s9/cylindermedium_inspect_1s6/knife_lifts6/mouse_lifts1/flashlight_lifts9/cubelarge_pass_1s2/pyramidlarge_pass_1_Retakes7/stanfordbunny_inspect_1s9/gamecontroller_play_1s4/hand_pass_1s3/toothpaste_squeeze_1s9/duck_lifts5/flashlight_on_1s5/cup_lifts10/waterbottle_drink_1s8/cubesmall_pass_1s10/train_lifts10/spheresmall_inspect_1s10/cup_pass_1s1/cubesmall_pass_1s4/fryingpan_cook_3s6/elephant_inspect_1s9/stapler_lifts1/pyramidmedium_offhand_1s9/pyramidmedium_pass_1s9/teapot_pour_2s4/fryingpan_cook_1s1/eyeglasses_wear_1s1/gamecontroller_play_1s3/binoculars_offhand_1s6/waterbottle_pour_1s3/cubesmall_inspect_1s8/pyramidlarge_pass_1s2/train_pass_1s10/mouse_lifts10/torusmedium_pass_1s8/waterbottle_drink_1s7/cubelarge_lifts5/duck_pass_1s1/gamecontroller_offhand_1s2/camera_pass_1s7/gamecontroller_play_1s7/toothbrush_pass_1s8/phone_pass_1s3/bowl_drink_1s6/toruslarge_pass_1s5/spheresmall_inspect_1s8/flashlight_pass_1s1/flashlight_on_2s8/gamecontroller_lifts3/stanfordbunny_lifts8/bowl_pass_1s4/banana_pass_1s6/stapler_lifts2/teapot_lifts3/camera_takepicture_2s8/torussmall_pass_1s9/camera_pass_1s4/apple_eat_1s1/watch_set_1s5/stanfordbunny_lifts6/spheremedium_inspect_1s1/eyeglasses_lifts10/headphones_use_1s3/doorknob_use_1s10/apple_pass_1s9/flute_pass_1s1/toruslarge_inspect_1s5/duck_lifts9/doorknob_use_2s10/torussmall_pass_1s2/doorknob_use_2s1/pyramidlarge_lifts6/stamp_lifts3/elephant_pass_1s7/headphones_use_1s6/cylindermedium_pass_1s6/stapler_staple_2s6/piggybank_pass_1s5/spheremedium_inspect_1s1/cubemedium_inspect_1s4/pyramidmedium_pass_1s7/cylinderlarge_inspect_1s1/cylindermedium_offhand_1s6/toothpaste_squeeze_1_Retakes9/stapler_pass_1s8/flashlight_on_1s5/cup_drink_2s8/apple_lifts8/airplane_pass_1s6/wineglass_pass_1s4/cylinderlarge_inspect_1s4/phone_call_1s5/stapler_pass_1s8/camera_takepicture_2s3/mouse_pass_1s7/pyramidlarge_inspect_1s10/stapler_staple_2s9/teapot_pass_1s5/gamecontroller_play_1s4/train_lifts8/doorknob_lifts1/watch_offhand_1s7/mug_drink_2s4/flashlight_pass_1s1/mug_offhand_1s4/camera_takepicture_3s8/train_pass_1s7/train_pass_1s8/gamecontroller_play_1s1/scissors_use_2s9/piggybank_pass_1s6/flute_lifts1/banana_peel_1s6/bowl_pass_1s1/mouse_pass_1s6/cubesmall_lifts5/airplane_lifts3/scissors_pass_1s2/cylinderlarge_pass_1s6/watch_set_1s10/stamp_pass_1s9/banana_lifts3/toruslarge_lifts10/hammer_use_1s10/cubesmall_lifts6/teapot_pass_1s3/pyramidlarge_offhand_1s8/cylindersmall_inspect_1s3/cylinderlarge_inspect_1s7/teapot_pass_1s9/mouse_pass_1s3/mug_drink_1s2/spheremedium_pass_1s9/waterbottle_pass_1s2/flute_pass_1s9/lightbulb_screw_1s8/cubemedium_pass_1s7/flashlight_pass_1s9/eyeglasses_lifts7/cubemedium_inspect_1s5/waterbottle_lifts6/cup_drink_1s1/pyramidlarge_inspect_1s3/airplane_fly_1s10/pyramidmedium_lifts10/bowl_lifts2/cubelarge_pass_1s7/stapler_staple_1s8/flashlight_on_2s4/cylindersmall_lifts10/stanfordbunny_pass_1s6/cubemedium_lifts10/stapler_pass_1s5/apple_pass_1s7/doorknob_use_2s4/watch_pass_1s1/elephant_pass_1s1/watch_set_2s2/cylinderlarge_inspect_1s2/pyramidlarge_inspect_1s9/eyeglasses_wear_1s4/phone_lifts1/spheremedium_lifts3/airplane_offhand_1s6/spheresmall_pass_1s9/piggybank_lift_Retakes8/cylinderlarge_inspect_1s5/wineglass_lifts3/train_play_1s10/knife_chop_1s9/wineglass_drink_2s6/hammer_lifts9/cylindersmall_pass_1s4/bowl_drink_1s1/mug_toast_1s1/pyramidmedium_inspect_1s9/stamp_stamp_1s10/toothpaste_squeeze_1s1/spheresmall_lifts3/doorknob_use_2s7/fryingpan_cook_1s5/teapot_pass_1s8/phone_lifts2/cubesmall_inspect_1s1/toruslarge_pass_1s6/headphones_pass_1s8/cylinderlarge_pass_1s4/toothpaste_pass_1s4/camera_takepicture_2s3/camera_offhand_1s8/cup_offhand_1s9/spherelarge_pass_1s10/stanfordbunny_lifts1/spheremedium_offhand_1s4/torusmedium_lifts9/cylinderlarge_lifts6/hammer_use_1s4/wineglass_toast_1s2/cylinderlarge_lifts6/cubesmall_inspect_1s1/camera_takepicture_2s3/phone_pass_1s1/hand_inspect_1s8/bowl_drink_2s1/stapler_offhand_1s1/piggybank_use_1s1/apple_pass_1s9/wineglass_drink_1s10/mug_lifts10/cylinderlarge_lifts2/stamp_stamp_1s10/stanfordbunny_inspect_1s4/cubelarge_lifts8/alarmclock_see_1s5/cubelarge_lifts3/eyeglasses_pass_1s1/pyramidsmall_pass_1s2/cylindermedium_pass_1s8/fryingpan_offhand_1s1/mug_drink_3s2/piggybank_pass_1_Retakes8/headphones_lifts9/alarmclock_see_1s5/toruslarge_pass_1s1/stapler_staple_1s1/stanfordbunny_offhand_1s3/airplane_lifts8/cubemedium_inspect_1s9/stapler_staple_2s3/fryingpan_lifts10/spherelarge_inspect_1s7/pyramidlarge_pass_1s5/mouse_lifts8/watch_set_2s3/wineglass_drink_1s6/spheremedium_lifts2/stapler_staple_2s9/airplane_pass_1s6/duck_inspect_1s10/lightbulb_pass_1s8/stapler_pass_1s6/camera_takepicture_3s10/camera_takepicture_2s10/mouse_pass_1s3/cup_drink_2s5/alarmclock_see_1s10/elephant_inspect_1s6/apple_pass_1s3/gamecontroller_pass_1s10/cubemedium_pass_1s5/wineglass_pass_1s5/waterbottle_pass_1s10/teapot_pour_2s6/train_pass_1s7/hammer_use_2s8/apple_pass_1s6/cup_pour_1s7/wineglass_lifts9/toothbrush_pass_1s6/doorknob_lifts9/banana_eat_1s4/cylinderlarge_pass_1s10/cubelarge_lifts1/camera_lifts1/stanfordbunny_pass_1s7/watch_pass_1s9/cup_lifts7/apple_pass_1s3/piggybank_pass_1s1/cylindersmall_inspect_1s4/cup_drink_2s8/spheremedium_pass_1s6/waterbottle_open_1s3/watch_set_1s8/cubesmall_inspect_1s3/duck_inspect_1s7/cylindermedium_inspect_1s9/cylindersmall_inspect_1s1/spherelarge_inspect_1s1/spheresmall_offhand_1s8/cylindermedium_lifts1/bowl_drink_2s5/train_pass_1s4/alarmclock_see_1s8/flashlight_offhand_1s2/cup_drink_1s8/duck_lifts6/cubelarge_pass_1s6/flute_pass_1s2/toruslarge_inspect_1s4/camera_pass_1s7/train_play_1s9/mouse_use_1s5/cylindermedium_pass_1s3/pyramidsmall_pass_1s3/eyeglasses_offhand_1s8/wineglass_toast_1s7/eyeglasses_clean_1s5/toothbrush_brush_1s10/toothpaste_squeeze_2s1/flute_lifts3/toothbrush_pass_1s1/bowl_lifts9/bowl_drink_2s7/banana_peel_2s8/doorknob_use_2s8/torussmall_inspect_1s1/camera_pass_1s8/hand_inspect_1s1/watch_pass_1s10/watch_pass_1s3/toruslarge_inspect_1s9/torusmedium_inspect_1s9/cylindermedium_lifts10/teapot_pass_1s6/wineglass_drink_2s7/headphones_lifts10/stapler_staple_1s2/pyramidmedium_inspect_1s3/flashlight_pass_1s1/torusmedium_pass_1s6/spherelarge_pass_1s2/phone_pass_1s2/pyramidmedium_pass_1s9/stanfordbunny_pass_1s8/pyramidmedium_inspect_1s1/toothbrush_lifts7/hammer_pass_1s8/hand_lifts8/camera_takepicture_3s8/stamp_lifts8/torusmedium_inspect_1s7/phone_call_1s3/pyramidlarge_inspect_1s6/torussmall_pass_1s3/mouse_use_1s6/toruslarge_inspect_1s3/elephant_lifts1/wineglass_drink_2s7/lightbulb_pass_1s8/hammer_pass_1s6/pyramidmedium_inspect_1s8/gamecontroller_pass_1s1/waterbottle_pour_1s9/toothpaste_lifts9/spherelarge_inspect_1s8/teapot_pour_1s4/spheremedium_inspect_1s6/stamp_stamp_1s9/hammer_use_1s1/torusmedium_offhand_1s1/alarmclock_see_1s6/phone_pass_1s5/waterbottle_open_1s4/cubemedium_pass_1s6/apple_lifts1/headphones_pass_1s8/hammer_use_3s3/piggybank_use_1s3/wineglass_toast_1s6/spheresmall_lifts1/camera_takepicture_3_Retakes1/cylindermedium_lifts6/teapot_pour_1s4/train_pass_1s7/toruslarge_inspect_1_Retakes8/cubelarge_pass_1s3/alarmclock_offhand_1s4/hand_lifts8/mug_drink_2s5/cup_pass_1s3/stapler_staple_1s10/phone_lifts6/torusmedium_inspect_1s4/cup_drink_1s2/train_lifts8/stapler_staple_1s2/apple_eat_1s6/torusmedium_pass_1s4/watch_set_1s3/camera_takepicture_3s9/spheresmall_inspect_1s4/cubesmall_pass_1s6/alarmclock_lifts2/toruslarge_pass_1s9/pyramidmedium_inspect_1s3/stanfordbunny_inspect_1s6/scissors_use_2s1/stamp_stamp_1s3/torusmedium_pass_1s6/eyeglasses_pass_1s7/cubelarge_inspect_1s3/stamp_lifts8/mouse_pass_1s7/elephant_inspect_1s8/camera_pass_1s10/bowl_pass_1s1/waterbottle_lifts8/bowl_lifts3/phone_call_1s8/phone_offhand_1s3/eyeglasses_wear_1s6/bowl_drink_1_Retakes9/torussmall_inspect_1s1/piggybank_offhand_1s1/mug_drink_2s4/airplane_fly_1s8/cubelarge_offhand_1s10/camera_pass_1s4/stanfordbunny_inspect_1s6/pyramidlarge_inspect_1s10/wineglass_drink_2s1/duck_inspect_1s4/duck_inspect_1s1/mouse_use_1s5/eyeglasses_clean_2s10/camera_takepicture_1s8/fryingpan_pass_1s10/cubelarge_inspect_1s7/hammer_use_3s5/spherelarge_lifts1/fryingpan_cook_1s5/cubemedium_pass_1s3/flute_play_1s9/headphones_use_1s1/cylinderlarge_inspect_1s7/hammer_lifts7/wineglass_toast_1s4/pyramidmedium_inspect_1s10/bowl_drink_1_Retakes9/piggybank_use_1s1/cubesmall_lifts1/fryingpan_cook_2s1/apple_eat_1s9/watch_set_2s9/bowl_lifts10/hand_lifts10/cylindersmall_inspect_1s1/piggybank_lifts2/toothpaste_squeeze_1s6/binoculars_see_1s6/spherelarge_inspect_1s8/alarmclock_lifts1/cylindersmall_pass_1s6/pyramidlarge_lifts4/binoculars_pass_1s10/bowl_drink_2s5/flute_pass_1s10/torusmedium_lifts1/duck_pass_1s2/cubelarge_inspect_1s8/watch_pass_1s1/waterbottle_open_1s9/flute_play_1s9/airplane_lifts1/mug_drink_4s4/wineglass_pass_1s6/camera_pass_1s4/duck_pass_1s10/cylindersmall_pass_1s10/alarmclock_lift_Retakes4/toruslarge_pass_1s10/wineglass_pass_1s5/cylindermedium_lifts2/pyramidlarge_lifts3/flute_offhand_1s8/camera_offhand_1s2/elephant_inspect_1s5/mug_pass_1s3/hammer_use_1s9/mug_drink_2s5/wineglass_drink_2s5/piggybank_lifts9/waterbottle_open_1s7/alarmclock_lifts1/eyeglasses_offhand_1s1/flute_play_1s8/wineglass_lifts7/waterbottle_shake_1s1/cubelarge_inspect_1s1/hammer_use_2s5/doorknob_lifts1/spheremedium_inspect_1s9/spheremedium_pass_1s6/knife_peel_1s4/fryingpan_pass_1s3/binoculars_lifts7/toruslarge_lifts4/piggybank_lifts3/cubelarge_pass_1s2/banana_peel_1s1/alarmclock_lifts5/train_lifts1/cup_pass_1s1/waterbottle_drink_1s3/bowl_drink_2s5/cylinderlarge_inspect_1s4/headphones_use_1s3/hand_pass_1s3/flashlight_on_1s3/toruslarge_pass_1s9/flashlight_on_1s8/mug_offhand_1s8/cubesmall_lifts10/airplane_pass_1s4/stanfordbunny_lifts3/cubelarge_offhand_1s2/stanfordbunny_pass_1s5/bowl_drink_1s3/knife_lifts8/fryingpan_cook_3s7/stamp_pass_1s10/hammer_pass_1s1/phone_pass_1s6/teapot_pour_2s2/mug_drink_2s8/spheresmall_lifts7/banana_pass_1s4/cup_lifts5/train_play_1s6/airplane_lifts3/spheremedium_inspect_1s1/hand_offhand_1s3/camera_pass_1s7/bowl_pass_1s6/mug_pass_1s7/binoculars_lifts8/hammer_lifts1/waterbottle_offhand_1s3/cylindermedium_pass_1s7/waterbottle_drink_1s7/spheremedium_inspect_1s10/banana_eat_1s2/spherelarge_lifts1/duck_offhand_2s6/doorknob_use_2s6/cylinderlarge_pass_1s9/camera_lifts1/eyeglasses_pass_1s3/cylinderlarge_pass_1s10/elephant_pass_1s4/scissors_pass_1s3/cubemedium_inspect_1s6/stamp_pass_1s9/mug_pass_1s10/phone_pass_1s7/mouse_pass_1s3/scissors_use_1s6/airplane_fly_1s8/lightbulb_pass_1s2/toruslarge_lifts8/stapler_lifts5/piggybank_use_1s6/banana_peel_2s10/doorknob_lifts8/stamp_pass_1s5/hand_pass_1s5/bowl_pass_1s3/pyramidlarge_pass_1s6/camera_lifts9/duck_inspect_1s3/cubelarge_lifts4/watch_set_2s5/cylinderlarge_lifts2/toothpaste_lifts8/knife_chop_1s1/flashlight_on_1s10/mug_pass_1s1/gamecontroller_lifts1/airplane_pass_1s7/cylindersmall_pass_1s7/cup_drink_1s7/piggybank_lifts9/lightbulb_pass_1s7/flashlight_on_1s5/binoculars_see_1s1/headphones_use_1s5/cubelarge_inspect_1s7/cubelarge_pass_1s9/toothpaste_pass_1s7/spherelarge_pass_1s10/banana_peel_1s6/stapler_staple_1_Retakes8/wineglass_drink_1s9/eyeglasses_pass_1s6/mug_lifts5/phone_pass_1s9/torussmall_lifts5/hand_inspect_1s1/cubelarge_lifts10/cubesmall_pass_1s7/banana_peel_1s3/watch_pass_1s2/banana_pass_1s8/duck_pass_1s7/waterbottle_pass_1s6/bowl_drink_1s1/teapot_pour_1s9/pyramidlarge_pass_1s3/mug_drink_2s10/spherelarge_pass_1s6/alarmclock_pass_1s6/hammer_use_2s9/cubesmall_pass_1s7/mouse_use_1s10/wineglass_lifts3/alarmclock_see_1s5/mouse_pass_1s8/doorknob_use_1s8/stamp_stamp_1s2/mug_drink_1s8/hammer_use_2s3/spherelarge_pass_1s2/flashlight_on_2s4/elephant_inspect_1s3/wineglass_lifts3/cup_pass_1s6/doorknob_use_1s1/torussmall_inspect_1s10/toruslarge_lifts6/cup_lifts9/alarmclock_lifts9/apple_eat_1s3/spheresmall_pass_1s6/flashlight_on_1s10/binoculars_lifts9/hammer_pass_1s1/doorknob_use_1s3/mug_pass_1s1/apple_offhand_1s9/doorknob_lifts7/gamecontroller_lifts9/cubelarge_lifts5/alarmclock_pass_1s9/cup_pass_1s4/apple_pass_1s8/elephant_inspect_1s6/toruslarge_lifts4/airplane_pass_1s8/bowl_drink_1s9/flashlight_pass_1s2/spherelarge_inspect_1s6/toothpaste_squeeze_2s8/stanfordbunny_inspect_1s7/cylindersmall_inspect_1s1/spheremedium_pass_1s8/train_play_1s8/elephant_pass_1s9/binoculars_pass_1s7/spherelarge_inspect_1s4/hammer_use_2s3/stapler_pass_1s3/cylindermedium_lifts7/camera_takepicture_3s9/stanfordbunny_inspect_1s3/mouse_offhand_1s8/cup_lifts1/pyramidmedium_lifts3/pyramidmedium_inspect_1s4/mug_drink_2s1/camera_offhand_1s8/cubesmall_offhand_1s1/pyramidmedium_pass_1s6/flashlight_on_2s1/torusmedium_inspect_1s8/stapler_staple_2s8/alarmclock_pass_1s8/mouse_lifts8/piggybank_pass_1s10/mug_toast_1s6/hammer_pass_1s2/hammer_use_1s4/waterbottle_pour_1s5/flashlight_on_2s8/hammer_use_1s7/train_lifts8/waterbottle_lifts1/wineglass_lifts5/gamecontroller_pass_1s3/toothpaste_pass_1s10/train_play_1s4/hammer_use_1s1/spherelarge_pass_1s10/wineglass_toast_1s9/cup_drink_1s1/torusmedium_lifts7/pyramidsmall_inspect_1s5/banana_pass_1s6/duck_pass_1s2/spherelarge_pass_1s10/cubemedium_inspect_1s1/binoculars_offhand_1s1/elephant_offhand_1s1/mug_pass_1s1/toothpaste_squeeze_1s5/airplane_pass_1s1/hand_pass_1s2/eyeglasses_clean_1s9/cubelarge_inspect_1s10/hand_inspect_1s7/phone_pass_1s6/gamecontroller_lifts8/toothpaste_lifts1/banana_offhand_1s4/spherelarge_lifts5/cylindersmall_pass_1s4/pyramidlarge_pass_1s10/cylindermedium_inspect_1s10/phone_call_1s6/flashlight_pass_1s6/train_play_1s10/binoculars_pass_1s10/eyeglasses_wear_1s1/mouse_offhand_1s4/camera_lifts6/gamecontroller_pass_1s2/scissors_use_1s6/stanfordbunny_inspect_1s2/cubesmall_pass_1s5/binoculars_lifts5/torusmedium_pass_1s3/stamp_pass_1s5/spheremedium_pass_1s8/flute_play_1s5/watch_pass_1s6/cubesmall_pass_1s5/cup_pour_1s4/stamp_pass_1s3/hammer_use_2s10/cubemedium_lifts10/pyramidmedium_inspect_1s8/cubemedium_lifts1/train_offhand_1s4/wineglass_drink_2s10/stapler_lifts4/torusmedium_inspect_1s2/piggybank_use_1s10/toothpaste_lifts2/gamecontroller_pass_1s8/banana_lifts10/cubelarge_pass_1s9/eyeglasses_clean_1s10/knife_pass_1s6/camera_takepicture_1s9/wineglass_toast_1_Retakes1/cubesmall_inspect_1s4/cup_pour_1s10/teapot_pour_1s1/stapler_pass_1s3/apple_eat_1s9/alarmclock_pass_1s7/wineglass_drink_2s1/cylinderlarge_pass_1s1/spheresmall_pass_1s10/banana_lifts7/camera_takepicture_2s8/scissors_pass_1s6/binoculars_pass_1s4/spherelarge_pass_1s1/headphones_offhand_1s10/toruslarge_inspect_1s10/cylinderlarge_pass_1s1/duck_offhand_1s10/doorknob_use_1s7/duck_pass_1s2/mouse_pass_1s10/pyramidlarge_pass_1s4/cubemedium_inspect_1s8/toruslarge_inspect_1s1/cup_drink_2s2/cylindersmall_pass_1s6/camera_takepicture_2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201s7/cup_drink_1s7/piggybank_lifts9/lightbulb_pass_1s7/flashlight_on_1s5/binoculars_see_1s1/headphones_use_1s5/cubelarge_inspect_1s7/cubelarge_pass_1s9/toothpaste_pass_1s7/spherelarge_pass_1s10/banana_peel_1s6/stapler_staple_1_Retakes8/wineglass_drink_1s9/eyeglasses_pass_1s6/mug_lifts5/phone_pass_1s9/torussmall_lifts5/hand_inspect_1s1/cubelarge_lifts10/cubesmall_pass_1s7/banana_peel_1s3/watch_pass_1s2/banana_pass_1s8/duck_pass_1s7/waterbottle_pass_1s6/bowl_drink_1s1/teapot_pour_1s9/pyramidlarge_pass_1s3/mug_drink_2s10/spherelarge_pass_1s6/alarmclock_pass_1s6/hammer_use_2s9/cubesmall_pass_1s7/mouse_use_1s10/wineglass_lifts3/alarmclock_see_1s5/mouse_pass_1s8/doorknob_use_1s8/stamp_stamp_1s2/mug_drink_1s8/hammer_use_2s3/spherelarge_pass_1s2/flashlight_on_2s4/elephant_inspect_1s3/wineglass_lifts3/cup_pass_1s6/doorknob_use_1s1/torussmall_inspect_1s10/toruslarge_lifts6/cup_lifts9/alarmclock_lifts9/apple_eat_1s3/spheresmall_pass_1s6/flashlight_on_1s10/binoculars_lifts9/hammer_pass_1s1/doorknob_use_1s3/mug_pass_1s1/apple_offhand_1s9/doorknob_lifts7/gamecontroller_lifts9/cubelarge_lifts5/alarmclock_pass_1s9/cup_pass_1s4/apple_pass_1s8/elephant_inspect_1s6/toruslarge_lifts4/airplane_pass_1s8/bowl_drink_1s9/flashlight_pass_1s2/spherelarge_inspect_1s6/toothpaste_squeeze_2s8/stanfordbunny_inspect_1s7/cylindersmall_inspect_1s1/spheremedium_pass_1s8/train_play_1s8/elephant_pass_1s9/binoculars_pass_1s7/spherelarge_inspect_1s4/hammer_use_2s3/stapler_pass_1s3/cylindermedium_lifts7/camera_takepicture_3s9/stanfordbunny_inspect_1s3/mouse_offhand_1s8/cup_lifts1/pyramidmedium_lifts3/pyramidmedium_inspect_1s4/mug_drink_2s1/camera_offhand_1s8/cubesmall_offhand_1s1/pyramidmedium_pass_1s6/flashlight_on_2s1/torusmedium_inspect_1s8/stapler_staple_2s8/alarmclock_pass_1s8/mouse_lifts8/piggybank_pass_1s10/mug_toast_1s6/hammer_pass_1s2/hammer_use_1s4/waterbottle_pour_1s5/flashlight_on_2s8/hammer_use_1s7/train_lifts8/waterbottle_lifts1/wineglass_lifts5/gamecontroller_pass_1s3/toothpaste_pass_1s10/train_play_1s4/hammer_use_1s1/spherelarge_pass_1s10/wineglass_toast_1s9/cup_drink_1s1/torusmedium_lifts7/pyramidsmall_inspect_1s5/banana_pass_1s6/duck_pass_1s2/spherelarge_pass_1s10/cubemedium_inspect_1s1/binoculars_offhand_1s1/elephant_offhand_1s1/mug_pass_1s1/toothpaste_squeeze_1s5/airplane_pass_1s1/hand_pass_1s2/eyeglasses_clean_1s9/cubelarge_inspect_1s10/hand_inspect_1s7/phone_pass_1s6/gamecontroller_lifts8/toothpaste_lifts1/banana_offhand_1s4/spherelarge_lifts5/cylindersmall_pass_1s4/pyramidlarge_pass_1s10/cylindermedium_inspect_1s10/phone_call_1s6/flashlight_pass_1s6/train_play_1s10/binoculars_pass_1s10/eyeglasses_wear_1s1/mouse_offhand_1s4/camera_lifts6/gamecontroller_pass_1s2/scissors_use_1s6/stanfordbunny_inspect_1s2/cubesmall_pass_1s5/binoculars_lifts5/torusmedium_pass_1s3/stamp_pass_1s5/spheremedium_pass_1s8/flute_play_1s5/watch_pass_1s6/cubesmall_pass_1s5/cup_pour_1s4/stamp_pass_1s3/hammer_use_2s10/cubemedium_lifts10/pyramidmedium_inspect_1s8/cubemedium_lifts1/train_offhand_1s4/wineglass_drink_2s10/stapler_lifts4/torusmedium_inspect_1s2/piggybank_use_1s10/toothpaste_lifts2/gamecontroller_pass_1s8/banana_lifts10/cubelarge_pass_1s9/eyeglasses_clean_1s10/knife_pass_1s6/camera_takepicture_1s9/wineglass_toast_1_Retakes1/cubesmall_inspect_1s4/cup_pour_1s10/teapot_pour_1s1/stapler_pass_1s3/apple_eat_1s9/alarmclock_pass_1s7/wineglass_drink_2s1/cylinderlarge_pass_1s1/spheresmall_pass_1s10/banana_lifts7/camera_takepicture_2s8/scissors_pass_1s6/binoculars_pass_1s4/spherelarge_pass_1s1/headphones_offhand_1s10/toruslarge_inspect_1s10/cylinderlarge_pass_1s1/duck_offhand_1s10/doorknob_use_1s7/duck_pass_1s2/mouse_pass_1s10/pyramidlarge_pass_1s4/cubemedium_inspect_1s8/toruslarge_inspect_1s1/cup_drink_2s2/cylindersmall_pass_1s6/camera_takepicture_2123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068s8/mug_toast_1s3/airplane_pass_1s1/lightbulb_pass_1s10/camera_takepicture_3s1/wineglass_toast_1s1/phone_lifts4/binoculars_see_1s8/teapot_pass_1s9/cubemedium_pass_1s8/elephant_lifts2/gamecontroller_play_1s6/duck_lifts4/stapler_staple_1s8/mug_drink_1s8/train_lifts1/cubesmall_offhand_1s6/cylindermedium_inspect_1s8/cylindersmall_lifts3/waterbottle_drink_1s1/wineglass_offhand_1s5/scissors_pass_1s1/cup_lifts8/binoculars_pass_1s9/hand_pass_1s7/doorknob_lifts8/spherelarge_pass_1s10/alarmclock_see_1s5/waterbottle_shake_1s5/mouse_use_1s2/cubesmall_lifts4/cubelarge_inspect_1s8/apple_eat_1s3/cylinderlarge_lift_Retakes7/mug_drink_1s8/knife_pass_1s1/flute_offhand_1s7/stapler_pass_1s6/flute_play_1s6/stapler_staple_1s3/gamecontroller_lifts9/spheresmall_pass_1s9/camera_takepicture_1s3/apple_offhand_1s4/binoculars_lifts8/fryingpan_lifts7/camera_pass_1s10/hand_shake_1s3/stamp_stamp_1s6/watch_set_2s6/wineglass_drink_1s1/cubelarge_pass_1s6/hand_inspect_1s2/torussmall_lifts1/torussmall_pass_1s3/mug_offhand_1s1/cylinderlarge_offhand_1s2/cylindermedium_inspect_1s4/stamp_stamp_1s4/mouse_use_1s8/spheremedium_lifts8/headphones_pass_1s3/gamecontroller_play_1s2/stanfordbunny_lifts10/fryingpan_cook_2s3/wineglass_pass_1s1/pyramidlarge_offhand_1s6/toothpaste_pass_1s1/mug_lifts10/waterbottle_pass_1s1/flashlight_pass_1s7/banana_lifts6/waterbottle_drink_1s1/stamp_offhand_1s1/camera_takepicture_1s10/cubesmall_inspect_1s7/alarmclock_see_1s7/gamecontroller_pass_1s8/banana_peel_1s2/camera_takepicture_2s2/cubemedium_lifts10/train_pass_1s10/cylindermedium_pass_1s6/spherelarge_lifts8/duck_inspect_1s3/mug_drink_3s6/hand_pass_1s3/headphones_use_1s5/wineglass_drink_1s10/doorknob_use_2s6/spheremedium_pass_1s5/wineglass_toast_1s5/pyramidmedium_inspect_1s10/spheremedium_inspect_1s5/bowl_drink_2s10/pyramidmedium_pass_1s9/watch_set_1s7/pyramidmedium_pass_1s5/stanfordbunny_pass_1s8/stanfordbunny_lifts7/waterbottle_open_1_Retakes9/pyramidmedium_lift_Retakes5/cubelarge_pass_1s2/stapler_staple_1s2/knife_pass_1s5/duck_inspect_1s8/wineglass_pass_1s5/spherelarge_pass_1s2/elephant_pass_1s1/spherelarge_offhand_1s4/doorknob_use_1s4/stanfordbunny_pass_1s5/piggybank_pass_1s5/banana_peel_2s10/spheremedium_lifts9/gamecontroller_pass_1s6/alarmclock_see_1s9/toruslarge_inspect_1s1/waterbottle_pass_1s7/piggybank_use_1s8/toruslarge_pass_1s1/hammer_use_1s6/stapler_offhand_1_Retakes8/toothpaste_pass_1s10/knife_peel_1s4/cylindersmall_pass_1s10/cylinderlarge_inspect_1s7/flashlight_on_2s2/cubelarge_lifts8/fryingpan_cook_1s6/wineglass_lifts1/stapler_lifts4/cup_pass_1s10/piggybank_use_1s10/binoculars_see_1s4/spheremedium_pass_1s9/bowl_drink_1s4/piggybank_use_1s5/cubesmall_inspect_1s7/stamp_stamp_1s3/scissors_use_2s10/torusmedium_inspect_1s7/hand_inspect_1s5/cylindermedium_inspect_1s8/banana_eat_1s7/binoculars_see_1s4/spheresmall_pass_1s4/cylinderlarge_lifts9/waterbottle_shake_1s4/hand_inspect_1s7/spherelarge_lifts2/flashlight_on_1s10/duck_pass_1s9/bowl_pass_1s1/mouse_lifts9/watch_pass_1s2/phone_call_1s6/cylinderlarge_inspect_1s3/wineglass_drink_2s10/toothpaste_pass_1s10/fryingpan_cook_1s8/watch_lifts9/pyramidlarge_inspect_1s2/mouse_use_1s6/pyramidmedium_pass_1s4/mouse_pass_1s6/wineglass_toast_1s1/watch_lifts9/hand_inspect_1s1/airplane_lifts9/mouse_lifts6/eyeglasses_clean_1s4/waterbottle_drink_1s4/torussmall_lifts6/binoculars_lifts8/bowl_offhand_1s2/eyeglasses_pass_1s8/fryingpan_cook_2s8/spherelarge_lifts1/cylindermedium_pass_1s1/banana_eat_1s10/gamecontroller_pass_1s9/camera_browse_1s6/eyeglasses_wear_1s1/stanfordbunny_lifts6/cylindersmall_inspect_1s6/elephant_pass_1s3/torusmedium_inspect_1s8/spheresmall_pass_1s6/apple_offhand_1_Retakes6/stanfordbunny_pass_1s6/mug_drink_2s8/mug_lifts1/binoculars_see_1s1/torussmall_offhand_1s9/duck_pass_1s8/cubemedium_offhand_1s8/spherelarge_inspect_1s7/wineglass_pass_1s9/toothpaste_squeeze_1s10/scissors_pass_1s10/torussmall_inspect_1s4/wineglass_lifts5/binoculars_pass_1s7/stanfordbunny_pass_1s1/mug_drink_1s1/stamp_pass_1s8/piggybank_use_1s10/spheremedium_pass_1s9/torusmedium_pass_1s3/mouse_lifts1/cylindermedium_inspect_1s8/cylindermedium_pass_1s7/cubesmall_pass_1s6/cylindermedium_lifts7/cup_pour_1s9/banana_pass_1s1/camera_browse_1s3/eyeglasses_clean_1s1/doorknob_use_fun_1s1/banana_lifts6/cylindersmall_pass_1s5/elephant_lifts5/elephant_inspect_1s9/waterbottle_lifts6/piggybank_lift_Retakes5/camera_takepicture_3s4/stapler_staple_2s1/cylindersmall_lifts1/airplane_offhand_1s9/apple_pass_1s9/cylindermedium_pass_1s9/hammer_use_3s7/cubemedium_pass_1s6/cubemedium_inspect_1s2/mug_lifts6/phone_lifts4/spherelarge_inspect_1s1/elephant_inspect_1s4/headphones_pass_1s8/binoculars_see_1s7/pyramidmedium_inspect_1s1/toothpaste_lifts4/stamp_lifts8/eyeglasses_pass_1s7/hand_pass_1s10/spherelarge_lifts2/stapler_pass_1s9/banana_peel_1s2/mug_pass_1s6/stapler_pass_1s10/wineglass_drink_1s10/lightbulb_screw_1s7/spheresmall_pass_1s2/stanfordbunny_inspect_1s7/piggybank_pass_1s8/mug_pass_1s10/torussmall_lifts8/cup_pour_1s5/pyramidlarge_pass_1s1/binoculars_pass_1s5/hammer_pass_1s1/flashlight_offhand_1s7/elephant_pass_1s6/hand_lifts1/cubelarge_offhand_1s9/elephant_lifts8/banana_peel_2s8/knife_peel_1s1/teapot_pass_1s10/headphones_pass_1s2/toothbrush_lifts9/knife_pass_1s2/cubemedium_inspect_1s8/teapot_lifts3/pyramidmedium_pass_1s2/cylindermedium_lifts4/mug_pass_1s10/stamp_lifts7/airplane_lift_Retakes10/toruslarge_pass_1s6/fryingpan_pass_1s4/train_play_1s5/pyramidmedium_pass_1s7/binoculars_pass_1s1/phone_call_1s2/spheresmall_inspect_1s3/apple_lifts6/hammer_use_3s8/toothbrush_pass_1s7/spheresmall_inspect_1s10/flashlight_on_1s9/elephant_inspect_1s4/elephant_pass_1s1/bowl_drink_1s6/cubemedium_pass_1s7/eyeglasses_pass_1s8/airplane_fly_1s3/alarmclock_lifts4/doorknob_lifts4/fryingpan_cook_2s4/toothbrush_pass_1s5/cylinderlarge_pass_1s2/banana_eat_1s5/stamp_stamp_1s1/knife_lifts10/hand_pass_1s4/bowl_drink_2s8/cup_pass_1s5/hammer_use_1s3/train_lifts2/cup_pass_1s7/torussmall_pass_1s8/hand_pass_1s10/cup_drink_2s3/toothpaste_lifts2/fryingpan_pass_1s3/cylindersmall_pass_1s5/spheremedium_lifts10/apple_eat_1s4/teapot_pour_2s4/torussmall_pass_1s5/toothpaste_pass_1s7/headphones_pass_1s5/camera_pass_1s9/elephant_pass_1s6/toothpaste_lifts8/flute_pass_1s4/spheremedium_lifts3/binoculars_see_1s10/camera_browse_1s1/banana_pass_1s1/toruslarge_lifts6/cubelarge_inspect_1s1/pyramidlarge_pass_1s2/teapot_pour_1s3/waterbottle_pass_1s2/hammer_lifts9/apple_lifts9/waterbottle_pour_1s4/cubemedium_lifts9/phone_pass_1s5/cubemedium_lifts4/gamecontroller_pass_1s9/cubemedium_inspect_1s3/cup_drink_1s4/stapler_lifts2/apple_pass_1s5/mug_toast_1s5/cylindersmall_inspect_1s3/cup_lifts1/hammer_pass_1s10/hammer_lifts5/elephant_pass_1s1/spheresmall_inspect_1s3/toothbrush_brush_1s7/apple_eat_1s7/pyramidlarge_lifts7/wineglass_drink_1s7/mug_lifts6/cubesmall_offhand_1s2/camera_lifts1/cubemedium_lifts10/gamecontroller_lifts9/cylinderlarge_pass_1s8/cubelarge_inspect_1s1/scissors_pass_1s1/train_play_1s5/stanfordbunny_inspect_1s4/spheresmall_lifts4/watch_lifts9/cylinderlarge_inspect_1s2/hand_inspect_1s8/toothpaste_squeeze_1s8/toothpaste_squeeze_2s8/mouse_use_1s2/teapot_pass_1s7/cup_pass_1s9/spheremedium_inspect_1s10/gamecontroller_play_1s7/apple_lifts6/eyeglasses_lifts10/flute_pass_1s9/airplane_fly_1s5/stamp_pass_1s5/alarmclock_lifts10/hammer_use_3s3/cylindersmall_inspect_1s10/alarmclock_pass_1s9/waterbottle_drink_1s10/banana_pass_1s6/watch_pass_1s1/banana_peel_2s8/pyramidmedium_pass_1s7/cubemedium_lifts6/cup_drink_2s4/cubelarge_pass_1s1/bowl_pass_1s8/wineglass_drink_2s8/phone_call_1s8/torusmedium_lifts4/piggybank_pass_1s9/stamp_pass_1s10/hammer_use_2s9/wineglass_pass_1s8/camera_browse_1s7/airplane_pass_1s6/cup_pass_1s6/airplane_pass_1s9/torussmall_pass_1s8/teapot_pour_2s4/mouse_use_2s10/flashlight_on_2s7/pyramidsmall_pass_1s3/cup_pour_1s1/piggybank_pass_1s5/cubesmall_pass_1s10/airplane_fly_1s8/cylinderlarge_offhand_1s6/gamecontroller_play_1s3/stanfordbunny_pass_1s7/stanfordbunny_lifts9/banana_peel_2s2/apple_lifts10/waterbottle_pour_1s1/alarmclock_pass_1s1/hammer_use_3s1/eyeglasses_clean_1s6/phone_call_1s7/banana_eat_1s4/waterbottle_shake_1s8/waterbottle_pass_1s6/cylinderlarge_lifts9/hand_shake_1s6/camera_browse_1s2/camera_browse_1s4/phone_pass_1s1/stamp_lifts7/torussmall_inspect_1s1/cylindersmall_offhand_1s7/cylinderlarge_lifts2/duck_inspect_1s7/spheremedium_pass_1s8/toruslarge_lifts3/hammer_pass_1s3/cup_offhand_1s2/headphones_use_1s2/train_play_1s10/scissors_use_1s5/cubesmall_lifts10/pyramidsmall_inspect_1s3/mug_drink_4s1/cubemedium_offhand_1s6/apple_eat_1s1/doorknob_use_2s1/cylinderlarge_lifts2/hand_lifts5/gamecontroller_lifts3/waterbottle_lifts3/apple_pass_1s10/flute_play_1s5/spherelarge_inspect_1s7/doorknob_use_1s8/torusmedium_pass_1s4/bowl_pass_1s10/headphones_lifts6/pyramidlarge_pass_1s2/mug_toast_1s4/hammer_use_3s1/stanfordbunny_inspect_1s3/alarmclock_pass_1s8/cylindermedium_inspect_1s1/elephant_lifts6/waterbottle_pass_1s8/cubelarge_lifts3/camera_takepicture_1s5/torussmall_inspect_1s2/airplane_fly_1s7/hammer_use_1s1/spherelarge_lifts1/cubemedium_pass_1s2/headphones_lifts8/piggybank_lifts1/apple_lifts3/spherelarge_inspect_1s8/banana_pass_1s8/stanfordbunny_pass_1s4/flute_play_1s6/banana_eat_1s1/scissors_offhand_1s1/binoculars_lifts10/cup_lifts7/eyeglasses_lifts3/stapler_lifts7/bowl_drink_1s1/cup_drink_1s4/alarmclock_lifts6/headphones_use_1s4/apple_lifts6/mouse_pass_1s7/flashlight_lifts5/torusmedium_inspect_1s10/cup_pour_1s5/toruslarge_lifts10/cup_drink_1s7/cylinderlarge_pass_1s4/wineglass_drink_1s1/stapler_staple_2s10/mug_drink_1s1/flute_pass_1s8/cylinderlarge_lifts10/piggybank_pass_1s7/duck_inspect_1s9/stamp_lifts6/bowl_lifts6/banana_pass_1s9/cubemedium_lifts7/flute_pass_1s8/eyeglasses_wear_1s9/flashlight_lifts9/hammer_use_2s1/cup_pour_1s2/piggybank_lifts8/pyramidlarge_inspect_1s2/teapot_pour_2s6/pyramidsmall_inspect_2s1/toothpaste_pass_1s10/banana_peel_2s1/wineglass_pass_1s5/pyramidlarge_inspect_1s5/cubemedium_inspect_1s7/knife_chop_1s6/mug_toast_1s5/mug_drink_1s6/banana_peel_1s7/cylindermedium_pass_1s10/mug_drink_2s3/elephant_offhand_1s4/stapler_pass_1s1/torussmall_lifts1/duck_lifts5/flute_play_1s1/airplane_fly_1s2/headphones_pass_1s3/lightbulb_screw_1s8/toothbrush_brush_1s10/mouse_use_1s5/flute_play_2s3/waterbottle_pour_2s10/airplane_lifts7/eyeglasses_wear_1s10/stamp_stamp_1s8/cup_drink_1s4/alarmclock_pass_1s3/train_pass_1s2/hammer_use_2s1/pyramidsmall_inspect_1s9/cubesmall_inspect_1s7/camera_browse_1s10/spheresmall_pass_1s1/phone_offhand_1s6/waterbottle_shake_1s1/alarmclock_offhand_1s8/spheresmall_inspect_1s9/cylindermedium_inspect_1s6/knife_lifts6/mouse_lifts1/flashlight_lifts9/cubelarge_pass_1s2/pyramidlarge_pass_1_Retakes7/stanfordbunny_inspect_1s9/gamecontroller_play_1s4/hand_pass_1s3/toothpaste_squeeze_1s9/duck_lifts5/flashlight_on_1s5/cup_lifts10/waterbottle_drink_1s8/cubesmall_pass_1s10/train_lifts10/spheresmall_inspect_1s10/cup_pass_1s1/cubesmall_pass_1s4/fryingpan_cook_3s6/elephant_inspect_1s9/stapler_lifts1/pyramidmedium_offhand_1s9/pyramidmedium_pass_1s9/teapot_pour_2s4/fryingpan_cook_1s1/eyeglasses_wear_1s1/gamecontroller_play_1s3/binoculars_offhand_1s6/waterbottle_pour_1s3/cubesmall_inspect_1s8/pyramidlarge_pass_1s2/train_pass_1s10/mouse_lifts10/torusmedium_pass_1s8/waterbottle_drink_1s7/cubelarge_lifts5/duck_pass_1s1/gamecontroller_offhand_1s2/camera_pass_1s7/gamecontroller_play_1s7/toothbrush_pass_1s8/phone_pass_1s3/bowl_drink_1s6/toruslarge_pass_1s5/spheresmall_inspect_1s8/flashlight_pass_1s1/flashlight_on_2s8/gamecontroller_lifts3/stanfordbunny_lifts8/bowl_pass_1s4/banana_pass_1s6/stapler_lifts2/teapot_lifts3/camera_takepicture_2s8/torussmall_pass_1s9/camera_pass_1s4/apple_eat_1s1/watch_set_1s5/stanfordbunny_lifts6/spheremedium_inspect_1s1/eyeglasses_lifts10/headphones_use_1s3/doorknob_use_1s10/apple_pass_1s9/flute_pass_1s1/toruslarge_inspect_1s5/duck_lifts9/doorknob_use_2s10/torussmall_pass_1s2/doorknob_use_2s1/pyramidlarge_lifts6/stamp_lifts3/elephant_pass_1s7/headphones_use_1s6/cylindermedium_pass_1s6/stapler_staple_2s6/piggybank_pass_1s5/spheremedium_inspect_1s1/cubemedium_inspect_1s4/pyramidmedium_pass_1s7/cylinderlarge_inspect_1s1/cylindermedium_offhand_1s6/toothpaste_squeeze_1_Retakes9/stapler_pass_1s8/flashlight_on_1s5/cup_drink_2s8/apple_lifts8/airplane_pass_1s6/wineglass_pass_1s4/cylinderlarge_inspect_1s4/phone_call_1s5/stapler_pass_1s8/camera_takepicture_2s3/mouse_pass_1s7/pyramidlarge_inspect_1s10/stapler_staple_2s9/teapot_pass_1s5/gamecontroller_play_1s4/train_lifts8/doorknob_lifts1/watch_offhand_1s7/mug_drink_2s4/flashlight_pass_1s1/mug_offhand_1s4/camera_takepicture_3s8/train_pass_1s7/train_pass_1s8/gamecontroller_play_1s1/scissors_use_2s9/piggybank_pass_1s6/flute_lifts1/banana_peel_1s6/bowl_pass_1s1/mouse_pass_1s6/cubesmall_lifts5/airplane_lifts3/scissors_pass_1s2/cylinderlarge_pass_1s6/watch_set_1s10/stamp_pass_1s9/banana_lifts3/toruslarge_lifts10/hammer_use_1s10/cubesmall_lifts6/teapot_pass_1s3/pyramidlarge_offhand_1s8/cylindersmall_inspect_1s3/cylinderlarge_inspect_1s7/teapot_pass_1s9/mouse_pass_1s3/mug_drink_1s2/spheremedium_pass_1s9/waterbottle_pass_1s2/flute_pass_1s9/lightbulb_screw_1s8/cubemedium_pass_1s7/flashlight_pass_1s9/eyeglasses_lifts7/cubemedium_inspect_1s5/waterbottle_lifts6/cup_drink_1s1/pyramidlarge_inspect_1s3/airplane_fly_1s10/pyramidmedium_lifts10/bowl_lifts2/cubelarge_pass_1s7/stapler_staple_1s8/flashlight_on_2s4/cylindersmall_lifts10/stanfordbunny_pass_1s6/cubemedium_lifts10/stapler_pass_1s5/apple_pass_1s7/doorknob_use_2s4/watch_pass_1s1/elephant_pass_1s1/watch_set_2s2/cylinderlarge_inspect_1s2/pyramidlarge_inspect_1s9/eyeglasses_wear_1s4/phone_lifts1/spheremedium_lifts3/airplane_offhand_1s6/spheresmall_pass_1s9/piggybank_lift_Retakes8/cylinderlarge_inspect_1s5/wineglass_lifts3/train_play_1s10/knife_chop_1s9/wineglass_drink_2s6/hammer_lifts9/cylindersmall_pass_1s4/bowl_drink_1s1/mug_toast_1s1/pyramidmedium_inspect_1s9/stamp_stamp_1s10/toothpaste_squeeze_1s1/spheresmall_lifts3/doorknob_use_2s7/fryingpan_cook_1s5/teapot_pass_1s8/phone_lifts2/cubesmall_inspect_1s1/toruslarge_pass_1s6/headphones_pass_1s8/cylinderlarge_pass_1s4/toothpaste_pass_1s4/camera_takepicture_2s3/camera_offhand_1s8/cup_offhand_1s9/spherelarge_pass_1s10/stanfordbunny_lifts1/spheremedium_offhand_1s4/torusmedium_lifts9/cylinderlarge_lifts6/hammer_use_1s4/wineglass_toast_1s2/cylinderlarge_lifts6/cubesmall_inspect_1s1/camera_takepicture_2s3/phone_pass_1s1/hand_inspect_1s8/bowl_drink_2s1/stapler_offhand_1s1/piggybank_use_1s1/apple_pass_1s9/wineglass_drink_1s10/mug_lifts10/cylinderlarge_lifts2/stamp_stamp_1s10/stanfordbunny_inspect_1s4/cubelarge_lifts8/alarmclock_see_1s5/cubelarge_lifts3/eyeglasses_pass_1s1/pyramidsmall_pass_1s2/cylindermedium_pass_1s8/fryingpan_offhand_1s1/mug_drink_3s2/piggybank_pass_1_Retakes8/headphones_lifts9/alarmclock_see_1s5/toruslarge_pass_1s1/stapler_staple_1s1/stanfordbunny_offhand_1s3/airplane_lifts8/cubemedium_inspect_1s9/stapler_staple_2s3/fryingpan_lifts10/spherelarge_inspect_1s7/pyramidlarge_pass_1s5/mouse_lifts8/watch_set_2s3/wineglass_drink_1s6/spheremedium_lifts2/stapler_staple_2s9/airplane_pass_1s6/duck_inspect_1s10/lightbulb_pass_1s8/stapler_pass_1s6/camera_takepicture_3s10/camera_takepicture_2s10/mouse_pass_1s3/cup_drink_2s5/alarmclock_see_1s10/elephant_inspect_1s6/apple_pass_1s3/gamecontroller_pass_1s10/cubemedium_pass_1s5/wineglass_pass_1s5/waterbottle_pass_1s10/teapot_pour_2s6/train_pass_1s7/hammer_use_2s8/apple_pass_1s6/cup_pour_1s7/wineglass_lifts9/toothbrush_pass_1s6/doorknob_lifts9/banana_eat_1s4/cylinderlarge_pass_1s10/cubelarge_lifts1/camera_lifts1/stanfordbunny_pass_1s7/watch_pass_1s9/cup_lifts7/apple_pass_1s3/piggybank_pass_1s1/cylindersmall_inspect_1s4/cup_drink_2s8/spheremedium_pass_1s6/waterbottle_open_1s3/watch_set_1s8/cubesmall_inspect_1s3/duck_inspect_1s7/cylindermedium_inspect_1s9/cylindersmall_inspect_1s1/spherelarge_inspect_1s1/spheresmall_offhand_1s8/cylindermedium_lifts1/bowl_drink_2s5/train_pass_1s4/alarmclock_see_1s8/flashlight_offhand_1s2/cup_drink_1s8/duck_lifts6/cubelarge_pass_1s6/flute_pass_1s2/toruslarge_inspect_1s4/camera_pass_1s7/train_play_1s9/mouse_use_1s5/cylindermedium_pass_1s3/pyramidsmall_pass_1s3/eyeglasses_offhand_1s8/wineglass_toast_1s7/eyeglasses_clean_1s5/toothbrush_brush_1s10/toothpaste_squeeze_2s1/flute_lifts3/toothbrush_pass_1s1/bowl_lifts9/bowl_drink_2s7/banana_peel_2s8/doorknob_use_2s8/torussmall_inspect_1s1/camera_pass_1s8/hand_inspect_1s1/watch_pass_1s10/watch_pass_1s3/toruslarge_inspect_1s9/torusmedium_inspect_1s9/cylindermedium_lifts10/teapot_pass_1s6/wineglass_drink_2s7/headphones_lifts10/stapler_staple_1s2/pyramidmedium_inspect_1s3/flashlight_pass_1s1/torusmedium_pass_1s6/spherelarge_pass_1s2/phone_pass_1s2/pyramidmedium_pass_1s9/stanfordbunny_pass_1s8/pyramidmedium_inspect_1s1/toothbrush_lifts7/hammer_pass_1s8/hand_lifts8/camera_takepicture_3s8/stamp_lifts8/torusmedium_inspect_1s7/phone_call_1s3/pyramidlarge_inspect_1s6/torussmall_pass_1s3/mouse_use_1s6/toruslarge_inspect_1s3/elephant_lifts1/wineglass_drink_2s7/lightbulb_pass_1s8/hammer_pass_1s6/pyramidmedium_inspect_1s8/gamecontroller_pass_1s1/waterbottle_pour_1s9/toothpaste_lifts9/spherelarge_inspect_1s8/teapot_pour_1s4/spheremedium_inspect_1s6/stamp_stamp_1s9/hammer_use_1s1/torusmedium_offhand_1s1/alarmclock_see_1s6/phone_pass_1s5/waterbottle_open_1s4/cubemedium_pass_1s6/apple_lifts1/headphones_pass_1s8/hammer_use_3s3/piggybank_use_1s3/wineglass_toast_1s6/spheresmall_lifts1/camera_takepicture_3_Retakes1/cylindermedium_lifts6/teapot_pour_1s4/train_pass_1s7/toruslarge_inspect_1_Retakes8/cubelarge_pass_1s3/alarmclock_offhand_1s4/hand_lifts8/mug_drink_2s5/cup_pass_1s3/stapler_staple_1s10/phone_lifts6/torusmedium_inspect_1s4/cup_drink_1s2/train_lifts8/stapler_staple_1s2/apple_eat_1s6/torusmedium_pass_1s4/watch_set_1s3/camera_takepicture_3s9/spheresmall_inspect_1s4/cubesmall_pass_1s6/alarmclock_lifts2/toruslarge_pass_1s9/pyramidmedium_inspect_1s3/stanfordbunny_inspect_1s6/scissors_use_2s1/stamp_stamp_1s3/torusmedium_pass_1s6/eyeglasses_pass_1s7/cubelarge_inspect_1s3/stamp_lifts8/mouse_pass_1s7/elephant_inspect_1s8/camera_pass_1s10/bowl_pass_1s1/waterbottle_lifts8/bowl_lifts3/phone_call_1s8/phone_offhand_1s3/eyeglasses_wear_1s6/bowl_drink_1_Retakes9/torussmall_inspect_1s1/piggybank_offhand_1s1/mug_drink_2s4/airplane_fly_1s8/cubelarge_offhand_1s10/camera_pass_1s4/stanfordbunny_inspect_1s6/pyramidlarge_inspect_1s10/wineglass_drink_2s1/duck_inspect_1s4/duck_inspect_1s1/mouse_use_1s5/eyeglasses_clean_2s10/camera_takepicture_1s8/fryingpan_pass_1s10/cubelarge_inspect_1s7/hammer_use_3s5/spherelarge_lifts1/fryingpan_cook_1s5/cubemedium_pass_1s3/flute_play_1s9/headphones_use_1s1/cylinderlarge_inspect_1s7/hammer_lifts7/wineglass_toast_1s4/pyramidmedium_inspect_1s10/bowl_drink_1_Retakes9/piggybank_use_1s1/cubesmall_lifts1/fryingpan_cook_2s1/apple_eat_1s9/watch_set_2s9/bowl_lifts10/hand_lifts10/cylindersmall_inspect_1s1/piggybank_lifts2/toothpaste_squeeze_1s6/binoculars_see_1s6/spherelarge_inspect_1s8/alarmclock_lifts1/cylindersmall_pass_1s6/pyramidlarge_lifts4/binoculars_pass_1s10/bowl_drink_2s5/flute_pass_1s10/torusmedium_lifts1/duck_pass_1s2/cubelarge_inspect_1s8/watch_pass_1s1/waterbottle_open_1s9/flute_play_1s9/airplane_lifts1/mug_drink_4s4/wineglass_pass_1s6/camera_pass_1s4/duck_pass_1s10/cylindersmall_pass_1s10/alarmclock_lift_Retakes4/toruslarge_pass_1s10/wineglass_pass_1s5/cylindermedium_lifts2/pyramidlarge_lifts3/flute_offhand_1s8/camera_offhand_1s2/elephant_inspect_1s5/mug_pass_1s3/hammer_use_1s9/mug_drink_2s5/wineglass_drink_2s5/piggybank_lifts9/waterbottle_open_1s7/alarmclock_lifts1/eyeglasses_offhand_1s1/flute_play_1s8/wineglass_lifts7/waterbottle_shake_1s1/cubelarge_inspect_1s1/hammer_use_2s5/doorknob_lifts1/spheremedium_inspect_1s9/spheremedium_pass_1s6/knife_peel_1s4/fryingpan_pass_1s3/binoculars_lifts7/toruslarge_lifts4/piggybank_lifts3/cubelarge_pass_1s2/banana_peel_1s1/alarmclock_lifts5/train_lifts1/cup_pass_1s1/waterbottle_drink_1s3/bowl_drink_2s5/cylinderlarge_inspect_1s4/headphones_use_1s3/hand_pass_1s3/flashlight_on_1s3/toruslarge_pass_1s9/flashlight_on_1s8/mug_offhand_1s8/cubesmall_lifts10/airplane_pass_1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566s4/stanfordbunny_lifts3/cubelarge_offhand_1s2/stanfordbunny_pass_1s5/bowl_drink_1s3/knife_lifts8/fryingpan_cook_3s7/stamp_pass_1s10/hammer_pass_1s1/phone_pass_1s6/teapot_pour_2s2/mug_drink_2s8/spheresmall_lifts7/banana_pass_1s4/cup_lifts5/train_play_1s6/airplane_lifts3/spheremedium_inspect_1s1/hand_offhand_1s3/camera_pass_1s7/bowl_pass_1s6/mug_pass_1s7/binoculars_lifts8/hammer_lifts1/waterbottle_offhand_1s3/cylindermedium_pass_1s7/waterbottle_drink_1s7/spheremedium_inspect_1s10/banana_eat_1s2/spherelarge_lifts1/duck_offhand_2s6/doorknob_use_2s6/cylinderlarge_pass_1s9/camera_lifts1/eyeglasses_pass_1s3/cylinderlarge_pass_1s10/elephant_pass_1s4/scissors_pass_1s3/cubemedium_inspect_1s6/stamp_pass_1s9/mug_pass_1s10/phone_pass_1s7/mouse_pass_1s3/scissors_use_1s6/airplane_fly_1s8/lightbulb_pass_1s2/toruslarge_lifts8/stapler_lifts5/piggybank_use_1s6/banana_peel_2s10/doorknob_lifts8/stamp_pass_1s5/hand_pass_1s5/bowl_pass_1s3/pyramidlarge_pass_1s6/camera_lifts9/duck_inspect_1s3/cubelarge_lifts4/watch_set_2s5/cylinderlarge_lifts2/toothpaste_lifts8/knife_chop_1s1/flashlight_on_1s10/mug_pass_1s1/gamecontroller_lifts1/airplane_pass_1s7/cylindersmall_pass_11s1/airplane_pass_1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068s8/mug_toast_1s3/airplane_pass_1s1/lightbulb_pass_1s10/camera_takepicture_3s1/wineglass_toast_1s1/phone_lifts4/binoculars_see_1s8/teapot_pass_1s9/cubemedium_pass_1s8/elephant_lifts2/gamecontroller_play_1s6/duck_lifts4/stapler_staple_1s8/mug_drink_1s8/train_lifts1/cubesmall_offhand_1s6/cylindermedium_inspect_1s8/cylindersmall_lifts3/waterbottle_drink_1s1/wineglass_offhand_1s5/scissors_pass_1s1/cup_lifts8/binoculars_pass_1s9/hand_pass_1s7/doorknob_lifts8/spherelarge_pass_1s10/alarmclock_see_1s5/waterbottle_shake_1s5/mouse_use_1s2/cubesmall_lifts4/cubelarge_inspect_1s8/apple_eat_1s3/cylinderlarge_lift_Retakes7/mug_drink_1s8/knife_pass_1s1/flute_offhand_1s7/stapler_pass_1s6/flute_play_1s6/stapler_staple_1s3/gamecontroller_lifts9/spheresmall_pass_1s9/camera_takepicture_1s3/apple_offhand_1s4/binoculars_lifts8/fryingpan_lifts7/camera_pass_1s10/hand_shake_1s3/stamp_stamp_1s6/watch_set_2s6/wineglass_drink_1s1/cubelarge_pass_1s6/hand_inspect_1s2/torussmall_lifts1/torussmall_pass_1s3/mug_offhand_1s1/cylinderlarge_offhand_1s2/cylindermedium_inspect_1s4/stamp_stamp_1s4/mouse_use_1s8/spheremedium_lifts8/headphones_pass_1s3/gamecontroller_play_1s2/stanfordbunny_lifts10/fryingpan_cook_2s3/wineglass_pass_1s1/pyramidlarge_offhand_1s6/toothpaste_pass_1s1/mug_lifts10/waterbottle_pass_1s1/flashlight_pass_1s7/banana_lifts6/waterbottle_drink_1s1/stamp_offhand_1s1/camera_takepicture_1s10/cubesmall_inspect_1s7/alarmclock_see_1s7/gamecontroller_pass_1s8/banana_peel_1s2/camera_takepicture_2s2/cubemedium_lifts10/train_pass_1s10/cylindermedium_pass_1s6/spherelarge_lifts8/duck_inspect_1s3/mug_drink_3s6/hand_pass_1s3/headphones_use_1s5/wineglass_drink_1s10/doorknob_use_2s6/spheremedium_pass_1s5/wineglass_toast_1s5/pyramidmedium_inspect_1s10/spheremedium_inspect_1s5/bowl_drink_2s10/pyramidmedium_pass_1s9/watch_set_1s7/pyramidmedium_pass_1s5/stanfordbunny_pass_1s8/stanfordbunny_lifts7/waterbottle_open_1_Retakes9/pyramidmedium_lift_Retakes5/cubelarge_pass_1s2/stapler_staple_1s2/knife_pass_1s5/duck_inspect_1s8/wineglass_pass_1s5/spherelarge_pass_1s2/elephant_pass_1s1/spherelarge_offhand_1s4/doorknob_use_1s4/stanfordbunny_pass_1s5/piggybank_pass_1s5/banana_peel_2s10/spheremedium_lifts9/gamecontroller_pass_1s6/alarmclock_see_1s9/toruslarge_inspect_1s1/waterbottle_pass_1s7/piggybank_use_1s8/toruslarge_pass_1s1/hammer_use_1s6/stapler_offhand_1_Retakes8/toothpaste_pass_1s10/knife_peel_1s4/cylindersmall_pass_1s10/cylinderlarge_inspect_1s7/flashlight_on_2s2/cubelarge_lifts8/fryingpan_cook_1s6/wineglass_lifts1/stapler_lifts4/cup_pass_1s10/piggybank_use_1s10/binoculars_see_1s4/spheremedium_pass_1s9/bowl_drink_1s4/piggybank_use_1s5/cubesmall_inspect_1s7/stamp_stamp_1s3/scissors_use_2s10/torusmedium_inspect_1s7/hand_inspect_1s5/cylindermedium_inspect_1s8/banana_eat_1s7/binoculars_see_1s4/spheresmall_pass_1s4/cylinderlarge_lifts9/waterbottle_shake_1s4/hand_inspect_1s7/spherelarge_lifts2/flashlight_on_1s10/duck_pass_1s9/bowl_pass_1s1/mouse_lifts9/watch_pass_1s2/phone_call_1s6/cylinderlarge_inspect_1s3/wineglass_drink_2s10/toothpaste_pass_1s10/fryingpan_cook_1s8/watch_lifts9/pyramidlarge_inspect_1s2/mouse_use_1s6/pyramidmedium_pass_1s4/mouse_pass_1s6/wineglass_toast_1s1/watch_lifts9/hand_inspect_1s1/airplane_lifts9/mouse_lifts6/eyeglasses_clean_1s4/waterbottle_drink_1s4/torussmall_lifts6/binoculars_lifts8/bowl_offhand_1s2/eyeglasses_pass_1s8/fryingpan_cook_2s8/spherelarge_lifts1/cylindermedium_pass_1s1/banana_eat_1s10/gamecontroller_pass_1s9/camera_browse_1s6/eyeglasses_wear_1s1/stanfordbunny_lifts6/cylindersmall_inspect_1s6/elephant_pass_1s3/torusmedium_inspect_1s8/spheresmall_pass_1s6/apple_offhand_1_Retakes6/stanfordbunny_pass_1s6/mug_drink_2s8/mug_lifts1/binoculars_see_1s1/torussmall_offhand_1s9/duck_pass_1s8/cubemedium_offhand_1s8/spherelarge_inspect_1s7/wineglass_pass_1s9/toothpaste_squeeze_1s10/scissors_pass_1s10/torussmall_inspect_1s4/wineglass_lifts5/binoculars_pass_1s7/stanfordbunny_pass_1s1/mug_drink_1s1/stamp_pass_1s8/piggybank_use_1s10/spheremedium_pass_1s9/torusmedium_pass_1s3/mouse_lifts1/cylindermedium_inspect_1s8/cylindermedium_pass_1s7/cubesmall_pass_1s6/cylindermedium_lifts7/cup_pour_1s9/banana_pass_1s1/camera_browse_1s3/eyeglasses_clean_1s1/doorknob_use_fun_1s1/banana_lifts6/cylindersmall_pass_1s5/elephant_lifts5/elephant_inspect_1s9/waterbottle_lifts6/piggybank_lift_Retakes5/camera_takepicture_3s4/stapler_staple_2s1/cylindersmall_lifts1/airplane_offhand_1s9/apple_pass_1s9/cylindermedium_pass_1s9/hammer_use_3s7/cubemedium_pass_1s6/cubemedium_inspect_1s2/mug_lifts6/phone_lifts4/spherelarge_inspect_1s1/elephant_inspect_1s4/headphones_pass_1s8/binoculars_see_1s7/pyramidmedium_inspect_1s1/toothpaste_lifts4/stamp_lifts8/eyeglasses_pass_1s7/hand_pass_1s10/spherelarge_lifts2/stapler_pass_1s9/banana_peel_1s2/mug_pass_1s6/stapler_pass_1s10/wineglass_drink_1s10/lightbulb_screw_1s7/spheresmall_pass_1s2/stanfordbunny_inspect_1s7/piggybank_pass_1s8/mug_pass_1s10/torussmall_lifts8/cup_pour_1s5/pyramidlarge_pass_1s1/binoculars_pass_1s5/hammer_pass_1s1/flashlight_offhand_1s7/elephant_pass_1s6/hand_lifts1/cubelarge_offhand_1s9/elephant_lifts8/banana_peel_2s8/knife_peel_1s1/teapot_pass_1s10/headphones_pass_1s2/toothbrush_lifts9/knife_pass_1s2/cubemedium_inspect_1s8/teapot_lifts3/pyramidmedium_pass_1s2/cylindermedium_lifts4/mug_pass_1s10/stamp_lifts7/airplane_lift_Retakes10/toruslarge_pass_1s6/fryingpan_pass_1s4/train_play_1s5/pyramidmedium_pass_1s7/binoculars_pass_1s1/phone_call_1s2/spheresmall_inspect_1s3/apple_lifts6/hammer_use_3s8/toothbrush_pass_1s7/spheresmall_inspect_1s10/flashlight_on_1s9/elephant_inspect_1s4/elephant_pass_1s1/bowl_drink_1s6/cubemedium_pass_1s7/eyeglasses_pass_1s8/airplane_fly_1s3/alarmclock_lifts4/doorknob_lifts4/fryingpan_cook_2s4/toothbrush_pass_1s5/cylinderlarge_pass_1s2/banana_eat_1s5/stamp_stamp_1s1/knife_lifts10/hand_pass_1s4/bowl_drink_2s8/cup_pass_1s5/hammer_use_1s3/train_lifts2/cup_pass_1s7/torussmall_pass_1s8/hand_pass_1s10/cup_drink_2s3/toothpaste_lifts2/fryingpan_pass_1s3/cylindersmall_pass_1s5/spheremedium_lifts10/apple_eat_1s4/teapot_pour_2s4/torussmall_pass_1s5/toothpaste_pass_1s7/headphones_pass_1s5/camera_pass_1s9/elephant_pass_1s6/toothpaste_lifts8/flute_pass_1s4/spheremedium_lifts3/binoculars_see_1s10/camera_browse_1s1/banana_pass_1s1/toruslarge_lifts6/cubelarge_inspect_1s1/pyramidlarge_pass_1s2/teapot_pour_1s3/waterbottle_pass_1s2/hammer_lifts9/apple_lifts9/waterbottle_pour_1s4/cubemedium_lifts9/phone_pass_1s5/cubemedium_lifts4/gamecontroller_pass_1s9/cubemedium_inspect_1s3/cup_drink_1s4/stapler_lifts2/apple_pass_1s5/mug_toast_1s5/cylindersmall_inspect_1s3/cup_lifts1/hammer_pass_1s10/hammer_lifts5/elephant_pass_1s1/spheresmall_inspect_1s3/toothbrush_brush_1s7/apple_eat_1s7/pyramidlarge_lifts7/wineglass_drink_1s7/mug_lifts6/cubesmall_offhand_1s2/camera_lifts1/cubemedium_lifts10/gamecontroller_lifts9/cylinderlarge_pass_1s8/cubelarge_inspect_1s1/scissors_pass_1s1/train_play_1s5/stanfordbunny_inspect_1s4/spheresmall_lifts4/watch_lifts9/cylinderlarge_inspect_1s2/hand_inspect_1s8/toothpaste_squeeze_1s8/toothpaste_squeeze_2s8/mouse_use_1s2/teapot_pass_1s7/cup_pass_1s9/spheremedium_inspect_1s10/gamecontroller_play_1s7/apple_lifts6/eyeglasses_lifts10/flute_pass_1s9/airplane_fly_1s5/stamp_pass_1s5/alarmclock_lifts10/hammer_use_3s3/cylindersmall_inspect_1s10/alarmclock_pass_1s9/waterbottle_drink_1s10/banana_pass_1s6/watch_pass_1s1/banana_peel_2s8/pyramidmedium_pass_1s7/cubemedium_lifts6/cup_drink_2s4/cubelarge_pass_1s1/bowl_pass_1s8/wineglass_drink_2s8/phone_call_1s8/torusmedium_lifts4/piggybank_pass_1s9/stamp_pass_1s10/hammer_use_2s9/wineglass_pass_1s8/camera_browse_1s7/airplane_pass_1s6/cup_pass_1s6/airplane_pass_1s9/torussmall_pass_1s8/teapot_pour_2s4/mouse_use_2s10/flashlight_on_2s7/pyramidsmall_pass_1s3/cup_pour_1s1/piggybank_pass_1s5/cubesmall_pass_1s10/airplane_fly_1s8/cylinderlarge_offhand_1s6/gamecontroller_play_1s3/stanfordbunny_pass_1s7/stanfordbunny_lifts9/banana_peel_2s2/apple_lifts10/waterbottle_pour_1s1/alarmclock_pass_1s1/hammer_use_3s1/eyeglasses_clean_1s6/phone_call_1s7/banana_eat_1s4/waterbottle_shake_1s8/waterbottle_pass_1s6/cylinderlarge_lifts9/hand_shake_1s6/camera_browse_1s2/camera_browse_1s4/phone_pass_1s1/stamp_lifts7/torussmall_inspect_1s1/cylindersmall_offhand_1s7/cylinderlarge_lifts2/duck_inspect_1s7/spheremedium_pass_1s8/toruslarge_lifts3/hammer_pass_1s3/cup_offhand_1s2/headphones_use_1s2/train_play_1s10/scissors_use_1s5/cubesmall_lifts10/pyramidsmall_inspect_1s3/mug_drink_4s1/cubemedium_offhand_1s6/apple_eat_1s1/doorknob_use_2s1/cylinderlarge_lifts2/hand_lifts5/gamecontroller_lifts3/waterbottle_lifts3/apple_pass_1s10/flute_play_1s5/spherelarge_inspect_1s7/doorknob_use_1s8/torusmedium_pass_1s4/bowl_pass_1s10/headphones_lifts6/pyramidlarge_pass_1s2/mug_toast_1s4/hammer_use_3s1/stanfordbunny_inspect_1s3/alarmclock_pass_1s8/cylindermedium_inspect_1s1/elephant_lifts6/waterbottle_pass_1s8/cubelarge_lifts3/camera_takepicture_1s5/torussmall_inspect_1s2/airplane_fly_1s7/hammer_use_1s1/spherelarge_lifts1/cubemedium_pass_1s2/headphones_lifts8/piggybank_lifts1/apple_lifts3/spherelarge_inspect_1s8/banana_pass_1s8/stanfordbunny_pass_1s4/flute_play_1s6/banana_eat_1s1/scissors_offhand_1s1/binoculars_lifts10/cup_lifts7/eyeglasses_lifts3/stapler_lifts7/bowl_drink_1s1/cup_drink_1s4/alarmclock_lifts6/headphones_use_1s4/apple_lifts6/mouse_pass_1s7/flashlight_lifts5/torusmedium_inspect_1s10/cup_pour_1s5/toruslarge_lifts10/cup_drink_1s7/cylinderlarge_pass_1s4/wineglass_drink_1s1/stapler_staple_2s10/mug_drink_1s1/flute_pass_1s8/cylinderlarge_lifts10/piggybank_pass_1s7/duck_inspect_1s9/stamp_lifts6/bowl_lifts6/banana_pass_1s9/cubemedium_lifts7/flute_pass_1s8/eyeglasses_wear_1s9/flashlight_lifts9/hammer_use_2s1/cup_pour_1s2/piggybank_lifts8/pyramidlarge_inspect_1s2/teapot_pour_2s6/pyramidsmall_inspect_2s1/toothpaste_pass_1s10/banana_peel_2s1/wineglass_pass_1s5/pyramidlarge_inspect_1s5/cubemedium_inspect_1s7/knife_chop_1s6/mug_toast_1s5/mug_drink_1s6/banana_peel_1s7/cylindermedium_pass_1s10/mug_drink_2s3/elephant_offhand_1s4/stapler_pass_1s1/torussmall_lifts1/duck_lifts5/flute_play_1s1/airplane_fly_1s2/headphones_pass_1s3/lightbulb_screw_1s8/toothbrush_brush_1s10/mouse_use_1s5/flute_play_2s3/waterbottle_pour_2s10/airplane_lifts7/eyeglasses_wear_1s10/stamp_stamp_1s8/cup_drink_1s4/alarmclock_pass_1s3/train_pass_1s2/hammer_use_2s1/pyramidsmall_inspect_1s9/cubesmall_inspect_1s7/camera_browse_1s10/spheresmall_pass_1s1/phone_offhand_1s6/waterbottle_shake_1s1/alarmclock_offhand_1s8/spheresmall_inspect_1s9/cylindermedium_inspect_1s6/knife_lifts6/mouse_lifts1/flashlight_lifts9/cubelarge_pass_1s2/pyramidlarge_pass_1_Retakes7/stanfordbunny_inspect_1s9/gamecontroller_play_1s4/hand_pass_1s3/toothpaste_squeeze_1s9/duck_lifts5/flashlight_on_1s5/cup_lifts10/waterbottle_drink_1s8/cubesmall_pass_1s10/train_lifts10/spheresmall_inspect_1s10/cup_pass_1s1/cubesmall_pass_1s4/fryingpan_cook_3s6/elephant_inspect_1s9/stapler_lifts1/pyramidmedium_offhand_1s9/pyramidmedium_pass_1s9/teapot_pour_2s4/fryingpan_cook_1s1/eyeglasses_wear_1s1/gamecontroller_play_1s3/binoculars_offhand_1s6/waterbottle_pour_1s3/cubesmall_inspect_1s8/pyramidlarge_pass_1s2/train_pass_1s10/mouse_lifts10/torusmedium_pass_1s8/waterbottle_drink_1s7/cubelarge_lifts5/duck_pass_1s1/gamecontroller_offhand_1s2/camera_pass_1s7/gamecontroller_play_1s7/toothbrush_pass_1s8/phone_pass_1s3/bowl_drink_1s6/toruslarge_pass_1s5/spheresmall_inspect_1s8/flashlight_pass_1s1/flashlight_on_2s8/gamecontroller_lifts3/stanfordbunny_lifts8/bowl_pass_1s4/banana_pass_1s6/stapler_lifts2/teapot_lifts3/camera_takepicture_2s8/torussmall_pass_1s9/camera_pass_1s4/apple_eat_1s1/watch_set_1s5/stanfordbunny_lifts6/spheremedium_inspect_1s1/eyeglasses_lifts10/headphones_use_1s3/doorknob_use_1s10/apple_pass_1s9/flute_pass_1s1/toruslarge_inspect_1s5/duck_lifts9/doorknob_use_2s10/torussmall_pass_1s2/doorknob_use_2s1/pyramidlarge_lifts6/stamp_lifts3/elephant_pass_1s7/headphones_use_1s6/cylindermedium_pass_1s6/stapler_staple_2s6/piggybank_pass_1s5/spheremedium_inspect_1s1/cubemedium_inspect_1s4/pyramidmedium_pass_1s7/cylinderlarge_inspect_1s1/cylindermedium_offhand_1s6/toothpaste_squeeze_1_Retakes9/stapler_pass_1s8/flashlight_on_1s5/cup_drink_2s8/apple_lifts8/airplane_pass_1s6/wineglass_pass_1s4/cylinderlarge_inspect_1s4/phone_call_1s5/stapler_pass_1s8/camera_takepicture_2s3/mouse_pass_1s7/pyramidlarge_inspect_1s10/stapler_staple_2s9/teapot_pass_1s5/gamecontroller_play_1s4/train_lifts8/doorknob_lifts1/watch_offhand_1s7/mug_drink_2s4/flashlight_pass_1s1/mug_offhand_1s4/camera_takepicture_3s8/train_pass_1s7/train_pass_1s8/gamecontroller_play_1s1/scissors_use_2s9/piggybank_pass_1s6/flute_lifts1/banana_peel_1s6/bowl_pass_1s1/mouse_pass_1s6/cubesmall_lifts5/airplane_lifts3/scissors_pass_1s2/cylinderlarge_pass_1s6/watch_set_1s10/stamp_pass_1s9/banana_lifts3/toruslarge_lifts10/hammer_use_1s10/cubesmall_lifts6/teapot_pass_1s3/pyramidlarge_offhand_1s8/cylindersmall_inspect_1s3/cylinderlarge_inspect_1s7/teapot_pass_1s9/mouse_pass_1s3/mug_drink_1s2/spheremedium_pass_1s9/waterbottle_pass_1s2/flute_pass_1s9/lightbulb_screw_1s8/cubemedium_pass_1s7/flashlight_pass_1s9/eyeglasses_lifts7/cubemedium_inspect_1s5/waterbottle_lifts6/cup_drink_1s1/pyramidlarge_inspect_1s3/airplane_fly_1s10/pyramidmedium_lifts10/bowl_lifts2/cubelarge_pass_1s7/stapler_staple_1s8/flashlight_on_2s4/cylindersmall_lifts10/stanfordbunny_pass_1s6/cubemedium_lifts10/stapler_pass_1s5/apple_pass_1s7/doorknob_use_2s4/watch_pass_1s1/elephant_pass_1s1/watch_set_2s2/cylinderlarge_inspect_1s2/pyramidlarge_inspect_1s9/eyeglasses_wear_1s4/phone_lifts1/spheremedium_lifts3/airplane_offhand_1s6/spheresmall_pass_1s9/piggybank_lift_Retakes8/cylinderlarge_inspect_1s5/wineglass_lifts3/train_play_1s10/knife_chop_1s9/wineglass_drink_2s6/hammer_lifts9/cylindersmall_pass_1s4/bowl_drink_1s1/mug_toast_1s1/pyramidmedium_inspect_1s9/stamp_stamp_1s10/toothpaste_squeeze_1s1/spheresmall_lifts3/doorknob_use_2s7/fryingpan_cook_1s5/teapot_pass_1s8/phone_lifts2/cubesmall_inspect_1s1/toruslarge_pass_1s6/headphones_pass_1s8/cylinderlarge_pass_1s4/toothpaste_pass_1s4/camera_takepicture_2s3/camera_offhand_1s8/cup_offhand_1s9/spherelarge_pass_1s10/stanfordbunny_lifts1/spheremedium_offhand_1s4/torusmedium_lifts9/cylinderlarge_lifts6/hammer_use_1s4/wineglass_toast_1s2/cylinderlarge_lifts6/cubesmall_inspect_1s1/camera_takepicture_2s3/phone_pass_1s1/hand_inspect_1s8/bowl_drink_2s1/stapler_offhand_1s1/piggybank_use_1s1/apple_pass_1s9/wineglass_drink_1s10/mug_lifts10/cylinderlarge_lifts2/stamp_stamp_1s10/stanfordbunny_inspect_1s4/cubelarge_lifts8/alarmclock_see_1s5/cubelarge_lifts3/eyeglasses_pass_1s1/pyramidsmall_pass_1s2/cylindermedium_pass_1s8/fryingpan_offhand_1s1/mug_drink_3s2/piggybank_pass_1_Retakes8/headphones_lifts9/alarmclock_see_1s5/toruslarge_pass_1s1/stapler_staple_1s1/stanfordbunny_offhand_1s3/airplane_lifts8/cubemedium_inspect_1s9/stapler_staple_2s3/fryingpan_lifts10/spherelarge_inspect_1s7/pyramidlarge_pass_1s5/mouse_lifts8/watch_set_2s3/wineglass_drink_1s6/spheremedium_lifts2/stapler_staple_2s9/airplane_pass_1s6/duck_inspect_1s10/lightbulb_pass_1s8/stapler_pass_1s6/camera_takepicture_3s10/camera_takepicture_2s10/mouse_pass_1s3/cup_drink_2s5/alarmclock_see_1s10/elephant_inspect_1s6/apple_pass_1s3/gamecontroller_pass_1s10/cubemedium_pass_1s5/wineglass_pass_1s5/waterbottle_pass_1s10/teapot_pour_2s6/train_pass_1s7/hammer_use_2s8/apple_pass_1s6/cup_pour_1s7/wineglass_lifts9/toothbrush_pass_1s6/doorknob_lifts9/banana_eat_1s4/cylinderlarge_pass_1s10/cubelarge_lifts1/camera_lifts1/stanfordbunny_pass_1s7/watch_pass_1s9/cup_lifts7/apple_pass_1s3/piggybank_pass_1s1/cylindersmall_inspect_1s4/cup_drink_2s8/spheremedium_pass_1s6/waterbottle_open_1s3/watch_set_1s8/cubesmall_inspect_1s3/duck_inspect_1s7/cylindermedium_inspect_1s9/cylindersmall_inspect_1s1/spherelarge_inspect_1s1/spheresmall_offhand_1s8/cylindermedium_lifts1/bowl_drink_2s5/train_pass_1s4/alarmclock_see_1s8/flashlight_offhand_1s2/cup_drink_1s8/duck_lifts6/cubelarge_pass_1s6/flute_pass_1s2/toruslarge_inspect_1s4/camera_pass_1s7/train_play_1s9/mouse_use_1s5/cylindermedium_pass_1s3/pyramidsmall_pass_1s3/eyeglasses_offhand_1s8/wineglass_toast_1s7/eyeglasses_clean_1s5/toothbrush_brush_1s10/toothpaste_squeeze_2s1/flute_lifts3/toothbrush_pass_1s1/bowl_lifts9/bowl_drink_2s7/banana_peel_2s8/doorknob_use_2s8/torussmall_inspect_1s1/camera_pass_1s8/hand_inspect_1s1/watch_pass_1s10/watch_pass_1s3/toruslarge_inspect_1s9/torusmedium_inspect_1s9/cylindermedium_lifts10/teapot_pass_1s6/wineglass_drink_2s7/headphones_lifts10/stapler_staple_1s2/pyramidmedium_inspect_1s3/flashlight_pass_1s1/torusmedium_pass_1s6/spherelarge_pass_1s2/phone_pass_1s2/pyramidmedium_pass_1s9/stanfordbunny_pass_1s8/pyramidmedium_inspect_1s1/toothbrush_lifts7/hammer_pass_1s8/hand_lifts8/camera_takepicture_3s8/stamp_lifts8/torusmedium_inspect_1s7/phone_call_1s3/pyramidlarge_inspect_1s6/torussmall_pass_1s3/mouse_use_1s6/toruslarge_inspect_1s3/elephant_lifts1/wineglass_drink_2s7/lightbulb_pass_1s8/hammer_pass_1s6/pyramidmedium_inspect_1s8/gamecontroller_pass_1s1/waterbottle_pour_1s9/toothpaste_lifts9/spherelarge_inspect_1s8/teapot_pour_1s4/spheremedium_inspect_1s6/stamp_stamp_1s9/hammer_use_1s1/torusmedium_offhand_1s1/alarmclock_see_1s6/phone_pass_1s5/waterbottle_open_1s4/cubemedium_pass_1s6/apple_lifts1/headphones_pass_1s8/hammer_use_3s3/piggybank_use_1s3/wineglass_toast_1s6/spheresmall_lifts1/camera_takepicture_3_Retakes1/cylindermedium_lifts6/teapot_pour_1s4/train_pass_1s7/toruslarge_inspect_1_Retakes8/cubelarge_pass_1s3/alarmclock_offhand_1s4/hand_lifts8/mug_drink_2s5/cup_pass_1s3/stapler_staple_1s10/phone_lifts6/torusmedium_inspect_1s4/cup_drink_1s2/train_lifts8/stapler_staple_1s2/apple_eat_1s6/torusmedium_pass_1s4/watch_set_1s3/camera_takepicture_3s9/spheresmall_inspect_1s4/cubesmall_pass_1s6/alarmclock_lifts2/toruslarge_pass_1s9/pyramidmedium_inspect_1s3/stanfordbunny_inspect_1s6/scissors_use_2s1/stamp_stamp_1s3/torusmedium_pass_1s6/eyeglasses_pass_1s7/cubelarge_inspect_1s3/stamp_lifts8/mouse_pass_1s7/elephant_inspect_1s8/camera_pass_1s10/bowl_pass_1s1/waterbottle_lifts8/bowl_lifts3/phone_call_1s8/phone_offhand_1s3/eyeglasses_wear_1s6/bowl_drink_1_Retakes9/torussmall_inspect_1s1/piggybank_offhand_1s1/mug_drink_2s4/airplane_fly_1s8/cubelarge_offhand_1s10/camera_pass_1s4/stanfordbunny_inspect_1s6/pyramidlarge_inspect_1s10/wineglass_drink_2s1/duck_inspect_1s4/duck_inspect_1s1/mouse_use_1s5/eyeglasses_clean_2s10/camera_takepicture_1s8/fryingpan_pass_1s10/cubelarge_inspect_1s7/hammer_use_3s5/spherelarge_lifts1/fryingpan_cook_1s5/cubemedium_pass_1s3/flute_play_1s9/headphones_use_1s1/cylinderlarge_inspect_1s7/hammer_lifts7/wineglass_toast_1s4/pyramidmedium_inspect_1s10/bowl_drink_1_Retakes9/piggybank_use_1s1/cubesmall_lifts1/fryingpan_cook_2s1/apple_eat_1s9/watch_set_2s9/bowl_lifts10/hand_lifts10/cylindersmall_inspect_1s1/piggybank_lifts2/toothpaste_squeeze_1s6/binoculars_see_1s6/spherelarge_inspect_1s8/alarmclock_lifts1/cylindersmall_pass_1s6/pyramidlarge_lifts4/binoculars_pass_1s10/bowl_drink_2s5/flute_pass_1s10/torusmedium_lifts1/duck_pass_1s2/cubelarge_inspect_1s8/watch_pass_1s1/waterbottle_open_1s9/flute_play_1s9/airplane_lifts1/mug_drink_4s4/wineglass_pass_1s6/camera_pass_1s4/duck_pass_1s10/cylindersmall_pass_1s10/alarmclock_lift_Retakes4/toruslarge_pass_1s10/wineglass_pass_1s5/cylindermedium_lifts2/pyramidlarge_lifts3/flute_offhand_1s8/camera_offhand_1s2/elephant_inspect_1s5/mug_pass_1s3/hammer_use_1s9/mug_drink_2s5/wineglass_drink_2s5/piggybank_lifts9/waterbottle_open_1s7/alarmclock_lifts1/eyeglasses_offhand_1s1/flute_play_1s8/wineglass_lifts7/waterbottle_shake_1s1/cubelarge_inspect_1s1/hammer_use_2s5/doorknob_lifts1/spheremedium_inspect_1s9/spheremedium_pass_1s6/knife_peel_1s4/fryingpan_pass_1s3/binoculars_lifts7/toruslarge_lifts4/piggybank_lifts3/cubelarge_pass_1s2/banana_peel_1s1/alarmclock_lifts5/train_lifts1/cup_pass_1s1/waterbottle_drink_1s3/bowl_drink_2s5/cylinderlarge_inspect_1s4/headphones_use_1s3/hand_pass_1s3/flashlight_on_1s3/toruslarge_pass_1s9/flashlight_on_1s8/mug_offhand_1s8/cubesmall_lifts10/airplane_pass_112345678s1/airplane_fly_1s1/airplane_lifts1/airplane_offhand_1s1/airplane_pass_1s1/alarmclock_offhand_1s1/alarmclock_pass_1s1/alarmclock_see_1s1/apple_eat_11custom/s5/airplane_pass_11s3/airplane_pass_112345678910111213141516from .dataloader import build_dataloaderfrom .dataset import Text2MotionDatasetfrom .evaluator import (EvaluationDataset, EvaluatorModelWrapper, get_dataset_motion_loader, get_motion_loader)
from .utils import drop_shapes_from_motion_arr# from .rendering import render_meshesfrom .motionx_explorer import (load_data_as_dict, motion_arr_to_dict, smplx_dict_to_array, to_smplx_dict)
__all__ = [ 'Text2MotionDataset', 'EvaluationDataset', 'build_dataloader', 'get_dataset_motion_loader', 'get_motion_loader', 'EvaluatorModelWrapper', 'load_data_as_dict', 'motion_arr_to_dict', 'smplx_dict_to_array', 'drop_shapes_from_motion_arr', 'render_meshes', 'to_smplx_dict']123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687import osimport re
from PIL import Image, ImageDraw, ImageFont, ImageSequence
def combine_gifs_with_timestep(gif_paths, output_path): """ Combines multiple GIF files into a single GIF, adding a timestep extracted from each file's name.
:param gif_paths: List of paths to the GIF files. :param output_path: Path where the combined GIF will be saved. """ frames = [] for gif_path in gif_paths: # Extract timestep from filename using regular expressions timestep = re.search(r'sample_tensor\(\[(\d+)\]\)', gif_path) if timestep: timestep = timestep.group(1) else: print(f"error: Timestep not found in filename {gif_path}. Skipping this file.") exit(1)
start_i = 0 n_frames_keep = 30 tot_frames = 30 min_frames = 20 # Open the GIF with Image.open(gif_path) as img: # Loop over each frame in the GIF # so lower the timestep, the more frames we keep n_frames_keep = (999-int(timestep))/999 * tot_frames + min_frames for i, frame in enumerate(ImageSequence.Iterator(img)): if i >= start_i: # if int(timestep) >= 50 and i >= (n_frames_keep + start_i): # break # Stop after 10 frames # elif int(timestep) < 50 and int(timestep) >= 20 and i >= n_frames_keep + start_i: # break # elif int(timestep) < 20 and int(timestep) > 0 and i >= n_frames_keep + start_i: # break if int(timestep) > 0 and i >= n_frames_keep + start_i: break # elif int(timestep) == 999 and i >= n_frames_keep + start_i: # break # Convert the frame to RGB mode and draw the timestep on it frame = frame.convert("RGBA") d = ImageDraw.Draw(frame)
# Load a font - you can adjust the size and font type as needed font_path = '/work3/s222376/MotionDiffuse2/text2motion/datasets/arial.ttf' font_large = ImageFont.truetype(font_path, 20) # Large font for the timestep number font_small = ImageFont.truetype(font_path, 20) # Small font for the word 'timestep'
# Calculate text size and position number_size = d.textsize(timestep, font=font_large) # label_size = d.textsize("timestep", font=font_small) # total_width = number_size[0] + label_size[0] # x_number = (frame.width - total_width) // 2 # y = 10 # 10 pixels from the top y_offset = 100 x_offset = 20 center = (frame.width // 2 - x_offset, frame.height // 2 - y_offset) # Draw the timestep number and label color = (0,0,0) d.text((10,10), f"t={timestep}", font=font_large, fill=color) # d.text((x_number + number_size[0], y + (number_size[1] - label_size[1]) // 2), "timestep", font=font_small, fill=color)
frames.append(frame)
# Save the frames as a new GIF frames[0].save(output_path, save_all=True, append_images=frames[1:], loop=0)
# Example usagedir = "/work3/s222376/MotionDiffuse2/text2motion/gifs/md_fulem_2g_excl_196_seed42/"# list all files in dir# gif_paths = [f for f in os.listdir(dir) if os.path.isfile(os.path.join(dir, f))]# # filter but contians 'sample_tensor' and 'happiness'# gif_paths = [f for f in gif_paths if 'sample_tensor' in f and 'happiness' in f]# # reverse sort by timestep# gif_paths.sort(key=lambda f: int(re.search(r'sample_tensor\(\[(\d+)\]\)', f).group(1)), reverse=True)# print(gif_paths)times = [999, 80, 10, 0]gif_paths = [f'sample_tensor([{t}])_happiness.gif' for t in times]full_gif_paths = [os.path.join(dir, gif_path) for gif_path in gif_paths]output_path = f'{dir}combined_gif.gif' # Replace with your desired output file pathcombine_gifs_with_timestep(full_gif_paths, output_path)print(f"Combined GIF saved to {output_path}")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import randomfrom functools import partialfrom typing import Optional, Union
import numpy as npfrom mmcv.runner import get_dist_infofrom torch.utils.data import DataLoaderfrom torch.utils.data.dataset import Dataset
import torchfrom torch.utils.data import DistributedSampler as _DistributedSampler
class DistributedSampler(_DistributedSampler):
def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True, round_up=True): super().__init__(dataset, num_replicas=num_replicas, rank=rank) self.shuffle = shuffle self.round_up = round_up if self.round_up: self.total_size = self.num_samples * self.num_replicas else: self.total_size = len(self.dataset)
def __iter__(self): # deterministically shuffle based on epoch if self.shuffle: g = torch.Generator() g.manual_seed(self.epoch) indices = torch.randperm(len(self.dataset), generator=g).tolist() else: indices = torch.arange(len(self.dataset)).tolist()
# add extra samples to make it evenly divisible if self.round_up: indices = ( indices * int(self.total_size / len(indices) + 1))[:self.total_size] assert len(indices) == self.total_size
# subsample indices = indices[self.rank:self.total_size:self.num_replicas] if self.round_up: assert len(indices) == self.num_samples
return iter(indices)
def build_dataloader(dataset: Dataset, samples_per_gpu: int, workers_per_gpu: int, num_gpus: Optional[int] = 1, dist: Optional[bool] = True, shuffle: Optional[bool] = True, round_up: Optional[bool] = True, seed: Optional[Union[int, None]] = None, persistent_workers: Optional[bool] = True, **kwargs): """Build PyTorch DataLoader.
In distributed training, each GPU/process has a dataloader. In non-distributed training, there is only one dataloader for all GPUs.
Args: dataset (:obj:`Dataset`): A PyTorch dataset. samples_per_gpu (int): Number of training samples on each GPU, i.e., batch size of each GPU. workers_per_gpu (int): How many subprocesses to use for data loading for each GPU. num_gpus (int, optional): Number of GPUs. Only used in non-distributed training. dist (bool, optional): Distributed training/test or not. Default: True. shuffle (bool, optional): Whether to shuffle the data at every epoch. Default: True. round_up (bool, optional): Whether to round up the length of dataset by adding extra samples to make it evenly divisible. Default: True. persistent_workers (bool): If True, the data loader will not shutdown the worker processes after a dataset has been consumed once. This allows to maintain the workers Dataset instances alive. The argument also has effect in PyTorch>=1.7.0. Default: True kwargs: any keyword argument to be used to initialize DataLoader
Returns: DataLoader: A PyTorch dataloader. """ rank, world_size = get_dist_info() if dist: sampler = DistributedSampler( dataset, world_size, rank, shuffle=shuffle, round_up=round_up) shuffle = False batch_size = samples_per_gpu num_workers = workers_per_gpu else: sampler = None batch_size = num_gpus * samples_per_gpu num_workers = num_gpus * workers_per_gpu
init_fn = partial( worker_init_fn, num_workers=num_workers, rank=rank, seed=seed) if seed is not None else None
data_loader = DataLoader( dataset, batch_size=batch_size, sampler=sampler, num_workers=num_workers, pin_memory=False, shuffle=shuffle, worker_init_fn=init_fn, persistent_workers=persistent_workers, **kwargs)
return data_loader
def worker_init_fn(worker_id: int, num_workers: int, rank: int, seed: int): """Init random seed for each worker.""" # The seed of each worker equals to # num_worker * rank + worker_id + user_seed worker_seed = num_workers * rank + worker_id + seed np.random.seed(worker_seed) random.seed(worker_seed)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194import codecs as csimport osimport randomfrom os.path import join as pjoin
import numpy as npimport torchfrom torch.utils import datafrom tqdm import tqdm
from .utils import drop_shapes_from_motion_arr, load_label_from_file
class Text2MotionDataset(data.Dataset): """Dataset for Text2Motion generation task.
""" def __init__(self, opt, mean, std, split_file, times=1, w_vectorizer=None, eval_mode=False): self.opt = opt self.max_length = 20 self.times = times self.w_vectorizer = w_vectorizer self.eval_mode = eval_mode min_motion_len = 40 if self.opt.dataset_name =='t2m' else 24
joints_num = opt.joints_num
data_dict = {} id_list = [] print(f"split file: {split_file}") with cs.open(split_file, 'r') as f: for line in f.readlines(): id_list.append(line.strip())
new_name_list = [] length_list = [] print(f"id-list length: {len(id_list)}") for name in tqdm(id_list): try: print(f"attempting to load motion for {name} at {pjoin(opt.motion_dir, name + '.npy')}") motion = np.load(pjoin(opt.motion_dir, name + '.npy')) if self.opt.dataset_name.lower() == 'grab': motion = drop_shapes_from_motion_arr(motion) assert motion.shape[-1] == opt.dim_pose, f"motion shape {motion.shape} does not match dim_pose {opt.dim_pose}" print(f"grab motion shape: {motion.shape}") print(f"len of motion: {len(motion)}") # TODO (elmc): verify we don't need this for GRAB data # if (len(motion)) < min_motion_len or (len(motion) >= 200): # continue text_data = [] flag = False with cs.open(pjoin(opt.text_dir, name + '.txt')) as f: for line in f.readlines(): text_dict = {} line_split = line.strip().split('#') caption = line_split[0] # append face_text to caption emotion_label = load_label_from_file(pjoin(opt.face_text_dir, name + '.txt')) caption = f"{emotion_label} {caption}" f_tag = 0.0 to_tag = 0.0 # TODO (elmc): add actual tokens back for grab tokens = [] if self.opt.dataset_name.lower() != 'grab': tokens = line_split[1].split(' ') f_tag = float(line_split[2]) to_tag = float(line_split[3]) f_tag = 0.0 if np.isnan(f_tag) else f_tag to_tag = 0.0 if np.isnan(to_tag) else to_tag
text_dict['caption'] = caption text_dict['tokens'] = tokens if f_tag == 0.0 and to_tag == 0.0: flag = True text_data.append(text_dict) else: n_motion = motion[int(f_tag*20) : int(to_tag*20)] if (len(n_motion)) < min_motion_len or (len(n_motion) >= 200): continue new_name = random.choice('ABCDEFGHIJKLMNOPQRSTUVW') + '_' + name while new_name in data_dict: new_name = random.choice('ABCDEFGHIJKLMNOPQRSTUVW') + '_' + name data_dict[new_name] = {'motion': n_motion, 'length': len(n_motion), 'text':[text_dict]} new_name_list.append(new_name) length_list.append(len(n_motion))
if flag: data_dict[name] = {'motion': motion, 'length': len(motion), 'text':text_data} new_name_list.append(name) length_list.append(len(motion)) except Exception as e: # Some motion may not exist in KIT dataset print(f"failed to load motion for {name} at {pjoin(opt.motion_dir, name + '.npy')} due to {e}")
if not new_name_list or not length_list: raise ValueError(f'No data loaded, new_name_list has len {len(new_name_list)} and length_list has len {len(length_list)}') name_list, length_list = zip(*sorted(zip(new_name_list, length_list), key=lambda x: x[1])) print(f"LOADED length of name_list: {len(name_list)}") # TODO (elmc): calculate mean and std and save to load here? if opt.is_train: # # TODO (elle): how best to standardize the data?
# # root_rot_velocity (B, seq_len, 1) # std[0:1] = std[0:1] / opt.feat_bias # # root_linear_velocity (B, seq_len, 2) # std[1:3] = std[1:3] / opt.feat_bias # # root_y (B, seq_len, 1) # std[3:4] = std[3:4] / opt.feat_bias # # ric_data (B, seq_len, (joint_num - 1)*3) # std[4: 4 + (joints_num - 1) * 3] = std[4: 4 + (joints_num - 1) * 3] / 1.0 # # rot_data (B, seq_len, (joint_num - 1)*6) # std[4 + (joints_num - 1) * 3: 4 + (joints_num - 1) * 9] = std[4 + (joints_num - 1) * 3: 4 + ( # joints_num - 1) * 9] / 1.0 # # local_velocity (B, seq_len, joint_num*3) # std[4 + (joints_num - 1) * 9: 4 + (joints_num - 1) * 9 + joints_num * 3] = std[ # 4 + (joints_num - 1) * 9: 4 + ( # joints_num - 1) * 9 + joints_num * 3] / 1.0 # # foot contact (B, seq_len, 4) # std[4 + (joints_num - 1) * 9 + joints_num * 3:] = std[ # 4 + (joints_num - 1) * 9 + joints_num * 3:] / opt.feat_bias
# assert 4 + (joints_num - 1) * 9 + joints_num * 3 + 4 == mean.shape[-1] # TODO (elmc): add back in np.save(pjoin(opt.meta_dir, 'mean.npy'), mean) np.save(pjoin(opt.meta_dir, 'std.npy'), std)
self.mean = mean self.std = std self.length_arr = np.array(length_list) self.data_dict = data_dict self.name_list = name_list
def inv_transform(self, data): return data * self.std + self.mean
def real_len(self): return len(self.data_dict)
def __len__(self): # authors explain why they multiple self.times here instead of increasing epochs # https://github.com/mingyuan-zhang/MotionDiffuse/issues/12 # also say it's not necessary set use persistent_workers = True in build_dataloader return self.real_len() * self.times
def __getitem__(self, item): idx = item % self.real_len() data = self.data_dict[self.name_list[idx]] motion, m_length, text_list = data['motion'], data['length'], data['text'] # Randomly select a caption text_data = random.choice(text_list) caption = text_data['caption'] max_motion_length = self.opt.max_motion_length # TODO (elmc): delete this and replace with if m_length >= self..etc # motion = motion[:max_motion_length] # TODO (elmc): add back in if m_length >= self.opt.max_motion_length: idx = random.randint(0, len(motion) - max_motion_length) motion = motion[idx: idx + max_motion_length] else: padding_len = max_motion_length - m_length D = motion.shape[1] padding_zeros = np.zeros((padding_len, D)) motion = np.concatenate((motion, padding_zeros), axis=0)
assert len(motion) == max_motion_length "Z Normalization" # TODO (elmc): add standardization back in motion = (motion - self.mean) / self.std
if self.eval_mode: tokens = text_data['tokens'] if len(tokens) < self.opt.max_text_len: # pad with "unk" tokens = ['sos/OTHER'] + tokens + ['eos/OTHER'] sent_len = len(tokens) tokens = tokens + ['unk/OTHER'] * (self.opt.max_text_len + 2 - sent_len) else: # crop tokens = tokens[:self.opt.max_text_len] tokens = ['sos/OTHER'] + tokens + ['eos/OTHER'] sent_len = len(tokens) pos_one_hots = [] word_embeddings = [] for token in tokens: word_emb, pos_oh = self.w_vectorizer[token] pos_one_hots.append(pos_oh[None, :]) word_embeddings.append(word_emb[None, :]) pos_one_hots = np.concatenate(pos_one_hots, axis=0) word_embeddings = np.concatenate(word_embeddings, axis=0) return word_embeddings, pos_one_hots, caption, sent_len, motion, m_length return caption, motion, m_length123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469import codecs as csimport osimport randomfrom os.path import join as pjoin
import numpy as npimport torchfrom torch.utils.data import DataLoader, Datasetfrom torch.utils.data._utils.collate import default_collatefrom tqdm import tqdm
from models import MotionTransformerfrom utils.get_opt import get_optfrom utils.word_vectorizer import POS_enumerator, WordVectorizer
from .evaluator_models import *from .utils import drop_shapes_from_motion_arr
class EvaluationDataset(Dataset):
def __init__(self, opt, trainer, dataset, w_vectorizer, mm_num_samples, mm_num_repeats): assert mm_num_samples < len(dataset) print(opt.model_dir)
dataloader = DataLoader(dataset, batch_size=1, num_workers=1, shuffle=True) epoch, it = trainer.load(pjoin(opt.model_dir, opt.which_epoch + '.tar'))
generated_motion = [] min_mov_length = 10 if opt.dataset_name == 't2m' else 6
trainer.eval_mode() trainer.to(opt.device)
# Pre-process all target captions mm_generated_motions = [] mm_idxs = np.random.choice(len(dataset), mm_num_samples, replace=False) mm_idxs = np.sort(mm_idxs) all_caption = [] all_m_lens = [] all_data = [] with torch.no_grad(): for i, data in tqdm(enumerate(dataloader)): word_emb, pos_ohot, caption, cap_lens, motions, m_lens, tokens = data all_data.append(data) tokens = tokens[0].split('_') mm_num_now = len(mm_generated_motions) is_mm = True if ((mm_num_now < mm_num_samples) and (i == mm_idxs[mm_num_now])) else False repeat_times = mm_num_repeats if is_mm else 1 m_lens = max(m_lens // opt.unit_length * opt.unit_length, min_mov_length * opt.unit_length) m_lens = min(m_lens, opt.max_motion_length) if isinstance(m_lens, int): m_lens = torch.LongTensor([m_lens]).to(opt.device) else: m_lens = m_lens.to(opt.device) for t in range(repeat_times): all_m_lens.append(m_lens) all_caption.extend(caption) if is_mm: mm_generated_motions.append(0) all_m_lens = torch.stack(all_m_lens) # Generate all sequences with torch.no_grad(): all_pred_motions = trainer.generate(all_caption, all_m_lens, opt.dim_pose) cur_idx = 0 mm_generated_motions = [] with torch.no_grad(): for i, data_dummy in tqdm(enumerate(dataloader)): data = all_data[i] word_emb, pos_ohot, caption, cap_lens, motions, m_lens, tokens = data tokens = tokens[0].split('_') mm_num_now = len(mm_generated_motions) is_mm = True if ((mm_num_now < mm_num_samples) and (i == mm_idxs[mm_num_now])) else False repeat_times = mm_num_repeats if is_mm else 1 mm_motions = [] m_lens = max(m_lens // opt.unit_length * opt.unit_length, min_mov_length * opt.unit_length) m_lens = min(m_lens, opt.max_motion_length) if isinstance(m_lens, int): m_lens = torch.LongTensor([m_lens]).to(opt.device) else: m_lens = m_lens.to(opt.device) for t in range(repeat_times): m_len = m_lens[0].item() pred_motions = all_pred_motions[cur_idx][:m_lens[0].item()] assert pred_motions.shape[0] == m_lens[0].item() cur_idx += 1 if t == 0: sub_dict = {'motion': pred_motions.cpu().numpy(), 'length': pred_motions.shape[0], 'caption': caption[0], 'cap_len': cap_lens[0].item(), 'tokens': tokens} generated_motion.append(sub_dict)
if is_mm: mm_motions.append({ 'motion': pred_motions.cpu().numpy(), 'length': m_lens[0].item() }) if is_mm: mm_generated_motions.append({'caption': caption[0], 'tokens': tokens, 'cap_len': cap_lens[0].item(), 'mm_motions': mm_motions}) self.generated_motion = generated_motion self.mm_generated_motion = mm_generated_motions self.opt = opt self.w_vectorizer = w_vectorizer
def __len__(self): return len(self.generated_motion)
def __getitem__(self, item): data = self.generated_motion[item] motion, m_length, caption, tokens = data['motion'], data['length'], data['caption'], data['tokens'] sent_len = data['cap_len'] pos_one_hots = [] word_embeddings = [] for token in tokens: word_emb, pos_oh = self.w_vectorizer[token] pos_one_hots.append(pos_oh[None, :]) word_embeddings.append(word_emb[None, :]) pos_one_hots = np.concatenate(pos_one_hots, axis=0) word_embeddings = np.concatenate(word_embeddings, axis=0)
if m_length < self.opt.max_motion_length: motion = np.concatenate([motion, np.zeros((self.opt.max_motion_length - m_length, motion.shape[1])) ], axis=0) return word_embeddings, pos_one_hots, caption, sent_len, motion, m_length, '_'.join(tokens)
def collate_fn(batch): batch.sort(key=lambda x: x[3], reverse=True) return default_collate(batch)
'''For use of training text motion matching model, and evaluations'''class Text2MotionDatasetV2(Dataset): def __init__(self, opt, mean, std, split_file, w_vectorizer): self.opt = opt self.w_vectorizer = w_vectorizer self.max_length = 20 self.pointer = 0 self.max_motion_length = opt.max_motion_length min_motion_len = 40 if self.opt.dataset_name =='t2m' else 24
data_dict = {} id_list = [] with cs.open(split_file, 'r') as f: for line in f.readlines(): id_list.append(line.strip())
new_name_list = [] length_list = [] for name in tqdm(id_list): try: print(f"attempting to load motion for {name} at {pjoin(opt.motion_dir, name + '.npy')}") motion = np.load(pjoin(opt.motion_dir, name + '.npy')) if self.opt.dataset_name.lower() == 'grab': motion = drop_shapes_from_motion_arr(motion) assert motion.shape[-1] == opt.dim_pose, f"motion shape {motion.shape} does not match dim_pose {opt.dim_pose}" print(f"grab motion shape: {motion.shape}") print(f"len of motion: {len(motion)}") # TODO (elmc): verify we don't need this for GRAB data # if (len(motion)) < min_motion_len or (len(motion) >= 200): # continue text_data = [] flag = False with cs.open(pjoin(opt.text_dir, name + '.txt')) as f: for line in f.readlines(): text_dict = {} line_split = line.strip().split('#') caption = line_split[0] f_tag = 0.0 to_tag = 0.0 # TODO (elmc): add actual tokens back for grab tokens = [] if self.opt.dataset_name.lower() != 'grab': tokens = line_split[1].split(' ') f_tag = float(line_split[2]) to_tag = float(line_split[3]) f_tag = 0.0 if np.isnan(f_tag) else f_tag to_tag = 0.0 if np.isnan(to_tag) else to_tag
text_dict['caption'] = caption text_dict['tokens'] = tokens if f_tag == 0.0 and to_tag == 0.0: flag = True text_data.append(text_dict) else: n_motion = motion[int(f_tag*20) : int(to_tag*20)] if (len(n_motion)) < min_motion_len or (len(n_motion) >= 200): continue new_name = random.choice('ABCDEFGHIJKLMNOPQRSTUVW') + '_' + name while new_name in data_dict: new_name = random.choice('ABCDEFGHIJKLMNOPQRSTUVW') + '_' + name data_dict[new_name] = {'motion': n_motion, 'length': len(n_motion), 'text':[text_dict]} new_name_list.append(new_name) length_list.append(len(n_motion))
if flag: data_dict[name] = {'motion': motion, 'length': len(motion), 'text':text_data} new_name_list.append(name) length_list.append(len(motion)) except Exception as e: # Some motion may not exist in KIT dataset print(f"failed to load motion for {name} at {pjoin(opt.motion_dir, name + '.npy')} due to {e}") pass
if not new_name_list or not length_list: raise ValueError(f'No data loaded, new_name_list has len {len(new_name_list)} and length_list has len {len(length_list)}') name_list, length_list = zip(*sorted(zip(new_name_list, length_list), key=lambda x: x[1])) print(f"LOADED length of name_list: {len(name_list)}") self.mean = mean self.std = std self.length_arr = np.array(length_list) self.data_dict = data_dict self.name_list = name_list # TODO (elmc): so.... V2 is same as V1 but has reset_max_len?? self.reset_max_len(self.max_length)
def reset_max_len(self, length): assert length <= self.max_motion_length self.pointer = np.searchsorted(self.length_arr, length) print("Pointer Pointing at %d"%self.pointer) self.max_length = length
def inv_transform(self, data): return data * self.std + self.mean
def __len__(self): return len(self.data_dict) - self.pointer
def __getitem__(self, item): idx = self.pointer + item data = self.data_dict[self.name_list[idx]] motion, m_length, text_list = data['motion'], data['length'], data['text'] # Randomly select a caption text_data = random.choice(text_list) caption, tokens = text_data['caption'], text_data['tokens']
if len(tokens) < self.opt.max_text_len: # pad with "unk" tokens = ['sos/OTHER'] + tokens + ['eos/OTHER'] sent_len = len(tokens) tokens = tokens + ['unk/OTHER'] * (self.opt.max_text_len + 2 - sent_len) else: # crop tokens = tokens[:self.opt.max_text_len] tokens = ['sos/OTHER'] + tokens + ['eos/OTHER'] sent_len = len(tokens) pos_one_hots = [] word_embeddings = [] for token in tokens: word_emb, pos_oh = self.w_vectorizer[token] pos_one_hots.append(pos_oh[None, :]) word_embeddings.append(word_emb[None, :]) pos_one_hots = np.concatenate(pos_one_hots, axis=0) word_embeddings = np.concatenate(word_embeddings, axis=0)
# Crop the motions in to times of 4, and introduce small variations if self.opt.unit_length < 10: coin2 = np.random.choice(['single', 'single', 'double']) else: coin2 = 'single'
if coin2 == 'double': m_length = (m_length // self.opt.unit_length - 1) * self.opt.unit_length elif coin2 == 'single': m_length = (m_length // self.opt.unit_length) * self.opt.unit_length idx = random.randint(0, len(motion) - m_length) motion = motion[idx:idx+m_length]
"Z Normalization" motion = (motion - self.mean) / self.std
if m_length < self.max_motion_length: motion = np.concatenate([motion, np.zeros((self.max_motion_length - m_length, motion.shape[1])) ], axis=0) return word_embeddings, pos_one_hots, caption, sent_len, motion, m_length, '_'.join(tokens)
def get_dataset_motion_loader(opt_path, batch_size, device): opt = get_opt(opt_path, device)
# Configurations of T2M dataset and KIT dataset is almost the same if opt.dataset_name == 't2m' or opt.dataset_name == 'kit' or opt.dataset_name == 'grab': print('Loading dataset %s ...' % opt.dataset_name)
mean_path = pjoin(opt.meta_dir, 'mean.npy') std_path = pjoin(opt.meta_dir, 'std.npy') if not os.path.exists(mean_path): mean = np.zeros(opt.dim_pose) else: mean = np.load(pjoin(opt.meta_dir, 'mean.npy')) if not os.path.exists(std_path): std = np.ones(opt.dim_pose) else: std = np.load(pjoin(opt.meta_dir, 'std.npy'))
# get glove data via following instructions here # https://github.com/mingyuan-zhang/MotionDiffuse/blob/main/text2motion/install.md#data-preparation w_vectorizer = WordVectorizer('./data/glove', 'our_vab') split_file = pjoin(opt.data_root, 'test.txt') dataset = Text2MotionDatasetV2(opt, mean, std, split_file, w_vectorizer) dataloader = DataLoader(dataset, batch_size=batch_size, num_workers=4, drop_last=True, collate_fn=collate_fn, shuffle=True) else: raise KeyError('Dataset not Recognized !!')
print('Ground Truth Dataset Loading Completed!!!') return dataloader, dataset
class MMGeneratedDataset(Dataset): def __init__(self, opt, motion_dataset, w_vectorizer): self.opt = opt self.dataset = motion_dataset.mm_generated_motion self.w_vectorizer = w_vectorizer
def __len__(self): return len(self.dataset)
def __getitem__(self, item): data = self.dataset[item] mm_motions = data['mm_motions'] m_lens = [] motions = [] for mm_motion in mm_motions: m_lens.append(mm_motion['length']) motion = mm_motion['motion'] if len(motion) < self.opt.max_motion_length: motion = np.concatenate([motion, np.zeros((self.opt.max_motion_length - len(motion), motion.shape[1])) ], axis=0) motion = motion[None, :] motions.append(motion) m_lens = np.array(m_lens, dtype=np.int) motions = np.concatenate(motions, axis=0) sort_indx = np.argsort(m_lens)[::-1].copy() # print(m_lens) # print(sort_indx) # print(m_lens[sort_indx]) m_lens = m_lens[sort_indx] motions = motions[sort_indx] return motions, m_lens
def get_motion_loader(opt, batch_size, trainer, ground_truth_dataset, mm_num_samples, mm_num_repeats):
# Currently the configurations of two datasets are almost the same if opt.dataset_name == 't2m' or opt.dataset_name == 'kit': w_vectorizer = WordVectorizer('./data/glove', 'our_vab') else: raise KeyError('Dataset not recognized!!') print('Generating %s ...' % opt.name)
dataset = EvaluationDataset(opt, trainer, ground_truth_dataset, w_vectorizer, mm_num_samples, mm_num_repeats) mm_dataset = MMGeneratedDataset(opt, dataset, w_vectorizer)
motion_loader = DataLoader(dataset, batch_size=batch_size, collate_fn=collate_fn, drop_last=True, num_workers=4) mm_motion_loader = DataLoader(mm_dataset, batch_size=1, num_workers=1)
print('Generated Dataset Loading Completed!!!')
return motion_loader, mm_motion_loader
def build_models(opt): movement_enc = MovementConvEncoder(opt.dim_pose-4, opt.dim_movement_enc_hidden, opt.dim_movement_latent) text_enc = TextEncoderBiGRUCo(word_size=opt.dim_word, pos_size=opt.dim_pos_ohot, hidden_size=opt.dim_text_hidden, output_size=opt.dim_coemb_hidden, device=opt.device)
motion_enc = MotionEncoderBiGRUCo(input_size=opt.dim_movement_latent, hidden_size=opt.dim_motion_hidden, output_size=opt.dim_coemb_hidden, device=opt.device)
checkpoint = torch.load(pjoin('data/pretrained_models', opt.dataset_name, 'text_mot_match', 'model', 'finest.tar'), map_location=opt.device) movement_enc.load_state_dict(checkpoint['movement_encoder']) text_enc.load_state_dict(checkpoint['text_encoder']) motion_enc.load_state_dict(checkpoint['motion_encoder']) print('Loading Evaluation Model Wrapper (Epoch %d) Completed!!' % (checkpoint['epoch'])) return text_enc, motion_enc, movement_enc
class EvaluatorModelWrapper(object):
def __init__(self, opt):
if opt.dataset_name == 't2m': opt.dim_pose = 263 elif opt.dataset_name == 'kit': opt.dim_pose = 251 elif opt.dataset_name == 'grab': opt.dim_pose = 212 else: raise KeyError('Dataset not Recognized!!!')
opt.dim_word = 300 opt.max_motion_length = 196 opt.dim_pos_ohot = len(POS_enumerator) opt.dim_motion_hidden = 1024 opt.max_text_len = 20 opt.dim_text_hidden = 512 opt.dim_coemb_hidden = 512
self.text_encoder, self.motion_encoder, self.movement_encoder = build_models(opt) self.opt = opt self.device = opt.device
self.text_encoder.to(opt.device) self.motion_encoder.to(opt.device) self.movement_encoder.to(opt.device)
self.text_encoder.eval() self.motion_encoder.eval() self.movement_encoder.eval()
# Please note that the results does not following the order of inputs def get_co_embeddings(self, word_embs, pos_ohot, cap_lens, motions, m_lens): with torch.no_grad(): word_embs = word_embs.detach().to(self.device).float() pos_ohot = pos_ohot.detach().to(self.device).float() motions = motions.detach().to(self.device).float()
align_idx = np.argsort(m_lens.data.tolist())[::-1].copy() motions = motions[align_idx] m_lens = m_lens[align_idx]
'''Movement Encoding''' movements = self.movement_encoder(motions[..., :-4]).detach() m_lens = m_lens // self.opt.unit_length motion_embedding = self.motion_encoder(movements, m_lens)
'''Text Encoding''' text_embedding = self.text_encoder(word_embs, pos_ohot, cap_lens) text_embedding = text_embedding[align_idx] return text_embedding, motion_embedding
# Please note that the results does not following the order of inputs def get_motion_embeddings(self, motions, m_lens): with torch.no_grad(): motions = motions.detach().to(self.device).float()
align_idx = np.argsort(m_lens.data.tolist())[::-1].copy() motions = motions[align_idx] m_lens = m_lens[align_idx]
'''Movement Encoding''' movements = self.movement_encoder(motions[..., :-4]).detach() m_lens = m_lens // self.opt.unit_length motion_embedding = self.motion_encoder(movements, m_lens) return motion_embedding123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438import torchimport torch.nn as nnimport numpy as npimport timeimport mathfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence# from networks.layers import *import torch.nn.functional as F
class ContrastiveLoss(torch.nn.Module): """ Contrastive loss function. Based on: http://yann.lecun.com/exdb/publis/pdf/hadsell-chopra-lecun-06.pdf """ def __init__(self, margin=3.0): super(ContrastiveLoss, self).__init__() self.margin = margin
def forward(self, output1, output2, label): euclidean_distance = F.pairwise_distance(output1, output2, keepdim=True) loss_contrastive = torch.mean((1-label) * torch.pow(euclidean_distance, 2) + (label) * torch.pow(torch.clamp(self.margin - euclidean_distance, min=0.0), 2)) return loss_contrastive
def init_weight(m): if isinstance(m, nn.Conv1d) or isinstance(m, nn.Linear) or isinstance(m, nn.ConvTranspose1d): nn.init.xavier_normal_(m.weight) # m.bias.data.fill_(0.01) if m.bias is not None: nn.init.constant_(m.bias, 0)
def reparameterize(mu, logvar): s_var = logvar.mul(0.5).exp_() eps = s_var.data.new(s_var.size()).normal_() return eps.mul(s_var).add_(mu)
# batch_size, dimension and position# output: (batch_size, dim)def positional_encoding(batch_size, dim, pos): assert batch_size == pos.shape[0] positions_enc = np.array([ [pos[j] / np.power(10000, (i-i%2)/dim) for i in range(dim)] for j in range(batch_size) ], dtype=np.float32) positions_enc[:, 0::2] = np.sin(positions_enc[:, 0::2]) positions_enc[:, 1::2] = np.cos(positions_enc[:, 1::2]) return torch.from_numpy(positions_enc).float()
def get_padding_mask(batch_size, seq_len, cap_lens): cap_lens = cap_lens.data.tolist() mask_2d = torch.ones((batch_size, seq_len, seq_len), dtype=torch.float32) for i, cap_len in enumerate(cap_lens): mask_2d[i, :, :cap_len] = 0 return mask_2d.bool(), 1 - mask_2d[:, :, 0].clone()
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=300): super(PositionalEncoding, self).__init__()
pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) # pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe)
def forward(self, pos): return self.pe[pos]
class MovementConvEncoder(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(MovementConvEncoder, self).__init__() self.main = nn.Sequential( nn.Conv1d(input_size, hidden_size, 4, 2, 1), nn.Dropout(0.2, inplace=True), nn.LeakyReLU(0.2, inplace=True), nn.Conv1d(hidden_size, output_size, 4, 2, 1), nn.Dropout(0.2, inplace=True), nn.LeakyReLU(0.2, inplace=True), ) self.out_net = nn.Linear(output_size, output_size) self.main.apply(init_weight) self.out_net.apply(init_weight)
def forward(self, inputs): inputs = inputs.permute(0, 2, 1) outputs = self.main(inputs).permute(0, 2, 1) # print(outputs.shape) return self.out_net(outputs)
class MovementConvDecoder(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(MovementConvDecoder, self).__init__() self.main = nn.Sequential( nn.ConvTranspose1d(input_size, hidden_size, 4, 2, 1), # nn.Dropout(0.2, inplace=True), nn.LeakyReLU(0.2, inplace=True), nn.ConvTranspose1d(hidden_size, output_size, 4, 2, 1), # nn.Dropout(0.2, inplace=True), nn.LeakyReLU(0.2, inplace=True), ) self.out_net = nn.Linear(output_size, output_size)
self.main.apply(init_weight) self.out_net.apply(init_weight)
def forward(self, inputs): inputs = inputs.permute(0, 2, 1) outputs = self.main(inputs).permute(0, 2, 1) return self.out_net(outputs)
class TextVAEDecoder(nn.Module): def __init__(self, text_size, input_size, output_size, hidden_size, n_layers): super(TextVAEDecoder, self).__init__() self.input_size = input_size self.output_size = output_size self.hidden_size = hidden_size self.n_layers = n_layers self.emb = nn.Sequential( nn.Linear(input_size, hidden_size), nn.LayerNorm(hidden_size), nn.LeakyReLU(0.2, inplace=True))
self.z2init = nn.Linear(text_size, hidden_size * n_layers) self.gru = nn.ModuleList([nn.GRUCell(hidden_size, hidden_size) for i in range(self.n_layers)]) self.positional_encoder = PositionalEncoding(hidden_size)
self.output = nn.Sequential( nn.Linear(hidden_size, hidden_size), nn.LayerNorm(hidden_size), nn.LeakyReLU(0.2, inplace=True), nn.Linear(hidden_size, output_size) )
# # self.output = nn.Sequential( # nn.Linear(hidden_size, hidden_size), # nn.LayerNorm(hidden_size), # nn.LeakyReLU(0.2, inplace=True), # nn.Linear(hidden_size, output_size-4) # )
# self.contact_net = nn.Sequential( # nn.Linear(output_size-4, 64), # nn.LayerNorm(64), # nn.LeakyReLU(0.2, inplace=True), # nn.Linear(64, 4) # )
self.output.apply(init_weight) self.emb.apply(init_weight) self.z2init.apply(init_weight) # self.contact_net.apply(init_weight)
def get_init_hidden(self, latent): hidden = self.z2init(latent) hidden = torch.split(hidden, self.hidden_size, dim=-1) return list(hidden)
def forward(self, inputs, last_pred, hidden, p): h_in = self.emb(inputs) pos_enc = self.positional_encoder(p).to(inputs.device).detach() h_in = h_in + pos_enc for i in range(self.n_layers): # print(h_in.shape) hidden[i] = self.gru[i](h_in, hidden[i]) h_in = hidden[i] pose_pred = self.output(h_in) # pose_pred = self.output(h_in) + last_pred.detach() # contact = self.contact_net(pose_pred) # return torch.cat([pose_pred, contact], dim=-1), hidden return pose_pred, hidden
class TextDecoder(nn.Module): def __init__(self, text_size, input_size, output_size, hidden_size, n_layers): super(TextDecoder, self).__init__() self.input_size = input_size self.output_size = output_size self.hidden_size = hidden_size self.n_layers = n_layers self.emb = nn.Sequential( nn.Linear(input_size, hidden_size), nn.LayerNorm(hidden_size), nn.LeakyReLU(0.2, inplace=True))
self.gru = nn.ModuleList([nn.GRUCell(hidden_size, hidden_size) for i in range(self.n_layers)]) self.z2init = nn.Linear(text_size, hidden_size * n_layers) self.positional_encoder = PositionalEncoding(hidden_size)
self.mu_net = nn.Linear(hidden_size, output_size) self.logvar_net = nn.Linear(hidden_size, output_size)
self.emb.apply(init_weight) self.z2init.apply(init_weight) self.mu_net.apply(init_weight) self.logvar_net.apply(init_weight)
def get_init_hidden(self, latent):
hidden = self.z2init(latent) hidden = torch.split(hidden, self.hidden_size, dim=-1)
return list(hidden)
def forward(self, inputs, hidden, p): # print(inputs.shape) x_in = self.emb(inputs) pos_enc = self.positional_encoder(p).to(inputs.device).detach() x_in = x_in + pos_enc
for i in range(self.n_layers): hidden[i] = self.gru[i](x_in, hidden[i]) h_in = hidden[i] mu = self.mu_net(h_in) logvar = self.logvar_net(h_in) z = reparameterize(mu, logvar) return z, mu, logvar, hidden
class AttLayer(nn.Module): def __init__(self, query_dim, key_dim, value_dim): super(AttLayer, self).__init__() self.W_q = nn.Linear(query_dim, value_dim) self.W_k = nn.Linear(key_dim, value_dim, bias=False) self.W_v = nn.Linear(key_dim, value_dim)
self.softmax = nn.Softmax(dim=1) self.dim = value_dim
self.W_q.apply(init_weight) self.W_k.apply(init_weight) self.W_v.apply(init_weight)
def forward(self, query, key_mat): ''' query (batch, query_dim) key (batch, seq_len, key_dim) ''' # print(query.shape) query_vec = self.W_q(query).unsqueeze(-1) # (batch, value_dim, 1) val_set = self.W_v(key_mat) # (batch, seq_len, value_dim) key_set = self.W_k(key_mat) # (batch, seq_len, value_dim)
weights = torch.matmul(key_set, query_vec) / np.sqrt(self.dim)
co_weights = self.softmax(weights) # (batch, seq_len, 1) values = val_set * co_weights # (batch, seq_len, value_dim) pred = values.sum(dim=1) # (batch, value_dim) return pred, co_weights
def short_cut(self, querys, keys): return self.W_q(querys), self.W_k(keys)
class TextEncoderBiGRU(nn.Module): def __init__(self, word_size, pos_size, hidden_size, device): super(TextEncoderBiGRU, self).__init__() self.device = device
self.pos_emb = nn.Linear(pos_size, word_size) self.input_emb = nn.Linear(word_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True) # self.linear2 = nn.Linear(hidden_size, output_size)
self.input_emb.apply(init_weight) self.pos_emb.apply(init_weight) # self.linear2.apply(init_weight) # self.batch_size = batch_size self.hidden_size = hidden_size self.hidden = nn.Parameter(torch.randn((2, 1, self.hidden_size), requires_grad=True))
# input(batch_size, seq_len, dim) def forward(self, word_embs, pos_onehot, cap_lens): num_samples = word_embs.shape[0]
pos_embs = self.pos_emb(pos_onehot) inputs = word_embs + pos_embs input_embs = self.input_emb(inputs) hidden = self.hidden.repeat(1, num_samples, 1)
cap_lens = cap_lens.data.tolist() emb = pack_padded_sequence(input_embs, cap_lens, batch_first=True)
gru_seq, gru_last = self.gru(emb, hidden)
gru_last = torch.cat([gru_last[0], gru_last[1]], dim=-1) gru_seq = pad_packed_sequence(gru_seq, batch_first=True)[0] forward_seq = gru_seq[..., :self.hidden_size] backward_seq = gru_seq[..., self.hidden_size:].clone()
# Concate the forward and backward word embeddings for i, length in enumerate(cap_lens): backward_seq[i:i+1, :length] = torch.flip(backward_seq[i:i+1, :length].clone(), dims=[1]) gru_seq = torch.cat([forward_seq, backward_seq], dim=-1)
return gru_seq, gru_last
class TextEncoderBiGRUCo(nn.Module): def __init__(self, word_size, pos_size, hidden_size, output_size, device): super(TextEncoderBiGRUCo, self).__init__() self.device = device
self.pos_emb = nn.Linear(pos_size, word_size) self.input_emb = nn.Linear(word_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True) self.output_net = nn.Sequential( nn.Linear(hidden_size * 2, hidden_size), nn.LayerNorm(hidden_size), nn.LeakyReLU(0.2, inplace=True), nn.Linear(hidden_size, output_size) )
self.input_emb.apply(init_weight) self.pos_emb.apply(init_weight) self.output_net.apply(init_weight) # self.linear2.apply(init_weight) # self.batch_size = batch_size self.hidden_size = hidden_size self.hidden = nn.Parameter(torch.randn((2, 1, self.hidden_size), requires_grad=True))
# input(batch_size, seq_len, dim) def forward(self, word_embs, pos_onehot, cap_lens): num_samples = word_embs.shape[0]
pos_embs = self.pos_emb(pos_onehot) inputs = word_embs + pos_embs input_embs = self.input_emb(inputs) hidden = self.hidden.repeat(1, num_samples, 1)
cap_lens = cap_lens.data.tolist() emb = pack_padded_sequence(input_embs, cap_lens, batch_first=True)
gru_seq, gru_last = self.gru(emb, hidden)
gru_last = torch.cat([gru_last[0], gru_last[1]], dim=-1)
return self.output_net(gru_last)
class MotionEncoderBiGRUCo(nn.Module): def __init__(self, input_size, hidden_size, output_size, device): super(MotionEncoderBiGRUCo, self).__init__() self.device = device
self.input_emb = nn.Linear(input_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True) self.output_net = nn.Sequential( nn.Linear(hidden_size*2, hidden_size), nn.LayerNorm(hidden_size), nn.LeakyReLU(0.2, inplace=True), nn.Linear(hidden_size, output_size) )
self.input_emb.apply(init_weight) self.output_net.apply(init_weight) self.hidden_size = hidden_size self.hidden = nn.Parameter(torch.randn((2, 1, self.hidden_size), requires_grad=True))
# input(batch_size, seq_len, dim) def forward(self, inputs, m_lens): num_samples = inputs.shape[0]
input_embs = self.input_emb(inputs) hidden = self.hidden.repeat(1, num_samples, 1)
cap_lens = m_lens.data.tolist() emb = pack_padded_sequence(input_embs, cap_lens, batch_first=True)
gru_seq, gru_last = self.gru(emb, hidden)
gru_last = torch.cat([gru_last[0], gru_last[1]], dim=-1)
return self.output_net(gru_last)
class MotionLenEstimatorBiGRU(nn.Module): def __init__(self, word_size, pos_size, hidden_size, output_size): super(MotionLenEstimatorBiGRU, self).__init__()
self.pos_emb = nn.Linear(pos_size, word_size) self.input_emb = nn.Linear(word_size, hidden_size) self.gru = nn.GRU(hidden_size, hidden_size, batch_first=True, bidirectional=True) nd = 512 self.output = nn.Sequential( nn.Linear(hidden_size*2, nd), nn.LayerNorm(nd), nn.LeakyReLU(0.2, inplace=True),
nn.Linear(nd, nd // 2), nn.LayerNorm(nd // 2), nn.LeakyReLU(0.2, inplace=True),
nn.Linear(nd // 2, nd // 4), nn.LayerNorm(nd // 4), nn.LeakyReLU(0.2, inplace=True),
nn.Linear(nd // 4, output_size) ) # self.linear2 = nn.Linear(hidden_size, output_size)
self.input_emb.apply(init_weight) self.pos_emb.apply(init_weight) self.output.apply(init_weight) # self.linear2.apply(init_weight) # self.batch_size = batch_size self.hidden_size = hidden_size self.hidden = nn.Parameter(torch.randn((2, 1, self.hidden_size), requires_grad=True))
# input(batch_size, seq_len, dim) def forward(self, word_embs, pos_onehot, cap_lens): num_samples = word_embs.shape[0]
pos_embs = self.pos_emb(pos_onehot) inputs = word_embs + pos_embs input_embs = self.input_emb(inputs) hidden = self.hidden.repeat(1, num_samples, 1)
cap_lens = cap_lens.data.tolist() emb = pack_padded_sequence(input_embs, cap_lens, batch_first=True)
gru_seq, gru_last = self.gru(emb, hidden)
gru_last = torch.cat([gru_last[0], gru_last[1]], dim=-1)
return self.output(gru_last)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231import argparseimport loggingimport logging as logimport osimport timefrom collections import defaultdictfrom os.path import join as pjoinfrom typing import Dict, Optional, Tuple
import imageioimport numpy as npimport pyrenderimport smplximport torchimport trimeshfrom numpy.typing import ArrayLikefrom torch import Tensorfrom tqdm import tqdm
from .motionx_explorer import (NUM_FACIAL_EXPRESSION_DIMS, calc_mean_stddev_pose, get_info_from_file, label_code, motion_arr_to_dict, names_to_arrays, to_smplx_dict)
log.basicConfig( level=log.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",)
def save_img(img, save_path): imageio.imwrite(save_path, img) # based on https://github.com/vchoutas/smplx/blob/main/examples/demo.py# used to render one pose (not sequence of poses) e.g. to see the mean posedef render_mesh(model, output, should_save=False, save_path=None): should_display = not should_save vertices = output.vertices.detach().cpu().numpy().squeeze() # joint points not visualized for now # joints = output.joints.detach().cpu().numpy().squeeze() scene = pyrender.Scene() if should_display: viewer = pyrender.Viewer(scene, run_in_thread=True)
mesh_node = None joints_node = None # Rotation matrix (90 degrees around the X-axis) rot = trimesh.transformations.rotation_matrix(np.radians(90), [1, 0, 0]) if should_save: os.makedirs(os.path.dirname(save_path), exist_ok=True) try: # print("Vertices shape =", vertices.shape) # print("Joints shape =", joints.shape)
# from their demo script plotting_module = "pyrender" if plotting_module == "pyrender": vertex_colors = np.ones([vertices.shape[0], 4]) * [0.3, 0.3, 0.3, 0.8] tri_mesh = trimesh.Trimesh(vertices, model.faces, vertex_colors=vertex_colors)
# Apply rotation tri_mesh.apply_transform(rot) ##### RENDER LOCK ##### if should_display: viewer.render_lock.acquire() if mesh_node: scene.remove_node(mesh_node) mesh = pyrender.Mesh.from_trimesh(tri_mesh) mesh_node = scene.add(mesh)
camera = pyrender.PerspectiveCamera(yfov=np.pi / 3.0, aspectRatio=1.0) min_bound, max_bound = mesh.bounds
# Calculate the center of the bounding box center = (min_bound + max_bound) / 2
# Calculate the extents (the dimensions of the bounding box) extents = max_bound - min_bound
# Estimate a suitable distance distance = max(extents) * 2 # Adjust the multiplier as needed
# Create a camera pose matrix cam_pose = np.array( [ [1.0, 0, 0, center[0]], [0, 1.0, 0, center[1]-1.0], [0, 0, 1.0, center[2] + distance + 0.5], [0, 0, 0, 1], ] ) # Rotate around X-axis angle = np.radians(90) cos_angle = np.cos(angle) sin_angle = np.sin(angle) rot_x = np.array([ [1, 0, 0, 0], [0, cos_angle, -sin_angle, 0], [0, sin_angle, cos_angle, 0], [0, 0, 0, 1] ]) cam_pose = np.matmul(cam_pose, rot_x) # this is great pose, head on, but a bit far from face # cam_pose[:3, 3] += np.array([0, 0, -3.5]) cam_pose[:3, 3] += np.array([-.01, 0.65, -3.3])
scene.add(camera, pose=cam_pose)
# Add light for better visualization light = pyrender.DirectionalLight(color=np.ones(3), intensity=2.0) scene.add(light, pose=cam_pose)
if should_save: r = pyrender.OffscreenRenderer(viewport_width=640, viewport_height=480) col_img, _ = r.render(scene) save_img(col_img, save_path) r.delete() # Free up the resources ###### RENDER LOCK RELEASE ##### if should_display: viewer.render_lock.release() except KeyboardInterrupt: if should_display: viewer.close_external()
# motion_arr is 212 dims (no shapes: aka no betas and no face shapes)def mesh_and_save(args, motion_arr, seq_name, model_name, emotion): motion_dict = motion_arr_to_dict(motion_arr, shapes_dropped=True) smplx_params = to_smplx_dict(motion_dict) model_folder = "./models/smplx" batch_size = 1 model = smplx.SMPLX( model_folder, use_pca=False, # our joints are not in pca space num_expression_coeffs=NUM_FACIAL_EXPRESSION_DIMS, batch_size=batch_size, ) output = model.forward(**smplx_params, return_verts=True) log.info(f"output size {output.vertices.shape}") log.info(f"output size {output.joints.shape}") log.info("rendering mesh") base_file = args.file.split('.')[0] # add {emotion}_{base_file} as a subfolder if it doesn't exist subfolder = f"single_pose_imgs/{model_name}/{emotion}_{base_file}" if not os.path.exists(subfolder): os.makedirs(subfolder) save_path = f"{subfolder}/{seq_name}_pose.png" render_mesh(model, output, should_save=True, save_path=save_path) log.warning( "if you don't see the mesh animation, make sure you are running on graphics compatible DTU machine (vgl xterm)." ) return subfolder if __name__ == "__main__": parser = argparse.ArgumentParser()
parser.add_argument( "-e", "--emotion", type=str, required=True, help="emotion to calculate mean, std for", ) parser.add_argument( "-f", "--file", type=str, required=True, help="file to filter for emotion", ) parser.add_argument( "-m", "--model_path", type=str, required=False, default="", help="Path to model directory e.g. ./checkpoints/grab/grab_baseline_dp_2gpu_8layers_1000", ) args = parser.parse_args() data_root = './data/GRAB' motion_label_dir = pjoin(data_root, 'texts') emotions_label_dir = pjoin(data_root, 'face_texts') args = parser.parse_args() seq_list_file = pjoin(data_root, args.file) logging.info("aggregating info about sequences...") info_dict = get_info_from_file(seq_list_file, emotions_label_dir, motion_label_dir) # get all files with args.emotion_code logging.info("calculating mean pose statistics...") emotions = info_dict["unique_emotions"] # emotions = [args.emotion] for emotion in emotions: logging.info(f"render mean mesh for {emotion} in {args.file}...") emo_code = label_code(emotion) names_with_emo = info_dict["emotion_to_names"][emo_code] arrays = names_to_arrays(data_root, names_with_emo) mean, std = calc_mean_stddev_pose(arrays) # add 1 dimension to mean and std mean = mean.reshape(1, -1) std = std.reshape(1, -1)
mean_dict = motion_arr_to_dict(mean, shapes_dropped=True) std_dict = motion_arr_to_dict(std, shapes_dropped=True) logging.info(f"{emotion} mean: {mean_dict['face_expr']}") logging.info(f"{emotion} std: {std_dict['face_expr']}")
logging.info(f"rendering mean mesh for {emotion} in {args.file}...") subfolder = mesh_and_save(args, mean, "mean", args.model_path, emotion)
model_name = args.model_path.split('/')[-1] if args.model_path else "ground_truth" # write the sequence names in a metadata folder at subfolder metadata_folder = f"{subfolder}/metadata" if not os.path.exists(metadata_folder): os.makedirs(metadata_folder) metadata_path = f"{metadata_folder}/metadata.txt" with open(metadata_path, 'w') as f: f.write(f"model: {model_name}\n") f.write(f"emotion: {emotion}\n") f.write(f"file: {args.file}\n") f.write(f"mean: {mean_dict}\n") f.write(f"std: {std_dict}\n") for name in names_with_emo: f.write(f"{name}\n") # now plot mesh for each of the sequences for i, arr in enumerate(arrays): one_pose = arr[0] one_pose = one_pose.reshape(1, -1) name = names_with_emo[i] # replace / with _ name = name.replace("/", "_") subfolder = mesh_and_save(args, one_pose, name, args.model_path, emotion)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554import argparseimport logging as logimport osimport timefrom collections import defaultdictfrom os.path import join as pjoinfrom typing import Dict, Optional, Tuple
import numpy as npimport smplximport torchfrom numpy.typing import ArrayLikefrom torch import Tensor
from .rendering import render_meshes
log.basicConfig( level=log.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",)
MOCAP_DATASETS = {"egobody", "grab", "humanml", "grab_motion"}DATA_DIR = "data"MODELS_DIR = "models"MOCAP_FACE_DIR = f"{DATA_DIR}/face_motion_data/smplx_322" # contains face motion data onlyMOTION_DIR = f"{DATA_DIR}/motion_data/smplx_322"ACTION_LABEL_DIR = f"{DATA_DIR}/semantic_labels"EMOTION_LABEL_DIR = f"{DATA_DIR}/face_texts"
"""Page 12 of https://arxiv.org/pdf/2307.00818.pdf shows:
smpl-x = {θb, θh, θf , ψ, r} = 3D body pose, 3D hand pose, jaw pose, facial expression, global root orientation, global translationdims: (22x3, 30x3, 1x3, 1x50, 1x3) = (66, 90, 3, 50, 3, 3)
NOTE: I think they are wrong about n_body_joints though, data indicates it's actually 21x3 = 63, not 22x3 = 66"""
MY_REPO = os.path.abspath("")log.info(f"MY_REPO: {MY_REPO}")NUM_BODY_JOINTS = 23 - 2 # SMPL has hand joints but we're replacing them with more detailed ones by SMLP-X, paper: 22x3 total body dims * not sure why paper says 22NUM_JAW_JOINTS = 1 # 1x3 total jaw dims# Motion-X paper says thereNUM_HAND_JOINTS = 15 # x2 for each hand -> 30x3 total hand dimsNUM_JOINTS = NUM_BODY_JOINTS + NUM_HAND_JOINTS * 2 + NUM_JAW_JOINTS # 21 + 30 + 1 = 52NUM_FACIAL_EXPRESSION_DIMS = 50 # as per Motion-X paper, but why is default 10 in smplx code then?FACE_SHAPE_DIMS = 100BODY_SHAPE_DIMS = 10 # betasROOT_DIMS = 3TRANS_DIMS = 3 # same as root, no?
pose_type_to_dims = { "pose_body": NUM_BODY_JOINTS * 3, "pose_hand": NUM_HAND_JOINTS * 2 * 3, # both hands "pose_jaw": NUM_JAW_JOINTS * 3, "face_expr": NUM_FACIAL_EXPRESSION_DIMS * 1, # double check "face_shape": FACE_SHAPE_DIMS * 1, # double check "root_orient": ROOT_DIMS * 1, "betas": BODY_SHAPE_DIMS * 1, "trans": TRANS_DIMS * 1,}
def names_to_arrays(root_dir, names, drop_shapes=True): all_arrays = [] for name in names: # Load each NumPy array and add it to the list array = np.load(pjoin(f"{root_dir}/joints", f"{name}.npy")) # drop shapes -> 212 dims if drop_shapes: array = drop_shapes_from_motion_arr(array) all_arrays.append(array) return all_arrays
def get_seq_names(file_path): with open(file_path, "r") as f: names = f.readlines() names = [name.strip() for name in names] return names
def get_data_path(dataset_dir: str, seq: str, file: str) -> str: # MY_REPO/face_motion_data/smplx_322/GRAB/s1/airplane_fly_1.npy top_dir = MOCAP_FACE_DIR if dataset_dir.lower() in MOCAP_DATASETS else MOTION_DIR path = f"{os.path.join(MY_REPO, top_dir, dataset_dir, seq, file)}.npy" return path
def get_label_paths(dataset_dir: str, seq: str, file: str) -> Dict[str, str]: # MY_REPO/MotionDiffuse/face_texts/GRAB/s1/airplane_fly_1.txt action_path = f"{os.path.join(MY_REPO, ACTION_LABEL_DIR, dataset_dir, seq, file)}.txt" emotion_path = f"{os.path.join(MY_REPO, EMOTION_LABEL_DIR, dataset_dir, seq, file)}.txt" paths = {"action": action_path, "emotion": emotion_path} return paths
def load_data_as_dict(dataset_dir: str, seq: str, file: str) -> Dict[str, Tensor]: path = get_data_path(dataset_dir, seq, file) motion = np.load(path) motion = torch.tensor(motion).float() return { "root_orient": motion[:, :3], # controls the global root orientation "pose_body": motion[:, 3 : 3 + 63], # controls the body "pose_hand": motion[:, 66 : 66 + 90], # controls the finger articulation "pose_jaw": motion[:, 66 + 90 : 66 + 93], # controls the jaw pose "face_expr": motion[:, 159 : 159 + 50], # controls the face expression "face_shape": motion[:, 209 : 209 + 100], # controls the face shape "trans": motion[:, 309 : 309 + 3], # controls the global body position "betas": motion[:, 312:], # controls the body shape. Body shape is static }
def motion_arr_to_dict(motion_arr: ArrayLike, shapes_dropped=False) -> Dict[str, Tensor]: # TODO (elmc): why did I need to convert to tensor again??? motion_arr = torch.tensor(motion_arr).float() motion_dict = { "root_orient": motion_arr[:, :3], # controls the global root orientation "pose_body": motion_arr[:, 3 : 3 + 63], # controls the body "pose_hand": motion_arr[:, 66 : 66 + 90], # controls the finger articulation "pose_jaw": motion_arr[:, 66 + 90 : 66 + 93], # controls the jaw pose "face_expr": motion_arr[:, 159 : 159 + 50], # controls the face expression } if not shapes_dropped: motion_dict["face_shape"] = motion_arr[:, 209 : 209 + 100] # controls the face shape motion_dict["trans"] = motion_arr[:, 309 : 309 + 3] # controls the global body position motion_dict["betas"] = motion_arr[:, 312:] # controls the body shape. Body shape is static else: motion_dict["trans"] = motion_arr[:, 209:] # controls the global body position return motion_dict
def drop_shapes_from_motion_arr(motion_arr: ArrayLike) -> ArrayLike: if isinstance(motion_arr, torch.Tensor): new_motion_arr = motion_arr.numpy() # Slice the array to exclude 'face_shape' and 'betas' new_motion_arr = np.concatenate((motion_arr[:, :209], motion_arr[:, 309:312]), axis=1) return new_motion_arr
def load_label_from_file(file_path: str) -> str: with open(file_path, "r") as file: # Read the contents of the file into a string label = file.read() return label
def load_label(dataset_dir: str, seq: str, file_path: str) -> Dict[str, str]: paths = get_label_paths(dataset_dir, seq, file_path) action_path, emotion_path = paths["action"], paths["emotion"] log.info(f"loading labels from {action_path} and {emotion_path}") paths = {} with open(action_path, "r") as file: # Read the contents of the file into a string action_label = file.read() with open(emotion_path, "r") as file: # Read the contents of the file into a string emotion_label = file.read() return {"action": action_label, "emotion": emotion_label}
def label_code(full_label): # take first 3 letters of label # surprise -> sur # airplane -> air return full_label[:3]
def get_seq_type(motion_label_dir, file_name): # e.g. s5/airplane_fly_1 -> airplane fly (motion label) seq_type_path = pjoin(motion_label_dir, f"{file_name}.txt") with open(seq_type_path, 'r') as f: seq_type = f.readline().strip() return seq_type
def calc_mean_stddev_pose(arrays): # all_arrays = [] # for file_path in file_list: # # Load each NumPy array and add it to the list # array = np.load(file_path) # all_arrays.append(array) # Concatenate all arrays along the first axis (stacking them on top of each other) concatenated_arrays = np.concatenate(arrays, axis=0) # Calculate the mean and standard deviation across all arrays mean = np.mean(concatenated_arrays, axis=0) stddev = np.std(concatenated_arrays, axis=0) return mean, stddev
def get_info_from_file(file_path, emotions_label_dir, motion_label_dir): # train_names = get_seq_names(pjoin(data_dir, "train.txt")) names = get_seq_names(file_path) seq_type_to_emotions = defaultdict(set) emotions_count = defaultdict(int) seq_type_count = defaultdict(int) obj_count = defaultdict(int) code_to_label = {} emotion_to_names = defaultdict(list) n_seq = len(names) for name in names: seq_type = get_seq_type(motion_label_dir, name) emotion = load_label_from_file(pjoin(emotions_label_dir, f"{name}.txt")) object_ = seq_type.split(" ")[0] seq_type_to_emotions[seq_type].add(emotion) emo_code = label_code(emotion) emotions_count[emo_code] += 1 seq_type_count[seq_type] += 1 obj_code = label_code(object_) obj_count[label_code(object_)] += 1 code_to_label[emo_code] = emotion code_to_label[obj_code] = object_ emotion_to_names[emo_code].append(name) unique_emotions = set([code_to_label[code] for code in emotions_count]) info_dict = { "seq_type_to_emotions": seq_type_to_emotions, "emotions_count": emotions_count, "seq_type_count": seq_type_count, "obj_count": obj_count, "code_to_label": code_to_label, "emotion_to_names": emotion_to_names, "unique_emotions": unique_emotions, "n_seq": n_seq, "code_to_label": code_to_label, } return info_dict
def to_smplx_dict(motion_dict: Dict[str, Tensor], timestep_range: Optional[Tuple[int, int]] = None) -> Dict[str, Tensor]: if timestep_range is None: # get all timesteps timestep_range = (0, len(motion_dict["pose_body"])) smplx_params = { "global_orient": motion_dict["root_orient"][ timestep_range[0] : timestep_range[1] ], # controls the global root orientation "body_pose": motion_dict["pose_body"][timestep_range[0] : timestep_range[1]], # controls the body "left_hand_pose": motion_dict["pose_hand"][timestep_range[0] : timestep_range[1]][ :, : NUM_HAND_JOINTS * 3 ], # controls the finger articulation "right_hand_pose": motion_dict["pose_hand"][timestep_range[0] : timestep_range[1]][:, NUM_HAND_JOINTS * 3 :], "expression": motion_dict["face_expr"][timestep_range[0] : timestep_range[1]], # controls the face expression "jaw_pose": motion_dict["pose_jaw"][timestep_range[0] : timestep_range[1]], # controls the jaw pose # 'face_shape': motion_dict['face_shape'][timestep], # controls the face shape, drop since we don't care to train on this "transl": motion_dict["trans"][timestep_range[0] : timestep_range[1]], # controls the global body position # "betas": motion["betas"][ # timestep_range[0] : timestep_range[1] # ], # controls the body shape. Body shape is static, drop since we don't care to train on this } return smplx_params
def smplx_dict_to_array(smplx_dict): # convert smplx dict to array # list keys to ensure known order when iterating over dict keys = ["global_orient", "body_pose", "left_hand_pose", "right_hand_pose", "expression", "jaw_pose", "transl"] smplx_array = [] for key in keys: smplx_array.append(smplx_dict[key]) smplx_array = torch.cat(smplx_array, dim=1) return smplx_array
def save_gif(gif_path, gif_frames, duration=0.01): if gif_frames: print(f"Saving GIF with {len(gif_frames)} frames to {gif_path}") imageio.mimsave(uri=gif_path, ims=gif_frames, duration=duration) else: print("No frames to save.")
# based on https://github.com/vchoutas/smplx/blob/main/examples/demo.pydef render_meshes(output, should_save_gif=False, gif_path=None): should_display = not should_save_gif vertices_list = output.vertices.detach().cpu().numpy().squeeze() joints_list = output.joints.detach().cpu().numpy().squeeze() # TODO (elmc): why do I wrap these in a list again? if len(vertices_list.shape) == 2: vertices_list = [vertices_list] joints_list = [joints_list] scene = pyrender.Scene() if should_display: viewer = pyrender.Viewer(scene, run_in_thread=True)
mesh_node = None joints_node = None # Rotation matrix (90 degrees around the X-axis) rot = trimesh.transformations.rotation_matrix(np.radians(90), [1, 0, 0]) gif_frames = [] if should_save_gif: os.makedirs(os.path.dirname(gif_path), exist_ok=True) try: for i in tqdm(range(len(vertices_list))): vertices = vertices_list[i] joints = joints_list[i] # print("Vertices shape =", vertices.shape) # print("Joints shape =", joints.shape)
# from their demo script plotting_module = "pyrender" plot_joints = False if plotting_module == "pyrender": vertex_colors = np.ones([vertices.shape[0], 4]) * [0.3, 0.3, 0.3, 0.8] tri_mesh = trimesh.Trimesh(vertices, model.faces, vertex_colors=vertex_colors)
# Apply rotation tri_mesh.apply_transform(rot) ##### RENDER LOCK ##### if should_display: viewer.render_lock.acquire() if mesh_node: scene.remove_node(mesh_node) mesh = pyrender.Mesh.from_trimesh(tri_mesh) mesh_node = scene.add(mesh)
camera = pyrender.PerspectiveCamera(yfov=np.pi / 3.0, aspectRatio=1.0) min_bound, max_bound = mesh.bounds
# Calculate the center of the bounding box center = (min_bound + max_bound) / 2
# Calculate the extents (the dimensions of the bounding box) extents = max_bound - min_bound
# Estimate a suitable distance distance = max(extents) * 2 # Adjust the multiplier as needed
# Create a camera pose matrix cam_pose = np.array( [ [1.0, 0, 0, center[0]], [0, 1.0, 0, center[1]-1.0], [0, 0, 1.0, center[2] + distance + 0.5], [0, 0, 0, 1], ] ) # Rotate around X-axis # Rotate around X-axis angle = np.radians(90) cos_angle = np.cos(angle) sin_angle = np.sin(angle) rot_x = np.array([ [1, 0, 0, 0], [0, cos_angle, -sin_angle, 0], [0, sin_angle, cos_angle, 0], [0, 0, 0, 1] ]) cam_pose = np.matmul(cam_pose, rot_x) cam_pose[:3, 3] += np.array([0, -2.5, -3.5])
scene.add(camera, pose=cam_pose)
# Add light for better visualization light = pyrender.DirectionalLight(color=np.ones(3), intensity=2.0) scene.add(light, pose=cam_pose)
# TODO: rotation doesn't work here, so appears sideways if plot_joints: sm = trimesh.creation.uv_sphere(radius=0.005) sm.visual.vertex_colors = [0.9, 0.1, 0.1, 1.0] tfs = np.tile(np.eye(4), (len(joints), 1, 1)) # tfs[:, :3, 3] = joints for i, joint in enumerate(joints): tfs[i, :3, :3] = rot[:3, :3] tfs[i, :3, 3] = joint joints_pcl = pyrender.Mesh.from_trimesh(sm, poses=tfs) if joints_node: scene.remove_node(joints_node) joints_node = scene.add(joints_pcl) if should_save_gif: r = pyrender.OffscreenRenderer(viewport_width=640, viewport_height=480) color, _ = r.render(scene) gif_frames.append(color) r.delete() # Free up the resources ###### RENDER LOCK RELEASE ##### if should_display: viewer.render_lock.release() except KeyboardInterrupt: if should_display: viewer.close_external() save_gif(gif_path, gif_frames) finally: save_gif(gif_path, gif_frames)
def get_numpy_file_path(prompt, epoch, n_frames): # e.g. "airplane_fly_1_1000_60f.npy" prompt_no_spaces = prompt.replace(' ', '_') return f"{prompt_no_spaces}_{epoch}_{n_frames}f"
if __name__ == "__main__": parser = argparse.ArgumentParser()
parser.add_argument( "-mn", "--min_t", type=int, required=False, default=0, help="Minimum number of timesteps to render", ) parser.add_argument( "-mx", "--max_t", type=int, required=False, help="Maximum number of timesteps to render", ) parser.add_argument( "-dm", "--display_mesh", action='store_true', required=False, default=False, help="Display mesh if this flag is present" ) # for now just specifies file name (with spaces) made by inference parser.add_argument( "-p", "--prompt", type=str, required=False, default="", help="Prompt for inference display", ) parser.add_argument( "-sf", "--seq_file", type=str, required=False, default="", help="file for non-inference display", ) # add model_path arg parser.add_argument( "-m", "--model_path", type=str, required=False, default="", help="Path to model directory e.g. ./checkpoints/grab/grab_baseline_dp_2gpu_8layers_1000", ) parser.add_argument( "-sg", "--save_gif", action='store_true', required=False, default=False, help="Save gif if this flag is present" ) # add which_epoch parser.add_argument( "-we", "--which_epoch", type=str, required=True, help="which epoch to load", ) args = parser.parse_args()
prompt = args.prompt is_inference = len(prompt) > 0 if args.seq_file != "" and args.prompt != "": log.error("cannot provide both prompt and seq_file; if trying to verify model inference, use --prompt, otherwise specify numpy --seq_file name to display") exit(1) elif args.seq_file == "" and args.prompt == "": log.error("must provide either prompt or seq_file; if trying to verify model inference, use --prompt, otherwise specify numpy --seq_file name to display") exit(1) if not is_inference: name = args.seq_file data_root = './data/GRAB' motion_dir = pjoin(data_root, 'joints') else: log.info(f"converting prompt into file name") name = get_numpy_file_path(prompt, args.which_epoch, args.max_t - args.min_t) model_type = args.model_path motion_dir = pjoin(model_type, 'outputs') motion_path = pjoin(motion_dir, name + '.npy') log.info(f"loading motion from {motion_path}") motion_arr = np.load(motion_path) t = 999 mean_path = '/work3/s222376/MotionDiffuse2/text2motion/checkpoints/grab/md_fulem_2g_excl_196_seed42/meta/mean.npy' std_path = '/work3/s222376/MotionDiffuse2/text2motion/checkpoints/grab/md_fulem_2g_excl_196_seed42/meta/std.npy' mean = np.load(mean_path) std = np.load(std_path) # do range skipping by 100 list_ = [t for t in range(10, 91, 10)] list_ += [t for t in range(100, 200, 30)] for t in list_: name = f"sample_tensor([{t}])" # breakpoint() motion_arr = np.load(f"/work3/s222376/MotionDiffuse2/text2motion/generation_samples/{name}.npy") motion_arr = np.squeeze(motion_arr)
motion_arr = motion_arr * std + mean # drop shapes for ground-truth to have same dimensionality as inference # for fair comparisons and reducing bugs if not is_inference: # directly get smplx dimensionality by dropping body and face shape data print("warning, dropping body and face shape data") motion_arr = drop_shapes_from_motion_arr(motion_arr) assert motion_arr.shape[1] == 212, f"expected 212 dims, got {motion_arr.shape[1]}"
# our MotionDiffuse predicts motion data that doesn't include face and body shape motion_dict = motion_arr_to_dict(motion_arr, shapes_dropped=True) n_points = len(motion_dict["pose_body"])
min_t = args.min_t max_t = args.max_t or n_points if max_t > n_points: max_t = n_points
timestep_range = (min_t, max_t) frames = max_t - min_t log.info(f"POSES: {n_points}") # checks data has expected shape tot_dims = 0 for key in motion_dict: dims = motion_dict[key].shape[1] exp_dims = pose_type_to_dims.get(key) tot_dims += motion_dict[key].shape[1] log.info(f"{key}: {motion_dict[key].shape}, dims {dims}, exp: {exp_dims}") log.info(f"total MOTION-X dims: {tot_dims}\n")
smplx_params = to_smplx_dict(motion_dict, timestep_range) tot_smplx_dims = 0 for key in smplx_params: tot_smplx_dims += smplx_params[key].shape[1] log.info(f"{key}: {smplx_params[key].shape}") log.info(f"TOTAL SMPLX dims: {tot_smplx_dims}\n")
if not is_inference: action_label_path = pjoin(data_root, 'texts', name + '.txt') action_label = load_label_from_file(action_label_path) emotion_label_path = pjoin(data_root, 'face_texts', name + '.txt') emotion_label = load_label_from_file(emotion_label_path) log.info(f"action: {action_label}") log.info(f"emotion: {emotion_label}")
if is_inference: emotion_label = args.prompt.split(' ')[0] if args.display_mesh: model_folder = os.path.join(MY_REPO, MODELS_DIR, "smplx") batch_size = max_t - min_t log.info(f"calculating mesh with batch size {batch_size}") model = smplx.SMPLX( model_folder, use_pca=False, # our joints are not in pca space num_expression_coeffs=NUM_FACIAL_EXPRESSION_DIMS, batch_size=batch_size, ) output = model.forward(**smplx_params, return_verts=True) log.info(f"output size {output.vertices.shape}") log.info(f"output size {output.joints.shape}") log.info("rendering mesh") model_name = args.model_path.split('/')[-1] if args.model_path else "ground_truth" gif_path = f"gifs/{model_name}/{name}_{emotion_label}.gif" render_meshes(output, gif_path=gif_path, should_save_gif=args.save_gif) log.warning( "if you don't see the mesh animation, make sure you are running on graphics compatible DTU machine (vgl xterm)." )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import pyrenderfrom tqdm import tqdmimport trimeshimport numpy as npimport osimport imageio
def save_gif(gif_path, gif_frames, duration=0.01): if gif_frames: print(f"Saving GIF with {len(gif_frames)} frames to {gif_path}") imageio.mimsave(uri=gif_path, ims=gif_frames, duration=duration) else: print("No frames to save.")
def render_meshes(model, output, should_save_gif=False, gif_path=None): should_display = not should_save_gif vertices_list = output.vertices.detach().cpu().numpy().squeeze() joints_list = output.joints.detach().cpu().numpy().squeeze() if len(vertices_list.shape) == 2: vertices_list = [vertices_list] joints_list = [joints_list] scene = pyrender.Scene() if should_display: viewer = pyrender.Viewer(scene, run_in_thread=True)
mesh_node = None joints_node = None # Rotation matrix (90 degrees around the X-axis) rot = trimesh.transformations.rotation_matrix(np.radians(90), [1, 0, 0]) gif_frames = [] if should_save_gif: os.makedirs(os.path.dirname(gif_path), exist_ok=True) try: for i in tqdm(range(len(vertices_list))): vertices = vertices_list[i] joints = joints_list[i] # print("Vertices shape =", vertices.shape) # print("Joints shape =", joints.shape)
# from their demo script plotting_module = "pyrender" plot_joints = False if plotting_module == "pyrender": vertex_colors = np.ones([vertices.shape[0], 4]) * [0.3, 0.3, 0.3, 0.8] tri_mesh = trimesh.Trimesh(vertices, model.faces, vertex_colors=vertex_colors)
# Apply rotation tri_mesh.apply_transform(rot) ##### RENDER LOCK ##### if should_display: viewer.render_lock.acquire() if mesh_node: scene.remove_node(mesh_node) mesh = pyrender.Mesh.from_trimesh(tri_mesh) mesh_node = scene.add(mesh)
camera = pyrender.PerspectiveCamera(yfov=np.pi / 3.0, aspectRatio=1.0) min_bound, max_bound = mesh.bounds
# Calculate the center of the bounding box center = (min_bound + max_bound) / 2
# Calculate the extents (the dimensions of the bounding box) extents = max_bound - min_bound
# Estimate a suitable distance distance = max(extents) * 2 # Adjust the multiplier as needed
# Create a camera pose matrix cam_pose = np.array( [ [1.0, 0, 0, center[0]], [0, 1.0, 0, center[1]-1.0], [0, 0, 1.0, center[2] + distance + 0.5], [0, 0, 0, 1], ] ) # Rotate around X-axis angle = np.radians(80) cos_angle = np.cos(angle) sin_angle = np.sin(angle) rot_x_10_deg = np.array([ [1, 0, 0, 0], [0, cos_angle, -sin_angle, 0], [0, sin_angle, cos_angle, 0], [0, 0, 0, 1] ]) # rotate cam_pose with rot_x_10_deg cam_pose = np.matmul(cam_pose, rot_x_10_deg) cam_pose[:3, 3] += np.array([0, -2.2, -3.0])
scene.add(camera, pose=cam_pose)
# Add light for better visualization light = pyrender.DirectionalLight(color=np.ones(3), intensity=2.0) scene.add(light, pose=cam_pose)
# TODO: rotation doesn't work here, so appears sideways if plot_joints: sm = trimesh.creation.uv_sphere(radius=0.005) sm.visual.vertex_colors = [0.9, 0.1, 0.1, 1.0] tfs = np.tile(np.eye(4), (len(joints), 1, 1)) # tfs[:, :3, 3] = joints for i, joint in enumerate(joints): tfs[i, :3, :3] = rot[:3, :3] tfs[i, :3, 3] = joint joints_pcl = pyrender.Mesh.from_trimesh(sm, poses=tfs) if joints_node: scene.remove_node(joints_node) joints_node = scene.add(joints_pcl) if should_save_gif: r = pyrender.OffscreenRenderer(viewport_width=640, viewport_height=480) color, _ = r.render(scene) gif_frames.append(color) r.delete() # Free up the resources ###### RENDER LOCK RELEASE ##### if should_display: viewer.render_lock.release() except KeyboardInterrupt: if should_display: viewer.close_external() save_gif(gif_path, gif_frames) finally: save_gif(gif_path, gif_frames)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556from os.path import join as pjoin
import numpy as npfrom motionx_explorer import (calc_mean_stddev_pose, drop_shapes_from_motion_arr, get_seq_names)
if __name__ == "__main__": # read names from ./data/GRAB/train.txt with open(pjoin("./data/GRAB", "train.txt"), "r") as f: names = f.readlines() names = [name.strip() for name in names] print(f"names: {names}") all_arrays = [] for name in names: # Load each NumPy array and add it to the list array = np.load(pjoin("./data/GRAB/joints", f"{name}.npy")) # drop shapes -> 212 dims array = drop_shapes_from_motion_arr(array) print(f"shape of {name}: {array.shape}") all_arrays.append(array) mean, stddev = calc_mean_stddev_pose(all_arrays) pose_dims = 212 assert mean.shape[0] == pose_dims assert stddev.shape[0] == pose_dims # check if stddev has 0's stdev_zeros = np.where(stddev == 0) n_zeros = len(stdev_zeros[0]) print(f"idx of stddev where 0: {stdev_zeros}") assert n_zeros == 0, "stddev has 0's, but it should not..." # save to ./data/GRAB/Mean.npy and ./data/GRAB/Std.npy mean_write_path = pjoin("./data/GRAB", "Mean.npy") stddev_write_path = pjoin("./data/GRAB", "Std.npy") with open(mean_write_path, "wb") as f: print(f"saving mean to {mean_write_path}") np.save(f, mean) with open(stddev_write_path, "wb") as f: print(f"saving stddev to {stddev_write_path}") np.save(f, stddev) # test calculate_mean_stddev # pose_dim = 3 # arrays_1s = np.full((4, pose_dim), 3) # arrays_2s = np.full((2, pose_dim), 2) # single_mean = (4*3 + 2*2) / (4+2) # std_dev_single = np.sqrt((4*(3-single_mean)**2 + 2*(2-single_mean)**2) / (4+2)) # exp_mean = np.full((pose_dim), single_mean) # exp_stddev = np.full((pose_dim), std_dev_single) # all_arrays = [arrays_1s, arrays_2s] # mean, stddev = calc_mean_stddev_pose(all_arrays) # print(f"mean: {mean}, exp mean: {exp_mean}") # print(f"stddev: {stddev}, exp stddev: {exp_stddev}") # assert mean.shape == (3,) # assert np.all(mean == exp_mean) # assert stddev.shape == (3,) # assert np.all(stddev == exp_stddev)123456789101112131415161718import torchimport numpy as npfrom numpy.typing import ArrayLike
def drop_shapes_from_motion_arr(motion_arr: ArrayLike) -> ArrayLike: if isinstance(motion_arr, torch.Tensor): new_motion_arr = motion_arr.numpy() # Slice the array to exclude 'face_shape' and 'betas' new_motion_arr = np.concatenate((motion_arr[:, :209], motion_arr[:, 309:312]), axis=1) return new_motion_arr
def load_label_from_file(file_path: str) -> str: with open(file_path, "r") as file: # Read the contents of the file into a string label = file.read() return label12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758## INSTALLATIONif you've noticed your python3 bin doens't point to your conda env when using --prefix to point to your scratch dir, then you need to do the following:* conda config --set always_copy True* conda config --show | grep always_copynow continue as normal:* conda create --prefix <your-scratch-path>/MotionDiffuse/env python=3.7* conda activate <your-scratch-path>/MotionDiffuse/env* double check your GCC is 5+ by running `gcc --version`; if not, do module load gcc/5.4.0* module load cuda/10.1 # you must run these icuda commands before installing torch otherwise it will say version not found!!* module load cudnn/v7.6.5.32-prod-cuda-10.1* conda install pytorch=1.7.1 torchvision=0.8.2 cudatoolkit=10.1 -c pytorch* python3 -m pip install "mmcv-full>=1.3.17,<=1.5.3" -f https://download.openmmlab.com/mmcv/dist/cu101/torch1.7.1/index.html* python3 -m pip install -r requirements.txt* python3 -m pip install --upgrade protobuf==3.20.0
fyi there is an annoying warning in the logs (https://stackoverflow.com/questions/57381430/synonym-of-type-is-deprecated-in-a-future-version-of-numpy-it-will-be-underst) that can be silenced by downgrading numpy:to 1.16.4 BUT this is incompatible with the other package versions, so don't do it
fyi:(/work3/s222376/MotionDiffuseNew) s222376@n-62-20-1 /work3/s222376/MotionDiffuse/text2motion (train_baseline)$ module listCurrently Loaded Modulefiles: 1) latex/TeXLive19(default) 3) cudnn/v7.6.5.32-prod-cuda-10.1 5) gcc/5.4.0 2) cuda/10.1 4) binutils/2.29(default) <aL>
## TRAINING* download KIT-ML data from <> and put the zip for it in text2motion/data/* cd text2motion/data && unzip KIT-ML-20231122T121619Z-001.zip* cd KIT-ML && unrar x new_joint_vecs.rar* unrar x new_joints.rar* unrar x texts.rar* dirs should look like```text2motion/data/KIT-ML├── new_joint_vecs│ ├─�├── new_joints│ ├─�└── texts ├─�--all.txt--<etc>```* voltash (dtu hpc command to go to interactive gpu node)* make train* verify above works without errors and then kill training because you're on interactive gpu, you will likely run out of memory anyway (can decrease --batchsize but then it's slow)* to do full training, edit jobscript.sh to use your email and submit job via "make queue"
## INFERENCE with pretrained model* download...checkpoints?? idk look at their README.md
## Changes I made* ignore standardization* tokens are [] empty...* reusing kit_chain thing lol* only training on one sequence from grab
TO KEEP IN MIND:* they specify best way to train in readme somewhere -- follow this when doing real training!* need to add the emotion text to the caption!!123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154# Installation
<!-- TOC -->
- [Requirements](#requirements)- [Prepare environment](#prepare-environment)- [Data Preparation](#data-preparation)
<!-- TOC -->
## Requirements
- Linux- Python 3.7+- PyTorch 1.6.0, 1.7.0, 1.7.1, 1.8.0, 1.8.1, 1.9.0 or 1.9.1.- CUDA 9.2+- GCC 5+- [MMCV](https://github.com/open-mmlab/mmcv) (Please install mmcv-full>=1.3.17,<1.6.0 for GPU)
## Prepare environment
a. Create a conda virtual environment and activate it.
```shellconda create -n motiondiffuse python=3.7 -yconda activate motiondiffuse```
b. Install PyTorch and torchvision following the [official instructions](https://pytorch.org/).```shellconda install pytorch={torch_version} torchvision cudatoolkit={cu_version} -c pytorch```
E.g., install PyTorch 1.7.1 & CUDA 10.1.```shellconda install pytorch=1.7.1 torchvision cudatoolkit=10.1 -c pytorch```
**Important:** Make sure that your compilation CUDA version and runtime CUDA version match.
c. Build mmcv-full
- mmcv-full
We recommend you to install the pre-build package as below.
For CPU:```shellpip install mmcv-full -f https://download.openmmlab.com/mmcv/dist/cpu/{torch_version}/index.html```Please replace `{torch_version}` in the url to your desired one.
For GPU:```shellpip install "mmcv-full>=1.3.17,<=1.5.3" -f https://download.openmmlab.com/mmcv/dist/{cu_version}/{torch_version}/index.html```Please replace `{cu_version}` and `{torch_version}` in the url to your desired one.
For example, to install mmcv-full with CUDA 10.1 and PyTorch 1.7.1, use the following command:```shellpip install "mmcv-full>=1.3.17,<=1.5.3" -f https://download.openmmlab.com/mmcv/dist/cu101/torch1.7.1/index.html```
See [here](https://mmcv.readthedocs.io/en/latest/get_started/installation.html) for different versions of MMCV compatible to different PyTorch and CUDA versions.For more version download link, refer to [openmmlab-download](https://download.openmmlab.com/mmcv/dist/index.html).
d. Install other requirements
```shellpip install -r requirements.txt```
## Data Preparation
a. Download datasets
For both the HumanML3D dataset and the KIT-ML dataset, you could find the details as well as download link [[here]](https://github.com/EricGuo5513/HumanML3D).
b. Download pretrained weights for evaluation
We use the same evaluation protocol as [this repo](https://github.com/EricGuo5513/text-to-motion). You should download pretrained weights of the contrastive models in [t2m](https://drive.google.com/file/d/1DSaKqWX2HlwBtVH5l7DdW96jeYUIXsOP/view) and [kit](https://drive.google.com/file/d/1tX79xk0fflp07EZ660Xz1RAFE33iEyJR/view) for calculating FID and precisions. To dynamically estimate the length of the target motion, `length_est_bigru` and [Glove data](https://drive.google.com/drive/folders/1qxHtwffhfI4qMwptNW6KJEDuT6bduqO7?usp=sharing) are required.
c. Download pretrained weights for **MotionDiffuse**
The pretrained weights for our proposed MotionDiffuse can be downloaded from [here](https://drive.google.com/drive/folders/1qxHtwffhfI4qMwptNW6KJEDuT6bduqO7?usp=sharing)
Download the above resources and arrange them in the following file structure:
```textMotionDiffuse└── text2motion ├── checkpoints │ ├── kit │ │ └── kit_motiondiffuse │ │ ├── meta │ │ │ ├── mean.npy │ │ │ └── std.npy │ │ ├── model │ │ │ └── latest.tar │ │ └── opt.txt │ └── t2m │ └── t2m_motiondiffuse │ ├── meta │ │ ├── mean.npy │ │ └── std.npy │ ├── model │ │ └── latest.tar │ └── opt.txt └── data ├── glove │ ├── our_vab_data.npy │ ├── our_vab_idx.pkl │ └── out_vab_words.pkl ├── pretrained_models │ ├── kit │ │ └── text_mot_match │ │ └── model │ │ └── finest.tar │ └── t2m │ │ ├── text_mot_match │ │ │ └── model │ │ │ └── finest.tar │ │ └── length_est_bigru │ │ └── model │ │ └── finest.tar ├── HumanML3D │ ├── new_joint_vecs │ │ └── ... │ ├── new_joints │ │ └── ... │ ├── texts │ │ └── ... │ ├── Mean.npy │ ├── Std.npy │ ├── test.txt │ ├── train_val.txt │ ├── train.txt │ └── val.txt └── KIT-ML ├── new_joint_vecs │ └── ... ├── new_joints │ └── ... ├── texts │ └── ... ├── Mean.npy ├── Std.npy ├── test.txt ├── train_val.txt ├── train.txt └── val.txt```12345678910111213141516171819202122232425262728293031323334353637383940#!/bin/sh### General options### –- specify queue --#BSUB -q gpuv100### -- set the job Name --#BSUB -J fulem_2g_excl_196### -- ask for number of cores (default: 1) --#BSUB -n 8### -- specify that the cores must be on the same host -- #BSUB -R "span[hosts=1]"### -- Select the resources: 1 gpu in exclusive process mode --#BSUB -gpu "num=2:mode=exclusive_process"### -- set walltime limit: hh:mm -- maximum 24 hours for GPU-queues right now#BSUB -W 15:00# request 5GB of system-memory#BSUB -R "rusage[mem=5GB]"### -- set the email address --# please uncomment the following line and put in your e-mail address,# if you want to receive e-mail notifications on a non-default address#BSUB -u s222376@dtu.dk### -- send notification at start --#BSUB -B### -- send notification at completion--#BSUB -N### -- Specify the output and error file. %J is the job-id --### -- -o and -e mean append, -oo and -eo mean overwrite --#BSUB -o gpu_%J.out#BSUB -e gpu_%J.err# -- end of LSF options --
nvidia-smi# Load the cuda module
module load cuda/10.1module load cudnn/v7.6.5.32-prod-cuda-10.1
echo "checking python bin location"which python3echo "training txt2motion diffusion model..."make train EXP=fulem_2g_excl_1961234from .transformer import MotionTransformerfrom .gaussian_diffusion import GaussianDiffusion
__all__ = ['MotionTransformer', 'GaussianDiffusion']1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147"""This code is borrowed from https://github.com/openai/guided-diffusion/blob/main/guided_diffusion/gaussian_diffusion.py"""
import enumimport mathfrom abc import ABC, abstractmethod
import numpy as npimport torch as thimport torch.distributed as dist
def create_named_schedule_sampler(name, diffusion): """ Create a ScheduleSampler from a library of pre-defined samplers. :param name: the name of the sampler. :param diffusion: the diffusion object to sample for. """ if name == "uniform": return UniformSampler(diffusion) elif name == "loss-second-moment": return LossSecondMomentResampler(diffusion) else: raise NotImplementedError(f"unknown schedule sampler: {name}")
class ScheduleSampler(ABC): """ A distribution over timesteps in the diffusion process, intended to reduce variance of the objective. By default, samplers perform unbiased importance sampling, in which the objective's mean is unchanged. However, subclasses may override sample() to change how the resampled terms are reweighted, allowing for actual changes in the objective. """
@abstractmethod def weights(self): """ Get a numpy array of weights, one per diffusion step. The weights needn't be normalized, but must be positive. """
def sample(self, batch_size, device): """ Importance-sample timesteps for a batch. :param batch_size: the number of timesteps. :param device: the torch device to save to. :return: a tuple (timesteps, weights): - timesteps: a tensor of timestep indices. - weights: a tensor of weights to scale the resulting losses. """ w = self.weights() p = w / np.sum(w) indices_np = np.random.choice(len(p), size=(batch_size,), p=p) indices = th.from_numpy(indices_np).long().to(device) weights_np = 1 / (len(p) * p[indices_np]) weights = th.from_numpy(weights_np).float().to(device) return indices, weights
class UniformSampler(ScheduleSampler): def __init__(self, diffusion): self.diffusion = diffusion self._weights = np.ones([diffusion.num_timesteps])
def weights(self): return self._weights
class LossAwareSampler(ScheduleSampler): def update_with_local_losses(self, local_ts, local_losses): """ Update the reweighting using losses from a model. Call this method from each rank with a batch of timesteps and the corresponding losses for each of those timesteps. This method will perform synchronization to make sure all of the ranks maintain the exact same reweighting. :param local_ts: an integer Tensor of timesteps. :param local_losses: a 1D Tensor of losses. """ batch_sizes = [ th.tensor([0], dtype=th.int32, device=local_ts.device) for _ in range(dist.get_world_size()) ] dist.all_gather( batch_sizes, th.tensor([len(local_ts)], dtype=th.int32, device=local_ts.device), )
# Pad all_gather batches to be the maximum batch size. batch_sizes = [x.item() for x in batch_sizes] max_bs = max(batch_sizes)
timestep_batches = [th.zeros(max_bs).to(local_ts) for bs in batch_sizes] loss_batches = [th.zeros(max_bs).to(local_losses) for bs in batch_sizes] dist.all_gather(timestep_batches, local_ts) dist.all_gather(loss_batches, local_losses) timesteps = [ x.item() for y, bs in zip(timestep_batches, batch_sizes) for x in y[:bs] ] losses = [x.item() for y, bs in zip(loss_batches, batch_sizes) for x in y[:bs]] self.update_with_all_losses(timesteps, losses)
@abstractmethod def update_with_all_losses(self, ts, losses): """ Update the reweighting using losses from a model. Sub-classes should override this method to update the reweighting using losses from the model. This method directly updates the reweighting without synchronizing between workers. It is called by update_with_local_losses from all ranks with identical arguments. Thus, it should have deterministic behavior to maintain state across workers. :param ts: a list of int timesteps. :param losses: a list of float losses, one per timestep. """
class LossSecondMomentResampler(LossAwareSampler): def __init__(self, diffusion, history_per_term=10, uniform_prob=0.001): self.diffusion = diffusion self.history_per_term = history_per_term self.uniform_prob = uniform_prob self._loss_history = np.zeros( [diffusion.num_timesteps, history_per_term], dtype=np.float64 ) self._loss_counts = np.zeros([diffusion.num_timesteps], dtype=np.int)
def weights(self): if not self._warmed_up(): return np.ones([self.diffusion.num_timesteps], dtype=np.float64) weights = np.sqrt(np.mean(self._loss_history ** 2, axis=-1)) weights /= np.sum(weights) weights *= 1 - self.uniform_prob weights += self.uniform_prob / len(weights) return weights
def update_with_all_losses(self, ts, losses): for t, loss in zip(ts, losses): if self._loss_counts[t] == self.history_per_term: # Shift out the oldest loss term. self._loss_history[t, :-1] = self._loss_history[t, 1:] self._loss_history[t, -1] = loss else: self._loss_history[t, self._loss_counts[t]] = loss self._loss_counts[t] += 1
def _warmed_up(self): return (self._loss_counts == self.history_per_term).all()
def mean_flat(tensor): """ Take the mean over all non-batch dimensions. """ return tensor.mean(dim=list(range(1, len(tensor.shape))))
def normal_kl(mean1, logvar1, mean2, logvar2): """ Compute the KL divergence between two gaussians. Shapes are automatically broadcasted, so batches can be compared to scalars, among other use cases. """ tensor = None for obj in (mean1, logvar1, mean2, logvar2): if isinstance(obj, th.Tensor): tensor = obj break assert tensor is not None, "at least one argument must be a Tensor"
# Force variances to be Tensors. Broadcasting helps convert scalars to # Tensors, but it does not work for th.exp(). logvar1, logvar2 = [ x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor) for x in (logvar1, logvar2) ]
return 0.5 * ( -1.0 + logvar2 - logvar1 + th.exp(logvar1 - logvar2) + ((mean1 - mean2) ** 2) * th.exp(-logvar2) )
def approx_standard_normal_cdf(x): """ A fast approximation of the cumulative distribution function of the standard normal. """ return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3))))
def discretized_gaussian_log_likelihood(x, *, means, log_scales): """ Compute the log-likelihood of a Gaussian distribution discretizing to a given image. :param x: the target images. It is assumed that this was uint8 values, rescaled to the range [-1, 1]. :param means: the Gaussian mean Tensor. :param log_scales: the Gaussian log stddev Tensor. :return: a tensor like x of log probabilities (in nats). """ assert x.shape == means.shape == log_scales.shape centered_x = x - means inv_stdv = th.exp(-log_scales) plus_in = inv_stdv * (centered_x + 1.0 / 255.0) cdf_plus = approx_standard_normal_cdf(plus_in) min_in = inv_stdv * (centered_x - 1.0 / 255.0) cdf_min = approx_standard_normal_cdf(min_in) log_cdf_plus = th.log(cdf_plus.clamp(min=1e-12)) log_one_minus_cdf_min = th.log((1.0 - cdf_min).clamp(min=1e-12)) cdf_delta = cdf_plus - cdf_min log_probs = th.where( x < -0.999, log_cdf_plus, th.where(x > 0.999, log_one_minus_cdf_min, th.log(cdf_delta.clamp(min=1e-12))), ) assert log_probs.shape == x.shape return log_probs
def get_named_beta_schedule(schedule_name, num_diffusion_timesteps): """ Get a pre-defined beta schedule for the given name.
The beta schedule library consists of beta schedules which remain similar in the limit of num_diffusion_timesteps. Beta schedules may be added, but should not be removed or changed once they are committed to maintain backwards compatibility. """ if schedule_name == "linear": # Linear schedule from Ho et al, extended to work for any number of # diffusion steps. scale = 1000 / num_diffusion_timesteps beta_start = scale * 0.0001 beta_end = scale * 0.02 return np.linspace( beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64 ) elif schedule_name == "cosine": return betas_for_alpha_bar( num_diffusion_timesteps, lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2, ) else: raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): """ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1].
:param num_diffusion_timesteps: the number of betas to produce. :param alpha_bar: a lambda that takes an argument t from 0 to 1 and produces the cumulative product of (1-beta) up to that part of the diffusion process. :param max_beta: the maximum beta to use; use values lower than 1 to prevent singularities. """ betas = [] for i in range(num_diffusion_timesteps): t1 = i / num_diffusion_timesteps t2 = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) return np.array(betas)
class ModelMeanType(enum.Enum): """ Which type of output the model predicts. """
PREVIOUS_X = enum.auto() # the model predicts x_{t-1} START_X = enum.auto() # the model predicts x_0 EPSILON = enum.auto() # the model predicts epsilon
class ModelVarType(enum.Enum): """ What is used as the model's output variance.
The LEARNED_RANGE option has been added to allow the model to predict values between FIXED_SMALL and FIXED_LARGE, making its job easier. """
LEARNED = enum.auto() FIXED_SMALL = enum.auto() FIXED_LARGE = enum.auto() LEARNED_RANGE = enum.auto()
class LossType(enum.Enum): MSE = enum.auto() # use raw MSE loss (and KL when learning variances) RESCALED_MSE = ( enum.auto() ) # use raw MSE loss (with RESCALED_KL when learning variances) KL = enum.auto() # use the variational lower-bound RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB
def is_vb(self): return self == LossType.KL or self == LossType.RESCALED_KL
class GaussianDiffusion: """ Utilities for training and sampling diffusion models.
Ported directly from here, and then adapted over time to further experimentation. https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42
:param betas: a 1-D numpy array of betas for each diffusion timestep, starting at T and going to 1. :param model_mean_type: a ModelMeanType determining what the model outputs. :param model_var_type: a ModelVarType determining how variance is output. :param loss_type: a LossType determining the loss function to use. :param rescale_timesteps: if True, pass floating point timesteps into the model so that they are always scaled like in the original paper (0 to 1000). """
def __init__( self, *, betas, model_mean_type, model_var_type, loss_type, rescale_timesteps=False, ): self.model_mean_type = model_mean_type self.model_var_type = model_var_type self.loss_type = loss_type self.rescale_timesteps = rescale_timesteps
# Use float64 for accuracy. betas = np.array(betas, dtype=np.float64) self.betas = betas assert len(betas.shape) == 1, "betas must be 1-D" assert (betas > 0).all() and (betas <= 1).all()
self.num_timesteps = int(betas.shape[0])
alphas = 1.0 - betas self.alphas_cumprod = np.cumprod(alphas, axis=0) self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1]) self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0) assert self.alphas_cumprod_prev.shape == (self.num_timesteps,)
# calculations for diffusion q(x_t | x_{t-1}) and others self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod) self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod) self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod) self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod) self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1)
# calculations for posterior q(x_{t-1} | x_t, x_0) self.posterior_variance = ( betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) ) # log calculation clipped because the posterior variance is 0 at the # beginning of the diffusion chain. self.posterior_log_variance_clipped = np.log( np.append(self.posterior_variance[1], self.posterior_variance[1:]) ) self.posterior_mean_coef1 = ( betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) ) self.posterior_mean_coef2 = ( (1.0 - self.alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - self.alphas_cumprod) )
def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0).
:param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = ( _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start ) variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = _extract_into_tensor( self.log_one_minus_alphas_cumprod, t, x_start.shape ) return mean, variance, log_variance
def q_sample(self, x_start, t, noise=None): """ Diffuse the data for a given number of diffusion steps.
In other words, sample from q(x_t | x_0).
:param x_start: the initial data batch. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :param noise: if specified, the split-out normal noise. :return: A noisy version of x_start. """ if noise is None: noise = th.randn_like(x_start) assert noise.shape == x_start.shape return ( _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise )
def q_posterior_mean_variance(self, x_start, x_t, t): """ Compute the mean and variance of the diffusion posterior:
q(x_{t-1} | x_t, x_0)
""" assert x_start.shape == x_t.shape posterior_mean = ( _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = _extract_into_tensor( self.posterior_log_variance_clipped, t, x_t.shape ) assert ( posterior_mean.shape[0] == posterior_variance.shape[0] == posterior_log_variance_clipped.shape[0] == x_start.shape[0] ) return posterior_mean, posterior_variance, posterior_log_variance_clipped
def p_mean_variance( self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None ): """ Apply the model to get p(x_{t-1} | x_t), as well as a prediction of the initial x, x_0.
:param model: the model, which takes a signal and a batch of timesteps as input. :param x: the [N x C x ...] tensor at time t. :param t: a 1-D Tensor of timesteps. :param clip_denoised: if True, clip the denoised signal into [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. Applies before clip_denoised. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :return: a dict with the following keys: - 'mean': the model mean output. - 'variance': the model variance output. - 'log_variance': the log of 'variance'. - 'pred_xstart': the prediction for x_0. """ if model_kwargs is None: model_kwargs = {}
B, C = x.shape[:2] assert t.shape == (B,) model_output = model(x, self._scale_timesteps(t), **model_kwargs)
if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]: assert model_output.shape == (B, 2 * C, *x.shape[2:]) model_output, model_var_values = th.split(model_output, C, dim=1) if self.model_var_type == ModelVarType.LEARNED: model_log_variance = model_var_values model_variance = th.exp(model_log_variance) else: min_log = _extract_into_tensor( self.posterior_log_variance_clipped, t, x.shape ) max_log = _extract_into_tensor(np.log(self.betas), t, x.shape) # The model_var_values is [-1, 1] for [min_var, max_var]. frac = (model_var_values + 1) / 2 model_log_variance = frac * max_log + (1 - frac) * min_log model_variance = th.exp(model_log_variance) else: model_variance, model_log_variance = { # for fixedlarge, we set the initial (log-)variance like so # to get a better decoder log likelihood. ModelVarType.FIXED_LARGE: ( np.append(self.posterior_variance[1], self.betas[1:]), np.log(np.append(self.posterior_variance[1], self.betas[1:])), ), ModelVarType.FIXED_SMALL: ( self.posterior_variance, self.posterior_log_variance_clipped, ), }[self.model_var_type] model_variance = _extract_into_tensor(model_variance, t, x.shape) model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape)
def process_xstart(x): if denoised_fn is not None: x = denoised_fn(x) if clip_denoised: return x.clamp(-1, 1) return x
if self.model_mean_type == ModelMeanType.PREVIOUS_X: pred_xstart = process_xstart( self._predict_xstart_from_xprev(x_t=x, t=t, xprev=model_output) ) model_mean = model_output elif self.model_mean_type in [ModelMeanType.START_X, ModelMeanType.EPSILON]: if self.model_mean_type == ModelMeanType.START_X: pred_xstart = process_xstart(model_output) else: pred_xstart = process_xstart( self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output) ) model_mean, _, _ = self.q_posterior_mean_variance( x_start=pred_xstart, x_t=x, t=t ) else: raise NotImplementedError(self.model_mean_type)
assert ( model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape ) return { "mean": model_mean, "variance": model_variance, "log_variance": model_log_variance, "pred_xstart": pred_xstart, }
def _predict_xstart_from_eps(self, x_t, t, eps): assert x_t.shape == eps.shape return ( _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps )
def _predict_xstart_from_xprev(self, x_t, t, xprev): assert x_t.shape == xprev.shape return ( # (xprev - coef2*x_t) / coef1 _extract_into_tensor(1.0 / self.posterior_mean_coef1, t, x_t.shape) * xprev - _extract_into_tensor( self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape ) * x_t )
def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return ( _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
def _scale_timesteps(self, t): if self.rescale_timesteps: return t.float() * (1000.0 / self.num_timesteps) return t
def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None): """ Compute the mean for the previous step, given a function cond_fn that computes the gradient of a conditional log probability with respect to x. In particular, cond_fn computes grad(log(p(y|x))), and we want to condition on y.
This uses the conditioning strategy from Sohl-Dickstein et al. (2015). """ gradient = cond_fn(x, self._scale_timesteps(t), **model_kwargs) new_mean = ( p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float() ) return new_mean
def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None): """ Compute what the p_mean_variance output would have been, should the model's score function be conditioned by cond_fn.
See condition_mean() for details on cond_fn.
Unlike condition_mean(), this instead uses the conditioning strategy from Song et al (2020). """ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)
eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"]) eps = eps - (1 - alpha_bar).sqrt() * cond_fn( x, self._scale_timesteps(t), **model_kwargs )
out = p_mean_var.copy() out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps) out["mean"], _, _ = self.q_posterior_mean_variance( x_start=out["pred_xstart"], x_t=x, t=t ) return out
def p_sample( self, model, x, t, clip_denoised=True, denoised_fn=None, cond_fn=None, pre_seq=None, transl_req=None, model_kwargs=None, ): """ Sample x_{t-1} from the model at the given timestep.
:param model: the model to sample from. :param x: the current tensor at x_{t-1}. :param t: the value of t, starting at 0 for the first diffusion step. :param clip_denoised: if True, clip the x_start prediction to [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. :param cond_fn: if not None, this is a gradient function that acts similarly to the model. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :return: a dict containing the following keys: - 'sample': a random sample from the model. - 'pred_xstart': a prediction of x_0. """ # concat seq if pre_seq is not None: T = pre_seq.shape[2] noise = th.randn_like(pre_seq) x_t = self.q_sample(pre_seq, t, noise=noise) x[:, :, :T] = x_t
if transl_req is not None: for item in transl_req: noise = th.randn(2).type_as(x) transl = th.Tensor(item[1:]).type_as(x) x_t = self.q_sample(transl, t, noise=noise) x[:, :2, item[0]] = x_t
out = self.p_mean_variance( model, x, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) noise = th.randn_like(x) nonzero_mask = ( (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) ) # no noise when t == 0 if cond_fn is not None: out["mean"] = self.condition_mean( cond_fn, out, x, t, model_kwargs=model_kwargs ) sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise return {"sample": sample, "pred_xstart": out["pred_xstart"]}
def p_sample_loop( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, pre_seq=None, transl_req=None, progress=False, ): """ Generate samples from the model.
:param model: the model module. :param shape: the shape of the samples, (N, C, H, W). :param noise: if specified, the noise from the encoder to sample. Should be of the same shape as `shape`. :param clip_denoised: if True, clip x_start predictions to [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. :param cond_fn: if not None, this is a gradient function that acts similarly to the model. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :param device: if specified, the device to create the samples on. If not specified, use a model parameter's device. :param progress: if True, show a tqdm progress bar. :return: a non-differentiable batch of samples. """ final = None for sample in self.p_sample_loop_progressive( model, shape, noise=noise, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, device=device, pre_seq=pre_seq, transl_req=transl_req, progress=progress, ): final = sample return final["sample"]
def p_sample_loop_progressive( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, pre_seq=None, transl_req=None, progress=False, ): """ Generate samples from the model and yield intermediate samples from each timestep of diffusion.
Arguments are the same as p_sample_loop(). Returns a generator over dicts, where each dict is the return value of p_sample(). """ if device is None: device = next(model.parameters()).device assert isinstance(shape, (tuple, list)) if noise is not None: img = noise else: img = th.randn(*shape, device=device) indices = list(range(self.num_timesteps))[::-1] if progress: # Lazy import so that we don't depend on tqdm. from tqdm.auto import tqdm
indices = tqdm(indices)
for i in indices: t = th.tensor([i] * shape[0], device=device) with th.no_grad(): out = self.p_sample( model, img, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, pre_seq=pre_seq, transl_req=transl_req ) yield out img = out["sample"] # write sample to /work3/s222376/MotionDiffuse2/text2motion/generation_samples # write torch tensor to numpy array with open(f'/work3/s222376/MotionDiffuse2/text2motion/generation_samples/sample_{t}.npy', 'wb') as f: np.save(f, img.cpu().numpy())
def ddim_sample( self, model, x, t, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, eta=0.0, ): """ Sample x_{t-1} from the model using DDIM.
Same usage as p_sample(). """ out = self.p_mean_variance( model, x, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) if cond_fn is not None: out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs)
# Usually our model outputs epsilon, but we re-derive it # in case we used x_start or x_prev prediction. eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape) alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape) sigma = ( eta * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar)) * th.sqrt(1 - alpha_bar / alpha_bar_prev) ) # Equation 12. noise = th.randn_like(x) mean_pred = ( out["pred_xstart"] * th.sqrt(alpha_bar_prev) + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps ) nonzero_mask = ( (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) ) # no noise when t == 0 sample = mean_pred + nonzero_mask * sigma * noise return {"sample": sample, "pred_xstart": out["pred_xstart"]}
def ddim_reverse_sample( self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None, eta=0.0, ): """ Sample x_{t+1} from the model using DDIM reverse ODE. """ assert eta == 0.0, "Reverse ODE only for deterministic path" out = self.p_mean_variance( model, x, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) # Usually our model outputs epsilon, but we re-derive it # in case we used x_start or x_prev prediction. eps = ( _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x - out["pred_xstart"] ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape) alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape)
# Equation 12. reversed mean_pred = ( out["pred_xstart"] * th.sqrt(alpha_bar_next) + th.sqrt(1 - alpha_bar_next) * eps )
return {"sample": mean_pred, "pred_xstart": out["pred_xstart"]}
def ddim_sample_loop( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, eta=0.0, ): """ Generate samples from the model using DDIM.
Same usage as p_sample_loop(). """ final = None for sample in self.ddim_sample_loop_progressive( model, shape, noise=noise, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, device=device, progress=progress, eta=eta, ): final = sample return final["sample"]
def ddim_sample_loop_progressive( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, eta=0.0, ): """ Use DDIM to sample from the model and yield intermediate samples from each timestep of DDIM.
Same usage as p_sample_loop_progressive(). """ if device is None: device = next(model.parameters()).device assert isinstance(shape, (tuple, list)) if noise is not None: img = noise else: img = th.randn(*shape, device=device) indices = list(range(self.num_timesteps))[::-1]
if progress: # Lazy import so that we don't depend on tqdm. from tqdm.auto import tqdm
indices = tqdm(indices)
for i in indices: t = th.tensor([i] * shape[0], device=device) with th.no_grad(): out = self.ddim_sample( model, img, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, eta=eta, ) yield out img = out["sample"]
def _vb_terms_bpd( self, model, x_start, x_t, t, clip_denoised=True, model_kwargs=None ): """ Get a term for the variational lower-bound.
The resulting units are bits (rather than nats, as one might expect). This allows for comparison to other papers.
:return: a dict with the following keys: - 'output': a shape [N] tensor of NLLs or KLs. - 'pred_xstart': the x_0 predictions. """ true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance( x_start=x_start, x_t=x_t, t=t ) out = self.p_mean_variance( model, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs ) kl = normal_kl( true_mean, true_log_variance_clipped, out["mean"], out["log_variance"] ) kl = mean_flat(kl) / np.log(2.0)
decoder_nll = -discretized_gaussian_log_likelihood( x_start, means=out["mean"], log_scales=0.5 * out["log_variance"] ) assert decoder_nll.shape == x_start.shape decoder_nll = mean_flat(decoder_nll) / np.log(2.0)
# At the first timestep return the decoder NLL, # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t)) output = th.where((t == 0), decoder_nll, kl) return {"output": output, "pred_xstart": out["pred_xstart"]}
def training_losses(self, model, x_start, t, model_kwargs=None, noise=None): """ Compute training losses for a single timestep.
:param model: the model to evaluate loss on. :param x_start: the [N x C x ...] tensor of inputs. :param t: a batch of timestep indices. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :param noise: if specified, the specific Gaussian noise to try to remove. :return: a dict with the key "loss" containing a tensor of shape [N]. Some mean or variance settings may also have other keys. """ if model_kwargs is None: model_kwargs = {} if noise is None: noise = th.randn_like(x_start) x_t = self.q_sample(x_start, t, noise=noise)
terms = {}
if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL: terms["loss"] = self._vb_terms_bpd( model=model, x_start=x_start, x_t=x_t, t=t, clip_denoised=False, model_kwargs=model_kwargs, )["output"] if self.loss_type == LossType.RESCALED_KL: terms["loss"] *= self.num_timesteps elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE: model_output = model(x_t, self._scale_timesteps(t), **model_kwargs)
if self.model_var_type in [ ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE, ]: B, C = x_t.shape[:2] assert model_output.shape == (B, C * 2, *x_t.shape[2:]) model_output, model_var_values = th.split(model_output, C, dim=1) # Learn the variance using the variational bound, but don't let # it affect our mean prediction. frozen_out = th.cat([model_output.detach(), model_var_values], dim=1) terms["vb"] = self._vb_terms_bpd( model=lambda *args, r=frozen_out: r, x_start=x_start, x_t=x_t, t=t, clip_denoised=False, )["output"] if self.loss_type == LossType.RESCALED_MSE: # Divide by 1000 for equivalence with initial implementation. # Without a factor of 1/1000, the VB term hurts the MSE term. terms["vb"] *= self.num_timesteps / 1000.0
target = { ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance( x_start=x_start, x_t=x_t, t=t )[0], ModelMeanType.START_X: x_start, ModelMeanType.EPSILON: noise, }[self.model_mean_type] assert model_output.shape == target.shape == x_start.shape terms["mse"] = mean_flat((target - model_output) ** 2).view(-1, 1).mean(-1) # if "vb" in terms: # terms["loss"] = terms["mse"] + terms["vb"] # else: # terms["loss"] = terms["mse"] terms["target"] = target terms["pred"] = model_output else: raise NotImplementedError(self.loss_type)
return terms
def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim.
This term can't be optimized, as it only depends on the encoder.
:param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = th.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) kl_prior = normal_kl( mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0 ) return mean_flat(kl_prior) / np.log(2.0)
def calc_bpd_loop(self, model, x_start, clip_denoised=True, model_kwargs=None): """ Compute the entire variational lower-bound, measured in bits-per-dim, as well as other related quantities.
:param model: the model to evaluate loss on. :param x_start: the [N x C x ...] tensor of inputs. :param clip_denoised: if True, clip denoised samples. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning.
:return: a dict containing the following keys: - total_bpd: the total variational lower-bound, per batch element. - prior_bpd: the prior term in the lower-bound. - vb: an [N x T] tensor of terms in the lower-bound. - xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep. - mse: an [N x T] tensor of epsilon MSEs for each timestep. """ device = x_start.device batch_size = x_start.shape[0]
vb = [] xstart_mse = [] mse = [] for t in list(range(self.num_timesteps))[::-1]: t_batch = th.tensor([t] * batch_size, device=device) noise = th.randn_like(x_start) x_t = self.q_sample(x_start=x_start, t=t_batch, noise=noise) # Calculate VLB term at the current timestep with th.no_grad(): out = self._vb_terms_bpd( model, x_start=x_start, x_t=x_t, t=t_batch, clip_denoised=clip_denoised, model_kwargs=model_kwargs, ) vb.append(out["output"]) xstart_mse.append(mean_flat((out["pred_xstart"] - x_start) ** 2)) eps = self._predict_eps_from_xstart(x_t, t_batch, out["pred_xstart"]) mse.append(mean_flat((eps - noise) ** 2))
vb = th.stack(vb, dim=1) xstart_mse = th.stack(xstart_mse, dim=1) mse = th.stack(mse, dim=1)
prior_bpd = self._prior_bpd(x_start) total_bpd = vb.sum(dim=1) + prior_bpd return { "total_bpd": total_bpd, "prior_bpd": prior_bpd, "vb": vb, "xstart_mse": xstart_mse, "mse": mse, }
def _extract_into_tensor(arr, timesteps, broadcast_shape): """ Extract values from a 1-D numpy array for a batch of indices.
:param arr: the 1-D numpy array. :param timesteps: a tensor of indices into the array to extract. :param broadcast_shape: a larger shape of K dimensions with the batch dimension equal to the length of timesteps. :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims. """ res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float() while len(res.shape) < len(broadcast_shape): res = res[..., None] return res.expand(broadcast_shape)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429"""Copyright 2021 S-Lab"""
from cv2 import normimport torchimport torch.nn.functional as Ffrom torch import layer_norm, nnimport numpy as npimport clip
import math
def timestep_embedding(timesteps, dim, max_period=10000): """ Create sinusoidal timestep embeddings. :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an [N x dim] Tensor of positional embeddings. """ half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=timesteps.device) args = timesteps[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def set_requires_grad(nets, requires_grad=False): """Set requies_grad for all the networks.
Args: nets (nn.Module | list[nn.Module]): A list of networks or a single network. requires_grad (bool): Whether the networks require gradients or not """ if not isinstance(nets, list): nets = [nets] for net in nets: if net is not None: for param in net.parameters(): param.requires_grad = requires_grad
def zero_module(module): """ Zero out the parameters of a module and return it. """ for p in module.parameters(): p.detach().zero_() return module
class StylizationBlock(nn.Module):
def __init__(self, latent_dim, time_embed_dim, dropout): super().__init__() self.emb_layers = nn.Sequential( nn.SiLU(), nn.Linear(time_embed_dim, 2 * latent_dim), ) self.norm = nn.LayerNorm(latent_dim) self.out_layers = nn.Sequential( nn.SiLU(), nn.Dropout(p=dropout), zero_module(nn.Linear(latent_dim, latent_dim)), )
def forward(self, h, emb): """ h: B, T, D emb: B, D """ # B, 1, 2D emb_out = self.emb_layers(emb).unsqueeze(1) # scale: B, 1, D / shift: B, 1, D scale, shift = torch.chunk(emb_out, 2, dim=2) h = self.norm(h) * (1 + scale) + shift h = self.out_layers(h) return h
class LinearTemporalSelfAttention(nn.Module):
def __init__(self, seq_len, latent_dim, num_head, dropout, time_embed_dim): super().__init__() self.num_head = num_head self.norm = nn.LayerNorm(latent_dim) self.query = nn.Linear(latent_dim, latent_dim) self.key = nn.Linear(latent_dim, latent_dim) self.value = nn.Linear(latent_dim, latent_dim) self.dropout = nn.Dropout(dropout) self.proj_out = StylizationBlock(latent_dim, time_embed_dim, dropout) def forward(self, x, emb, src_mask): """ x: B, T, D """ B, T, D = x.shape H = self.num_head # B, T, D query = self.query(self.norm(x)) # B, T, D key = (self.key(self.norm(x)) + (1 - src_mask) * -1000000) query = F.softmax(query.view(B, T, H, -1), dim=-1) key = F.softmax(key.view(B, T, H, -1), dim=1) # B, T, H, HD value = (self.value(self.norm(x)) * src_mask).view(B, T, H, -1) # B, H, HD, HD attention = torch.einsum('bnhd,bnhl->bhdl', key, value) y = torch.einsum('bnhd,bhdl->bnhl', query, attention).reshape(B, T, D) y = x + self.proj_out(y, emb) return y
class LinearTemporalCrossAttention(nn.Module):
def __init__(self, seq_len, latent_dim, text_latent_dim, num_head, dropout, time_embed_dim): super().__init__() self.num_head = num_head self.norm = nn.LayerNorm(latent_dim) self.text_norm = nn.LayerNorm(text_latent_dim) self.query = nn.Linear(latent_dim, latent_dim) self.key = nn.Linear(text_latent_dim, latent_dim) self.value = nn.Linear(text_latent_dim, latent_dim) self.dropout = nn.Dropout(dropout) self.proj_out = StylizationBlock(latent_dim, time_embed_dim, dropout) def forward(self, x, xf, emb): """ x: B, T, D xf: B, N, L """ B, T, D = x.shape N = xf.shape[1] H = self.num_head # B, T, D query = self.query(self.norm(x)) # B, N, D key = self.key(self.text_norm(xf)) query = F.softmax(query.view(B, T, H, -1), dim=-1) key = F.softmax(key.view(B, N, H, -1), dim=1) # B, N, H, HD value = self.value(self.text_norm(xf)).view(B, N, H, -1) # B, H, HD, HD attention = torch.einsum('bnhd,bnhl->bhdl', key, value) y = torch.einsum('bnhd,bhdl->bnhl', query, attention).reshape(B, T, D) y = x + self.proj_out(y, emb) return y
class FFN(nn.Module):
def __init__(self, latent_dim, ffn_dim, dropout, time_embed_dim): super().__init__() self.linear1 = nn.Linear(latent_dim, ffn_dim) self.linear2 = zero_module(nn.Linear(ffn_dim, latent_dim)) self.activation = nn.GELU() self.dropout = nn.Dropout(dropout) self.proj_out = StylizationBlock(latent_dim, time_embed_dim, dropout)
def forward(self, x, emb): y = self.linear2(self.dropout(self.activation(self.linear1(x)))) y = x + self.proj_out(y, emb) return y
class LinearTemporalDiffusionTransformerDecoderLayer(nn.Module):
def __init__(self, seq_len=60, latent_dim=32, text_latent_dim=512, time_embed_dim=128, ffn_dim=256, num_head=4, dropout=0.1): super().__init__() self.sa_block = LinearTemporalSelfAttention( seq_len, latent_dim, num_head, dropout, time_embed_dim) self.ca_block = LinearTemporalCrossAttention( seq_len, latent_dim, text_latent_dim, num_head, dropout, time_embed_dim) self.ffn = FFN(latent_dim, ffn_dim, dropout, time_embed_dim)
def forward(self, x, xf, emb, src_mask): x = self.sa_block(x, emb, src_mask) x = self.ca_block(x, xf, emb) x = self.ffn(x, emb) return x
class TemporalSelfAttention(nn.Module):
def __init__(self, seq_len, latent_dim, num_head, dropout, time_embed_dim): super().__init__() self.num_head = num_head self.norm = nn.LayerNorm(latent_dim) self.query = nn.Linear(latent_dim, latent_dim) self.key = nn.Linear(latent_dim, latent_dim) self.value = nn.Linear(latent_dim, latent_dim) self.dropout = nn.Dropout(dropout) self.proj_out = StylizationBlock(latent_dim, time_embed_dim, dropout) def forward(self, x, emb, src_mask): """ x: B, T, D """ B, T, D = x.shape H = self.num_head # B, T, 1, D query = self.query(self.norm(x)).unsqueeze(2) # B, 1, T, D key = self.key(self.norm(x)).unsqueeze(1) query = query.view(B, T, H, -1) key = key.view(B, T, H, -1) # B, T, T, H attention = torch.einsum('bnhd,bmhd->bnmh', query, key) / math.sqrt(D // H) attention = attention + (1 - src_mask.unsqueeze(-1)) * -100000 weight = self.dropout(F.softmax(attention, dim=2)) value = self.value(self.norm(x)).view(B, T, H, -1) y = torch.einsum('bnmh,bmhd->bnhd', weight, value).reshape(B, T, D) y = x + self.proj_out(y, emb) return y
class TemporalCrossAttention(nn.Module):
def __init__(self, seq_len, latent_dim, text_latent_dim, num_head, dropout, time_embed_dim): super().__init__() self.num_head = num_head self.norm = nn.LayerNorm(latent_dim) self.text_norm = nn.LayerNorm(text_latent_dim) self.query = nn.Linear(latent_dim, latent_dim) self.key = nn.Linear(text_latent_dim, latent_dim) self.value = nn.Linear(text_latent_dim, latent_dim) self.dropout = nn.Dropout(dropout) self.proj_out = StylizationBlock(latent_dim, time_embed_dim, dropout) def forward(self, x, xf, emb): """ x: B, T, D xf: B, N, L """ B, T, D = x.shape N = xf.shape[1] H = self.num_head # B, T, 1, D query = self.query(self.norm(x)).unsqueeze(2) # B, 1, N, D key = self.key(self.text_norm(xf)).unsqueeze(1) query = query.view(B, T, H, -1) key = key.view(B, N, H, -1) # B, T, N, H attention = torch.einsum('bnhd,bmhd->bnmh', query, key) / math.sqrt(D // H) weight = self.dropout(F.softmax(attention, dim=2)) value = self.value(self.text_norm(xf)).view(B, N, H, -1) y = torch.einsum('bnmh,bmhd->bnhd', weight, value).reshape(B, T, D) y = x + self.proj_out(y, emb) return y
class TemporalDiffusionTransformerDecoderLayer(nn.Module):
def __init__(self, seq_len=60, latent_dim=32, text_latent_dim=512, time_embed_dim=128, ffn_dim=256, num_head=4, dropout=0.1): super().__init__() self.sa_block = TemporalSelfAttention( seq_len, latent_dim, num_head, dropout, time_embed_dim) self.ca_block = TemporalCrossAttention( seq_len, latent_dim, text_latent_dim, num_head, dropout, time_embed_dim) self.ffn = FFN(latent_dim, ffn_dim, dropout, time_embed_dim)
def forward(self, x, xf, emb, src_mask): x = self.sa_block(x, emb, src_mask) x = self.ca_block(x, xf, emb) x = self.ffn(x, emb) return x
class MotionTransformer(nn.Module): def __init__(self, input_feats, num_frames=240, latent_dim=512, ff_size=1024, num_layers=8, num_heads=8, dropout=0, activation="gelu", num_text_layers=4, text_latent_dim=256, text_ff_size=2048, text_num_heads=4, no_clip=False, no_eff=False, **kargs): super().__init__() self.num_frames = num_frames self.latent_dim = latent_dim self.ff_size = ff_size self.num_layers = num_layers self.num_heads = num_heads self.dropout = dropout self.activation = activation self.input_feats = input_feats self.time_embed_dim = latent_dim * 4 self.sequence_embedding = nn.Parameter(torch.randn(num_frames, latent_dim))
# Text Transformer self.clip, _ = clip.load('ViT-B/32', "cpu") if no_clip: self.clip.initialize_parameters() else: set_requires_grad(self.clip, False) if text_latent_dim != 512: self.text_pre_proj = nn.Linear(512, text_latent_dim) else: self.text_pre_proj = nn.Identity() textTransEncoderLayer = nn.TransformerEncoderLayer( d_model=text_latent_dim, nhead=text_num_heads, dim_feedforward=text_ff_size, dropout=dropout, activation=activation) self.textTransEncoder = nn.TransformerEncoder( textTransEncoderLayer, num_layers=num_text_layers) self.text_ln = nn.LayerNorm(text_latent_dim) self.text_proj = nn.Sequential( nn.Linear(text_latent_dim, self.time_embed_dim) )
# Input Embedding self.joint_embed = nn.Linear(self.input_feats, self.latent_dim)
self.time_embed = nn.Sequential( nn.Linear(self.latent_dim, self.time_embed_dim), nn.SiLU(), nn.Linear(self.time_embed_dim, self.time_embed_dim), ) self.temporal_decoder_blocks = nn.ModuleList() for i in range(num_layers): if no_eff: self.temporal_decoder_blocks.append( TemporalDiffusionTransformerDecoderLayer( seq_len=num_frames, latent_dim=latent_dim, text_latent_dim=text_latent_dim, time_embed_dim=self.time_embed_dim, ffn_dim=ff_size, num_head=num_heads, dropout=dropout ) ) else: self.temporal_decoder_blocks.append( LinearTemporalDiffusionTransformerDecoderLayer( seq_len=num_frames, latent_dim=latent_dim, text_latent_dim=text_latent_dim, time_embed_dim=self.time_embed_dim, ffn_dim=ff_size, num_head=num_heads, dropout=dropout ) ) # Output Module self.out = zero_module(nn.Linear(self.latent_dim, self.input_feats)) def encode_text(self, text, device): with torch.no_grad(): text = clip.tokenize(text, truncate=True).to(device) x = self.clip.token_embedding(text).type(self.clip.dtype) # [batch_size, n_ctx, d_model]
x = x + self.clip.positional_embedding.type(self.clip.dtype) x = x.permute(1, 0, 2) # NLD -> LND x = self.clip.transformer(x) x = self.clip.ln_final(x).type(self.clip.dtype)
# T, B, D x = self.text_pre_proj(x) xf_out = self.textTransEncoder(x) xf_out = self.text_ln(xf_out) xf_proj = self.text_proj(xf_out[text.argmax(dim=-1), torch.arange(xf_out.shape[1])]) # B, T, D xf_out = xf_out.permute(1, 0, 2) return xf_proj, xf_out
def generate_src_mask(self, T, length): B = len(length) src_mask = torch.ones(B, T) for i in range(B): for j in range(length[i], T): src_mask[i, j] = 0 return src_mask
def forward(self, x, timesteps, length=None, text=None, xf_proj=None, xf_out=None): """ x: B, T, D """ B, T = x.shape[0], x.shape[1] if text is not None and len(text) != B: index = x.device.index text = text[index * B: index * B + B] if xf_proj is None or xf_out is None: xf_proj, xf_out = self.encode_text(text, x.device)
emb = self.time_embed(timestep_embedding(timesteps, self.latent_dim)) + xf_proj
# B, T, latent_dim h = self.joint_embed(x) h = h + self.sequence_embedding.unsqueeze(0)[:, :T, :]
src_mask = self.generate_src_mask(T, length).to(x.device).unsqueeze(-1) for module in self.temporal_decoder_blocks: h = module(h, xf_out, emb, src_mask)
output = self.out(h).view(B, T, -1).contiguous() return output12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091import argparseimport os
import torchimport torch.distributed as distfrom mmcv.runner import get_dist_info, init_dist
class BaseOptions(): def __init__(self): self.parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter) self.initialized = False
def initialize(self): self.parser.add_argument('--name', type=str, default="test", help='Name of this trial') self.parser.add_argument('--decomp_name', type=str, default="Decomp_SP001_SM001_H512", help='Name of autoencoder model')
self.parser.add_argument("--gpu_id", type=int, nargs='+', default=(-1), help='GPU id') self.parser.add_argument("--distributed", action="store_true", help='Whether to use DDP training') self.parser.add_argument("--data_parallel", action="store_true", help="Whether to use DP training")
self.parser.add_argument('--dataset_name', type=str, default='t2m', help='Dataset Name') self.parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints', help='models are saved here')
self.parser.add_argument("--unit_length", type=int, default=4, help="Motions are cropped to the maximum times of unit_length") self.parser.add_argument("--max_text_len", type=int, default=20, help="Maximum length of text description")
self.parser.add_argument('--text_enc_mod', type=str, default='bigru') self.parser.add_argument('--estimator_mod', type=str, default='bigru')
self.parser.add_argument('--dim_text_hidden', type=int, default=512, help='Dimension of hidden unit in text encoder') self.parser.add_argument('--dim_att_vec', type=int, default=512, help='Dimension of attention vector') self.parser.add_argument('--dim_z', type=int, default=128, help='Dimension of latent Gaussian vector')
self.parser.add_argument('--n_layers_pri', type=int, default=1, help='Number of layers in prior network') self.parser.add_argument('--n_layers_pos', type=int, default=1, help='Number of layers in posterior network') self.parser.add_argument('--n_layers_dec', type=int, default=1, help='Number of layers in generator')
self.parser.add_argument('--dim_pri_hidden', type=int, default=1024, help='Dimension of hidden unit in prior network') self.parser.add_argument('--dim_pos_hidden', type=int, default=1024, help='Dimension of hidden unit in posterior network') self.parser.add_argument('--dim_dec_hidden', type=int, default=1024, help='Dimension of hidden unit in generator')
self.parser.add_argument('--dim_movement_enc_hidden', type=int, default=512, help='Dimension of hidden in AutoEncoder(encoder)') self.parser.add_argument('--dim_movement_dec_hidden', type=int, default=512, help='Dimension of hidden in AutoEncoder(decoder)') self.parser.add_argument('--dim_movement_latent', type=int, default=512, help='Dimension of motion snippet')
self.initialized = True
def parse(self): if not self.initialized: self.initialize()
self.opt = self.parser.parse_args()
self.opt.is_train = self.is_train
args = vars(self.opt) if args["distributed"]: init_dist('slurm') rank, world_size = get_dist_info() if args["distributed"]: self.opt.gpu_id = range(world_size) elif self.opt.gpu_id != (-1): if len(self.opt.gpu_id) == 1: torch.cuda.set_device(self.opt.gpu_id[0]) else: assert args["data_parallel"] == False
if rank == 0: print('------------ Options -------------') for k, v in sorted(args.items()): print('%s: %s' % (str(k), str(v))) print('-------------- End ----------------') if self.is_train: # save to the disk expr_dir = os.path.join(self.opt.checkpoints_dir, self.opt.dataset_name, self.opt.name) if not os.path.exists(expr_dir): os.makedirs(expr_dir) file_name = os.path.join(expr_dir, 'opt.txt') with open(file_name, 'wt') as opt_file: opt_file.write('------------ Options -------------\n') for k, v in sorted(args.items()): opt_file.write('%s: %s\n' % (str(k), str(v))) opt_file.write('-------------- End ----------------\n') if world_size > 1: dist.barrier() return self.opt123456789101112131415161718192021222324252627from options.base_options import BaseOptions
class TestOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) self.parser.add_argument('--batch_size', type=int, default=1, help='Batch size') self.parser.add_argument('--start_mov_len', type=int, default=10) self.parser.add_argument('--est_length', action="store_true", help="Whether to use sampled motion length") self.parser.add_argument('--num_layers', type=int, default=8, help='num_layers of transformer') self.parser.add_argument('--latent_dim', type=int, default=512, help='latent_dim of transformer') self.parser.add_argument('--diffusion_steps', type=int, default=1000, help='diffusion_steps of transformer') self.parser.add_argument('--no_clip', action='store_true', help='whether use clip pretrain') self.parser.add_argument('--no_eff', action='store_true', help='whether use efficient attention')
self.parser.add_argument('--repeat_times', type=int, default=3, help="Number of generation rounds for each text description") self.parser.add_argument('--split_file', type=str, default='test.txt') self.parser.add_argument('--text', type=str, default="", help='Text description for motion generation') self.parser.add_argument('--motion_length', type=int, default=0, help='Number of framese for motion generation') self.parser.add_argument('--text_file', type=str, default="", help='Path of text description for motion generation') self.parser.add_argument('--which_epoch', type=str, default="latest", help='Checkpoint that will be used') self.parser.add_argument('--result_path', type=str, default="./eval_results/", help='Path to save generation results') self.parser.add_argument('--num_results', type=int, default=40, help='Number of descriptions that will be used') self.parser.add_argument('--ext', type=str, default='default', help='Save file path extension')
self.is_train = False1234567891011121314151617181920212223242526272829303132import argparse
from options.base_options import BaseOptions
class TrainCompOptions(BaseOptions): def initialize(self): BaseOptions.initialize(self) self.parser.add_argument('--num_layers', type=int, default=8, help='num_layers of transformer') self.parser.add_argument('--latent_dim', type=int, default=512, help='latent_dim of transformer') self.parser.add_argument('--diffusion_steps', type=int, default=1000, help='diffusion_steps of transformer') self.parser.add_argument('--no_clip', action='store_true', help='whether use clip pretrain') self.parser.add_argument('--no_eff', action='store_true', help='whether use efficient attention')
self.parser.add_argument('--num_epochs', type=int, default=50, help='Number of epochs') self.parser.add_argument('--lr', type=float, default=2e-4, help='Learning rate') self.parser.add_argument('--batch_size', type=int, default=32, help='Batch size per GPU') self.parser.add_argument('--times', type=int, default=1, help='times of dataset')
self.parser.add_argument('--feat_bias', type=float, default=25, help='Scales for global motion features and foot contact')
self.parser.add_argument('--is_continue', action="store_true", help='Is this trail continued from previous trail?')
self.parser.add_argument('--log_every', type=int, default=50, help='Frequency of printing training progress (by iteration)') self.parser.add_argument('--save_every_e', type=int, default=5, help='Frequency of saving models (by epoch)') self.parser.add_argument('--eval_every_e', type=int, default=5, help='Frequency of animation results (by epoch)') self.parser.add_argument('--save_latest', type=int, default=500, help='Frequency of saving models (by iteration)') self.parser.add_argument('--use_wandb', action='store_true', help='whether to log with wandb') self.parser.add_argument('--wandb_user', type=str, default='text2motion', help='wandb user name') self.parser.add_argument('--experiment_name', type=str, default='motiondiffuse', help='experiment name') self.parser.add_argument('--seed', type=int, default=0, help='random seed') self.is_train = True1234567891011scipysmplxopencv-pythontqdmmatplotlib==3.3.1spacypyglet==1.5.0imageoiwandbpyrendergit+https://github.com/openai/CLIP.git12345678910111213141516171819202122232425262728293031323334353637from argparse import ArgumentParser, Namespace
GEN_NS = Namespace()GEN_NS
GEN_PARSER = ArgumentParser()GEN_PARSER.add_argument('--opt_path', type=str, help='Opt path')GEN_PARSER.add_argument('--text', type=str, default="", help='Text description for motion generation')GEN_PARSER.add_argument('--motion_length', type=int, default=60, help='Number of frames for motion generation')GEN_PARSER.add_argument('--result_path', type=str, default="test_sample.gif", help='Path to save generation result')GEN_PARSER.add_argument('--npy_path', type=str, default="", help='Path to save 3D keypoints sequence')GEN_PARSER.add_argument('--gpu_id', type=int, default=-1, help="which gpu to use")GEN_PARSER.add_argument('--seed', type=int, default=0, help="random seed")
GEN_PARSER.add_argument("-dm", "--display_mesh", action='store_true', required=False, default=False, help="Display mesh if this flag is present")# for now just specifies file name (with spaces) made by inferenceGEN_PARSER.add_argument("-p", "--prompt", type=str, required=False, default="", help="Prompt for inference display",)GEN_PARSER.add_argument("-sf", "--seq_file", type=str, required=False, default="", help="file for non-inference display",)# add model_path argGEN_PARSER.add_argument("-m", "--model_path", type=str, required=False, default="", help="Path to model directory e.g. ./checkpoints/grab/grab_baseline_dp_2gpu_8layers_1000",)GEN_PARSER.add_argument("-sg", "--save_gif", action='store_true', required=False, default=False, help="Saves gif")
def get_case_arguments(case_:str): """ Returns the parsed GEN_PARSER for the indicated case cases can be: 'train','evaluation' and 'generation' """ args = { 'generation': GEN_PARSER.parse_args("") }
if case_ in ('train','evaluation'): raise NotImplementedError(f'{case_} arguments have not been included yet, \ you can find them in their script file in tools/{case_}.py')
return args.get(case_, None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278from datetime import datetimeimport numpy as npimport torchfrom datasets import get_dataset_motion_loader, get_motion_loaderfrom models import MotionTransformerfrom utils.get_opt import get_optfrom utils.metrics import *from datasets import EvaluatorModelWrapperfrom collections import OrderedDictfrom utils.plot_script import *from utils import paramUtilfrom utils.utils import *from trainers import DDPMTrainer
from os.path import join as pjoinimport sys
def build_models(opt, dim_pose): encoder = MotionTransformer( input_feats=dim_pose, num_frames=opt.max_motion_length, num_layers=opt.num_layers, latent_dim=opt.latent_dim, no_clip=opt.no_clip, no_eff=opt.no_eff) return encoder
torch.multiprocessing.set_sharing_strategy('file_system')
def evaluate_matching_score(motion_loaders, file): match_score_dict = OrderedDict({}) R_precision_dict = OrderedDict({}) activation_dict = OrderedDict({}) # print(motion_loaders.keys()) print('========== Evaluating Matching Score ==========') for motion_loader_name, motion_loader in motion_loaders.items(): all_motion_embeddings = [] score_list = [] all_size = 0 matching_score_sum = 0 top_k_count = 0 # print(motion_loader_name) with torch.no_grad(): for idx, batch in enumerate(motion_loader): word_embeddings, pos_one_hots, _, sent_lens, motions, m_lens, _ = batch text_embeddings, motion_embeddings = eval_wrapper.get_co_embeddings( word_embs=word_embeddings, pos_ohot=pos_one_hots, cap_lens=sent_lens, motions=motions, m_lens=m_lens ) dist_mat = euclidean_distance_matrix(text_embeddings.cpu().numpy(), motion_embeddings.cpu().numpy()) matching_score_sum += dist_mat.trace()
argsmax = np.argsort(dist_mat, axis=1) top_k_mat = calculate_top_k(argsmax, top_k=3) top_k_count += top_k_mat.sum(axis=0)
all_size += text_embeddings.shape[0]
all_motion_embeddings.append(motion_embeddings.cpu().numpy())
all_motion_embeddings = np.concatenate(all_motion_embeddings, axis=0) matching_score = matching_score_sum / all_size R_precision = top_k_count / all_size match_score_dict[motion_loader_name] = matching_score R_precision_dict[motion_loader_name] = R_precision activation_dict[motion_loader_name] = all_motion_embeddings
print(f'---> [{motion_loader_name}] Matching Score: {matching_score:.4f}') print(f'---> [{motion_loader_name}] Matching Score: {matching_score:.4f}', file=file, flush=True)
line = f'---> [{motion_loader_name}] R_precision: ' for i in range(len(R_precision)): line += '(top %d): %.4f ' % (i+1, R_precision[i]) print(line) print(line, file=file, flush=True)
return match_score_dict, R_precision_dict, activation_dict
def evaluate_fid(groundtruth_loader, activation_dict, file): eval_dict = OrderedDict({}) gt_motion_embeddings = [] print('========== Evaluating FID ==========') with torch.no_grad(): for idx, batch in enumerate(groundtruth_loader): _, _, _, sent_lens, motions, m_lens, _ = batch motion_embeddings = eval_wrapper.get_motion_embeddings( motions=motions, m_lens=m_lens ) gt_motion_embeddings.append(motion_embeddings.cpu().numpy()) gt_motion_embeddings = np.concatenate(gt_motion_embeddings, axis=0) gt_mu, gt_cov = calculate_activation_statistics(gt_motion_embeddings)
# print(gt_mu) for model_name, motion_embeddings in activation_dict.items(): mu, cov = calculate_activation_statistics(motion_embeddings) # print(mu) fid = calculate_frechet_distance(gt_mu, gt_cov, mu, cov) print(f'---> [{model_name}] FID: {fid:.4f}') print(f'---> [{model_name}] FID: {fid:.4f}', file=file, flush=True) eval_dict[model_name] = fid return eval_dict
def evaluate_diversity(activation_dict, file): eval_dict = OrderedDict({}) print('========== Evaluating Diversity ==========') for model_name, motion_embeddings in activation_dict.items(): diversity = calculate_diversity(motion_embeddings, diversity_times) eval_dict[model_name] = diversity print(f'---> [{model_name}] Diversity: {diversity:.4f}') print(f'---> [{model_name}] Diversity: {diversity:.4f}', file=file, flush=True) return eval_dict
def evaluate_multimodality(mm_motion_loaders, file): eval_dict = OrderedDict({}) print('========== Evaluating MultiModality ==========') for model_name, mm_motion_loader in mm_motion_loaders.items(): mm_motion_embeddings = [] with torch.no_grad(): for idx, batch in enumerate(mm_motion_loader): # (1, mm_replications, dim_pos) motions, m_lens = batch motion_embedings = eval_wrapper.get_motion_embeddings(motions[0], m_lens[0]) mm_motion_embeddings.append(motion_embedings.unsqueeze(0)) if len(mm_motion_embeddings) == 0: multimodality = 0 else: mm_motion_embeddings = torch.cat(mm_motion_embeddings, dim=0).cpu().numpy() multimodality = calculate_multimodality(mm_motion_embeddings, mm_num_times) print(f'---> [{model_name}] Multimodality: {multimodality:.4f}') print(f'---> [{model_name}] Multimodality: {multimodality:.4f}', file=file, flush=True) eval_dict[model_name] = multimodality return eval_dict
def get_metric_statistics(values): mean = np.mean(values, axis=0) std = np.std(values, axis=0) conf_interval = 1.96 * std / np.sqrt(replication_times) return mean, conf_interval
def evaluation(log_file): with open(log_file, 'w') as f: all_metrics = OrderedDict({'Matching Score': OrderedDict({}), 'R_precision': OrderedDict({}), 'FID': OrderedDict({}), 'Diversity': OrderedDict({}), 'MultiModality': OrderedDict({})}) for replication in range(replication_times): motion_loaders = {} mm_motion_loaders = {} motion_loaders['ground truth'] = gt_loader for motion_loader_name, motion_loader_getter in eval_motion_loaders.items(): motion_loader, mm_motion_loader = motion_loader_getter() motion_loaders[motion_loader_name] = motion_loader mm_motion_loaders[motion_loader_name] = mm_motion_loader
print(f'==================== Replication {replication} ====================') print(f'==================== Replication {replication} ====================', file=f, flush=True) print(f'Time: {datetime.now()}') print(f'Time: {datetime.now()}', file=f, flush=True) mat_score_dict, R_precision_dict, acti_dict = evaluate_matching_score(motion_loaders, f)
print(f'Time: {datetime.now()}') print(f'Time: {datetime.now()}', file=f, flush=True) fid_score_dict = evaluate_fid(gt_loader, acti_dict, f)
print(f'Time: {datetime.now()}') print(f'Time: {datetime.now()}', file=f, flush=True) div_score_dict = evaluate_diversity(acti_dict, f)
print(f'Time: {datetime.now()}') print(f'Time: {datetime.now()}', file=f, flush=True) mm_score_dict = evaluate_multimodality(mm_motion_loaders, f)
print(f'!!! DONE !!!') print(f'!!! DONE !!!', file=f, flush=True)
for key, item in mat_score_dict.items(): if key not in all_metrics['Matching Score']: all_metrics['Matching Score'][key] = [item] else: all_metrics['Matching Score'][key] += [item]
for key, item in R_precision_dict.items(): if key not in all_metrics['R_precision']: all_metrics['R_precision'][key] = [item] else: all_metrics['R_precision'][key] += [item]
for key, item in fid_score_dict.items(): if key not in all_metrics['FID']: all_metrics['FID'][key] = [item] else: all_metrics['FID'][key] += [item]
for key, item in div_score_dict.items(): if key not in all_metrics['Diversity']: all_metrics['Diversity'][key] = [item] else: all_metrics['Diversity'][key] += [item]
for key, item in mm_score_dict.items(): if key not in all_metrics['MultiModality']: all_metrics['MultiModality'][key] = [item] else: all_metrics['MultiModality'][key] += [item]
# print(all_metrics['Diversity']) for metric_name, metric_dict in all_metrics.items(): print('========== %s Summary ==========' % metric_name) print('========== %s Summary ==========' % metric_name, file=f, flush=True)
for model_name, values in metric_dict.items(): # print(metric_name, model_name) mean, conf_interval = get_metric_statistics(np.array(values)) # print(mean, mean.dtype) if isinstance(mean, np.float64) or isinstance(mean, np.float32): print(f'---> [{model_name}] Mean: {mean:.4f} CInterval: {conf_interval:.4f}') print(f'---> [{model_name}] Mean: {mean:.4f} CInterval: {conf_interval:.4f}', file=f, flush=True) elif isinstance(mean, np.ndarray): line = f'---> [{model_name}]' for i in range(len(mean)): line += '(top %d) Mean: %.4f CInt: %.4f;' % (i+1, mean[i], conf_interval[i]) print(line) print(line, file=f, flush=True)
if __name__ == '__main__': mm_num_samples = 100 mm_num_repeats = 30 mm_num_times = 10
diversity_times = 300 replication_times = 1 batch_size = 32 opt_path = sys.argv[1] dataset_opt_path = opt_path
try: device_id = int(sys.argv[2]) except: device_id = 0 device = torch.device('cuda:%d' % device_id if torch.cuda.is_available() else 'cpu') torch.cuda.set_device(device_id)
gt_loader, gt_dataset = get_dataset_motion_loader(dataset_opt_path, batch_size, device) wrapper_opt = get_opt(dataset_opt_path, device) eval_wrapper = EvaluatorModelWrapper(wrapper_opt)
opt = get_opt(opt_path, device) encoder = build_models(opt, opt.dim_pose) trainer = DDPMTrainer(opt, encoder) eval_motion_loaders = { 'text2motion': lambda: get_motion_loader( opt, batch_size, trainer, gt_dataset, mm_num_samples, mm_num_repeats ) }
log_file = './t2m_evaluation.log' evaluation(log_file)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105import argparseimport osfrom os.path import join as pjoin
import numpy as npimport torchimport utils.paramUtil as paramUtilfrom models import MotionTransformerfrom torch.utils.data import DataLoaderfrom trainers import DDPMTrainerfrom utils.get_opt import get_optfrom utils.motion_process import recover_from_ricfrom utils.plot_script import *from utils.utils import *from utils.word_vectorizer import POS_enumerator
def plot_t2m(data, result_path, npy_path, caption, joints_n): joint = recover_from_ric(torch.from_numpy(data).float(), joints_n).numpy()
def get_numpy_file_path(prompt, epoch, n_frames): # e.g. "airplane_fly_1_1000_60f.npy" prompt_no_spaces = prompt.replace(' ', '_') return f"{prompt_no_spaces}_{epoch}_{n_frames}f"
def get_wordvec_model(opt): encoder = MotionTransformer( input_feats=opt.dim_pose, num_frames=opt.max_motion_length, num_layers=opt.num_layers, latent_dim=opt.latent_dim, no_clip=opt.no_clip, no_eff=opt.no_eff) return encoder
if __name__ == '__main__': print("inferencemake started") parser = argparse.ArgumentParser() parser.add_argument('--opt_path', type=str, help='Opt path') parser.add_argument('--text', type=str, default="", help='Text description for motion generation') parser.add_argument('--motion_length', type=int, default=60, help='Number of frames for motion generation') parser.add_argument('--result_path', type=str, default="test_sample.gif", help='Path to save generation result') parser.add_argument('--npy_path', type=str, default="", help='Path to save 3D keypoints sequence') parser.add_argument('--gpu_id', type=int, default=-1, help="which gpu to use") parser.add_argument('--seed', type=int, default=0, help="random seed") # add which_epoch parser.add_argument('--which_epoch', type=str, default="latest", help="which epoch to load") args = parser.parse_args() set_random_seed(args.seed) print(f"set random seed to {args.seed}") device = torch.device('cuda:%d' % args.gpu_id if args.gpu_id != -1 else 'cpu') opt = get_opt(args.opt_path, device) opt.do_denoise = True opt.which_epoch = args.which_epoch
# TODO (elmc): re-enable this # assert opt.dataset_name == "t2m" # assert args.motion_length <= 196 # opt.data_root = './dataset/HumanML3D' opt.data_root = './data/GRAB' # opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs') opt.text_dir = pjoin(opt.data_root, 'texts') # TODO (elmc): re-enable this # opt.joints_num = 22 # opt.dim_pose = 263 opt.dim_pose = 212 dim_word = 300 dim_pos_ohot = len(POS_enumerator) # TODO (elmc): re-enable this # num_classes = 200 // opt.unit_length
mean = np.load(pjoin(opt.meta_dir, 'mean.npy')) std = np.load(pjoin(opt.meta_dir, 'std.npy'))
print("Loading word vectorizer...") encoder = get_wordvec_model(opt).to(device) print("Loading model...") trainer = DDPMTrainer(opt, encoder) trainer.load(pjoin(opt.model_dir, opt.which_epoch + '.tar'))
trainer.eval_mode() trainer.to(opt.device)
result_dict = {} with torch.no_grad(): if args.motion_length != -1: caption = [args.text] file_name = f"{opt.which_epoch}_{args.motion_length}f.npy" m_lens = torch.LongTensor([args.motion_length]).to(device) pred_motions = trainer.generate(caption, m_lens, opt.dim_pose) motion = pred_motions[0].cpu().numpy() motion = motion * std + mean title = args.text + " #%d" % motion.shape[0] print(f"trying to plot {title}") # write motion to numpy file if not os.path.exists(args.npy_path): os.makedirs(args.npy_path) full_npy_path = f"{args.npy_path}/{get_numpy_file_path(caption[0], opt.which_epoch, args.motion_length)}.npy" with open(full_npy_path, 'wb') as f: print(f"saving output to {full_npy_path}") np.save(f, motion)
# plot_t2m(motion, args.result_path, args.npy_path, title)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134import os# print cwdimport sysfrom os.path import join as pjoin
sys.path.append(os.getcwd())import torchimport torch.distributed as distimport utils.paramUtil as paramUtilimport wandbfrom datasets import Text2MotionDatasetfrom mmcv.parallel import MMDataParallel, MMDistributedDataParallelfrom mmcv.runner import get_dist_info, init_distfrom models import MotionTransformerfrom options.train_options import TrainCompOptionsfrom trainers import DDPMTrainerfrom utils.plot_script import *from utils.utils import *
def build_models(opt, dim_pose): encoder = MotionTransformer( input_feats=dim_pose, num_frames=opt.max_motion_length, num_layers=opt.num_layers, latent_dim=opt.latent_dim, no_clip=opt.no_clip, no_eff=opt.no_eff) return encoder
if __name__ == '__main__':
parser = TrainCompOptions() opt = parser.parse() rank, world_size = get_dist_info()
print(f"setting random seed to {opt.seed}") set_random_seed(opt.seed) opt.device = torch.device("cuda") torch.autograd.set_detect_anomaly(True) print(f"device id: {torch.cuda.current_device()}") print(f"selected device ids: {opt.gpu_id}") opt.save_root = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.name) opt.model_dir = pjoin(opt.save_root, 'model') opt.meta_dir = pjoin(opt.save_root, 'meta') opt.noise_dir = pjoin(opt.save_root, 'noise')
if rank == 0: os.makedirs(opt.model_dir, exist_ok=True) os.makedirs(opt.meta_dir, exist_ok=True) os.makedirs(opt.noise_dir, exist_ok=True) if world_size > 1: dist.barrier() if opt.use_wandb: wandb_id = wandb.util.generate_id() wandb.init( project="text2motion", name=f"{opt.experiment_name}", entity=opt.wandb_user, # notes=opt.EXPERIMENT_NOTE, config=opt, id=wandb_id, resume="allow", # monitor_gym=True, sync_tensorboard=True, ) # opt.wandb = wandb if opt.dataset_name == 't2m': opt.data_root = './data/HumanML3D' opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs') opt.text_dir = pjoin(opt.data_root, 'texts') opt.joints_num = 22 radius = 4 fps = 20 opt.max_motion_length = 196 dim_pose = 263 kinematic_chain = paramUtil.t2m_kinematic_chain elif opt.dataset_name == 'grab': opt.data_root = './data/GRAB' opt.motion_dir = pjoin(opt.data_root, 'joints') opt.text_dir = pjoin(opt.data_root, 'texts') opt.face_text_dir = pjoin(opt.data_root, 'face_texts') opt.joints_num = 72 # TODO (elmc): verify this BUT ALSO I'M NOT USING IT FOR NOW! # radius = 4 # TODO (elmc): verify this, think it's only for visualization purposes # fps = 20 # TODO (elmc): verify this, also for visualization I think dim_pose = 212 # drop betas (body shape) and face-shape from Motion data (via to_smplx_params & smplx_dict_to_array method) opt.dim_pose = dim_pose opt.max_motion_length = 196 # TODO (elmc): verify this; do this dynamically..?? # TODO (elmc): verify what this does and if we can use the t2m one # NOTE: think, again, it's only for visualization # kinematic_chain = paramUtil.t2m_kinematic_chain # kinematic_chain = paramUtil.grab_kinematic_chain print(f"loading data root: {opt.data_root}") # print(f"kinematic chain: {kinematic_chain}") elif opt.dataset_name == 'kit': opt.data_root = './data/KIT-ML' opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs') opt.text_dir = pjoin(opt.data_root, 'texts') opt.joints_num = 21 radius = 240 * 8 fps = 12.5 dim_pose = 251 opt.max_motion_length = 196 kinematic_chain = paramUtil.kit_kinematic_chain
else: raise KeyError('Dataset Does Not Exist')
# TODO (elmc): check dim_word and add back in??? # dim_word = 300 mean = np.load(pjoin(opt.data_root, 'Mean.npy')) std = np.load(pjoin(opt.data_root, 'Std.npy'))
train_split_file = pjoin(opt.data_root, 'train.txt') print(f"cwd is {os.getcwd()}") print(f"train_split_file: {train_split_file}") encoder = build_models(opt, dim_pose) if world_size > 1: encoder = MMDistributedDataParallel( encoder.cuda(), device_ids=[torch.cuda.current_device()], broadcast_buffers=False, find_unused_parameters=True) elif opt.data_parallel: encoder = MMDataParallel( encoder.cuda(opt.gpu_id[0]), device_ids=opt.gpu_id) else: encoder = encoder.cuda()
trainer = DDPMTrainer(opt, encoder) train_dataset = Text2MotionDataset(opt, mean, std, train_split_file, opt.times) print(f"loaded data, now training") trainer.train(train_dataset)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import osimport refrom argparse import Namespacefrom os.path import join as pjoin
from utils.word_vectorizer import POS_enumerator
def is_float(numStr): flag = False numStr = str(numStr).strip().lstrip('-').lstrip('+') try: reg = re.compile(r'^[-+]?[0-9]+\.[0-9]+$') res = reg.match(str(numStr)) if res: flag = True except Exception as ex: print("is_float() - error: " + str(ex)) return flag
def is_number(numStr): flag = False numStr = str(numStr).strip().lstrip('-').lstrip('+') if str(numStr).isdigit(): flag = True return flag
def get_opt(opt_path, device): opt = Namespace() opt_dict = vars(opt)
skip = ('-------------- End ----------------', '------------ Options -------------', '\n') print('Reading', opt_path) with open(opt_path) as f: for line in f: if line.strip() not in skip: # print(line.strip()) key, value = line.strip().split(': ') if value in ('True', 'False'): opt_dict[key] = True if value == 'True' else False elif is_float(value): opt_dict[key] = float(value) elif is_number(value): opt_dict[key] = int(value) else: opt_dict[key] = str(value)
# opt_dict['which_epoch'] = 'latest' if 'num_layers' not in opt_dict: opt_dict['num_layers'] = 8 if 'latent_dim' not in opt_dict: opt_dict['latent_dim'] = 512 if 'diffusion_steps' not in opt_dict: opt_dict['diffusion_steps'] = 1000 if 'no_clip' not in opt_dict: opt_dict['no_clip'] = False if 'no_eff' not in opt_dict: opt_dict['no_eff'] = False
opt.save_root = pjoin(opt.checkpoints_dir, opt.dataset_name, opt.name) opt.model_dir = pjoin(opt.save_root, 'model') opt.meta_dir = pjoin(opt.save_root, 'meta')
if opt.dataset_name == 't2m': opt.data_root = './data/HumanML3D' opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs') opt.text_dir = pjoin(opt.data_root, 'texts') opt.joints_num = 22 opt.dim_pose = 263 opt.max_motion_length = 196 elif opt.dataset_name == 'kit': opt.data_root = './data/KIT-ML' opt.motion_dir = pjoin(opt.data_root, 'new_joint_vecs') opt.text_dir = pjoin(opt.data_root, 'texts') opt.joints_num = 21 opt.dim_pose = 251 opt.max_motion_length = 196 elif opt.dataset_name == 'grab': opt.data_root = './data/GRAB' opt.motion_dir = pjoin(opt.data_root, 'joints') opt.text_dir = pjoin(opt.data_root, 'texts') # opt.joints_num = 72 # TODO (elmc): verify this BUT ALSO I'M NOT USING IT FOR NOW! opt.dim_pose = 212 # drop betas (body shape) and face-shape from Motion data (via to_smplx_params & smplx_dict_to_array method) # TOOD (elmc): verify this opt.max_motion_length = 196 else: raise KeyError('Dataset not recognized')
# TODO (elmc): is dim_word ever actually used? # opt.dim_word = 300 # TODO (elmc): what is num classes for GRAB? # opt.num_classes = 200 // opt.unit_length opt.dim_pos_ohot = len(POS_enumerator) opt.is_train = False opt.is_continue = False opt.device = device
return opt123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146import numpy as npfrom scipy import linalg
# (X - X_train)*(X - X_train) = -2X*X_train + X*X + X_train*X_traindef euclidean_distance_matrix(matrix1, matrix2): """ Params: -- matrix1: N1 x D -- matrix2: N2 x D Returns: -- dist: N1 x N2 dist[i, j] == distance(matrix1[i], matrix2[j]) """ assert matrix1.shape[1] == matrix2.shape[1] d1 = -2 * np.dot(matrix1, matrix2.T) # shape (num_test, num_train) d2 = np.sum(np.square(matrix1), axis=1, keepdims=True) # shape (num_test, 1) d3 = np.sum(np.square(matrix2), axis=1) # shape (num_train, ) dists = np.sqrt(d1 + d2 + d3) # broadcasting return dists
def calculate_top_k(mat, top_k): size = mat.shape[0] gt_mat = np.expand_dims(np.arange(size), 1).repeat(size, 1) bool_mat = (mat == gt_mat) correct_vec = False top_k_list = [] for i in range(top_k):# print(correct_vec, bool_mat[:, i]) correct_vec = (correct_vec | bool_mat[:, i]) # print(correct_vec) top_k_list.append(correct_vec[:, None]) top_k_mat = np.concatenate(top_k_list, axis=1) return top_k_mat
def calculate_R_precision(embedding1, embedding2, top_k, sum_all=False): dist_mat = euclidean_distance_matrix(embedding1, embedding2) argmax = np.argsort(dist_mat, axis=1) top_k_mat = calculate_top_k(argmax, top_k) if sum_all: return top_k_mat.sum(axis=0) else: return top_k_mat
def calculate_matching_score(embedding1, embedding2, sum_all=False): assert len(embedding1.shape) == 2 assert embedding1.shape[0] == embedding2.shape[0] assert embedding1.shape[1] == embedding2.shape[1]
dist = linalg.norm(embedding1 - embedding2, axis=1) if sum_all: return dist.sum(axis=0) else: return dist
def calculate_activation_statistics(activations): """ Params: -- activation: num_samples x dim_feat Returns: -- mu: dim_feat -- sigma: dim_feat x dim_feat """ mu = np.mean(activations, axis=0) cov = np.cov(activations, rowvar=False) return mu, cov
def calculate_diversity(activation, diversity_times): assert len(activation.shape) == 2 assert activation.shape[0] > diversity_times num_samples = activation.shape[0]
first_indices = np.random.choice(num_samples, diversity_times, replace=False) second_indices = np.random.choice(num_samples, diversity_times, replace=False) dist = linalg.norm(activation[first_indices] - activation[second_indices], axis=1) return dist.mean()
def calculate_multimodality(activation, multimodality_times): assert len(activation.shape) == 3 assert activation.shape[1] > multimodality_times num_per_sent = activation.shape[1]
first_dices = np.random.choice(num_per_sent, multimodality_times, replace=False) second_dices = np.random.choice(num_per_sent, multimodality_times, replace=False) dist = linalg.norm(activation[:, first_dices] - activation[:, second_dices], axis=2) return dist.mean()
def calculate_frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6): """Numpy implementation of the Frechet Distance. The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1) and X_2 ~ N(mu_2, C_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)). Stable version by Dougal J. Sutherland. Params: -- mu1 : Numpy array containing the activations of a layer of the inception net (like returned by the function 'get_predictions') for generated samples. -- mu2 : The sample mean over activations, precalculated on an representative data set. -- sigma1: The covariance matrix over activations for generated samples. -- sigma2: The covariance matrix over activations, precalculated on an representative data set. Returns: -- : The Frechet Distance. """
mu1 = np.atleast_1d(mu1) mu2 = np.atleast_1d(mu2)
sigma1 = np.atleast_2d(sigma1) sigma2 = np.atleast_2d(sigma2)
assert mu1.shape == mu2.shape, \ 'Training and test mean vectors have different lengths' assert sigma1.shape == sigma2.shape, \ 'Training and test covariances have different dimensions'
diff = mu1 - mu2
# Product might be almost singular covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False) if not np.isfinite(covmean).all(): msg = ('fid calculation produces singular product; ' 'adding %s to diagonal of cov estimates') % eps print(msg) offset = np.eye(sigma1.shape[0]) * eps covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
# Numerical error might give slight imaginary component if np.iscomplexobj(covmean): if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3): m = np.max(np.abs(covmean.imag)) raise ValueError('Imaginary component {}'.format(m)) covmean = covmean.real
tr_covmean = np.trace(covmean)
return (diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515from os.path import join as pjoin
import numpy as npimport osfrom utils.quaternion import *from utils.skeleton import Skeletonfrom utils.paramUtil import *
import torchfrom tqdm import tqdm
# positions (batch, joint_num, 3)def uniform_skeleton(positions, target_offset): src_skel = Skeleton(n_raw_offsets, kinematic_chain, 'cpu') src_offset = src_skel.get_offsets_joints(torch.from_numpy(positions[0])) src_offset = src_offset.numpy() tgt_offset = target_offset.numpy() # print(src_offset) # print(tgt_offset) '''Calculate Scale Ratio as the ratio of legs''' src_leg_len = np.abs(src_offset[l_idx1]).max() + np.abs(src_offset[l_idx2]).max() tgt_leg_len = np.abs(tgt_offset[l_idx1]).max() + np.abs(tgt_offset[l_idx2]).max()
scale_rt = tgt_leg_len / src_leg_len # print(scale_rt) src_root_pos = positions[:, 0] tgt_root_pos = src_root_pos * scale_rt
'''Inverse Kinematics''' quat_params = src_skel.inverse_kinematics_np(positions, face_joint_indx) # print(quat_params.shape)
'''Forward Kinematics''' src_skel.set_offset(target_offset) new_joints = src_skel.forward_kinematics_np(quat_params, tgt_root_pos) return new_joints
def extract_features(positions, feet_thre, n_raw_offsets, kinematic_chain, face_joint_indx, fid_r, fid_l): global_positions = positions.copy() """ Get Foot Contacts """
def foot_detect(positions, thres): velfactor, heightfactor = np.array([thres, thres]), np.array([3.0, 2.0])
feet_l_x = (positions[1:, fid_l, 0] - positions[:-1, fid_l, 0]) ** 2 feet_l_y = (positions[1:, fid_l, 1] - positions[:-1, fid_l, 1]) ** 2 feet_l_z = (positions[1:, fid_l, 2] - positions[:-1, fid_l, 2]) ** 2 # feet_l_h = positions[:-1,fid_l,1] # feet_l = (((feet_l_x + feet_l_y + feet_l_z) < velfactor) & (feet_l_h < heightfactor)).astype(np.float) feet_l = ((feet_l_x + feet_l_y + feet_l_z) < velfactor).astype(np.float)
feet_r_x = (positions[1:, fid_r, 0] - positions[:-1, fid_r, 0]) ** 2 feet_r_y = (positions[1:, fid_r, 1] - positions[:-1, fid_r, 1]) ** 2 feet_r_z = (positions[1:, fid_r, 2] - positions[:-1, fid_r, 2]) ** 2 # feet_r_h = positions[:-1,fid_r,1] # feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor) & (feet_r_h < heightfactor)).astype(np.float) feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor)).astype(np.float) return feet_l, feet_r
# feet_l, feet_r = foot_detect(positions, feet_thre) # feet_l, feet_r = foot_detect(positions, 0.002)
'''Quaternion and Cartesian representation''' r_rot = None
def get_rifke(positions): '''Local pose''' positions[..., 0] -= positions[:, 0:1, 0] positions[..., 2] -= positions[:, 0:1, 2] '''All pose face Z+''' positions = qrot_np(np.repeat(r_rot[:, None], positions.shape[1], axis=1), positions) return positions
def get_quaternion(positions): skel = Skeleton(n_raw_offsets, kinematic_chain, "cpu") # (seq_len, joints_num, 4) quat_params = skel.inverse_kinematics_np(positions, face_joint_indx, smooth_forward=False)
'''Fix Quaternion Discontinuity''' quat_params = qfix(quat_params) # (seq_len, 4) r_rot = quat_params[:, 0].copy() # print(r_rot[0]) '''Root Linear Velocity''' # (seq_len - 1, 3) velocity = (positions[1:, 0] - positions[:-1, 0]).copy() # print(r_rot.shape, velocity.shape) velocity = qrot_np(r_rot[1:], velocity) '''Root Angular Velocity''' # (seq_len - 1, 4) r_velocity = qmul_np(r_rot[1:], qinv_np(r_rot[:-1])) quat_params[1:, 0] = r_velocity # (seq_len, joints_num, 4) return quat_params, r_velocity, velocity, r_rot
def get_cont6d_params(positions): skel = Skeleton(n_raw_offsets, kinematic_chain, "cpu") # (seq_len, joints_num, 4) quat_params = skel.inverse_kinematics_np(positions, face_joint_indx, smooth_forward=True)
'''Quaternion to continuous 6D''' cont_6d_params = quaternion_to_cont6d_np(quat_params) # (seq_len, 4) r_rot = quat_params[:, 0].copy() # print(r_rot[0]) '''Root Linear Velocity''' # (seq_len - 1, 3) velocity = (positions[1:, 0] - positions[:-1, 0]).copy() # print(r_rot.shape, velocity.shape) velocity = qrot_np(r_rot[1:], velocity) '''Root Angular Velocity''' # (seq_len - 1, 4) r_velocity = qmul_np(r_rot[1:], qinv_np(r_rot[:-1])) # (seq_len, joints_num, 4) return cont_6d_params, r_velocity, velocity, r_rot
cont_6d_params, r_velocity, velocity, r_rot = get_cont6d_params(positions) positions = get_rifke(positions)
# trejec = np.cumsum(np.concatenate([np.array([[0, 0, 0]]), velocity], axis=0), axis=0) # r_rotations, r_pos = recover_ric_glo_np(r_velocity, velocity[:, [0, 2]])
# plt.plot(positions_b[:, 0, 0], positions_b[:, 0, 2], marker='*') # plt.plot(ground_positions[:, 0, 0], ground_positions[:, 0, 2], marker='o', color='r') # plt.plot(trejec[:, 0], trejec[:, 2], marker='^', color='g') # plt.plot(r_pos[:, 0], r_pos[:, 2], marker='s', color='y') # plt.xlabel('x') # plt.ylabel('z') # plt.axis('equal') # plt.show()
'''Root height''' root_y = positions[:, 0, 1:2]
'''Root rotation and linear velocity''' # (seq_len-1, 1) rotation velocity along y-axis # (seq_len-1, 2) linear velovity on xz plane r_velocity = np.arcsin(r_velocity[:, 2:3]) l_velocity = velocity[:, [0, 2]] # print(r_velocity.shape, l_velocity.shape, root_y.shape) root_data = np.concatenate([r_velocity, l_velocity, root_y[:-1]], axis=-1)
'''Get Joint Rotation Representation''' # (seq_len, (joints_num-1) *6) quaternion for skeleton joints rot_data = cont_6d_params[:, 1:].reshape(len(cont_6d_params), -1)
'''Get Joint Rotation Invariant Position Represention''' # (seq_len, (joints_num-1)*3) local joint position ric_data = positions[:, 1:].reshape(len(positions), -1)
'''Get Joint Velocity Representation''' # (seq_len-1, joints_num*3) local_vel = qrot_np(np.repeat(r_rot[:-1, None], global_positions.shape[1], axis=1), global_positions[1:] - global_positions[:-1]) local_vel = local_vel.reshape(len(local_vel), -1)
data = root_data data = np.concatenate([data, ric_data[:-1]], axis=-1) data = np.concatenate([data, rot_data[:-1]], axis=-1) # print(data.shape, local_vel.shape) data = np.concatenate([data, local_vel], axis=-1) data = np.concatenate([data, feet_l, feet_r], axis=-1)
return data
def process_file(positions, feet_thre): # (seq_len, joints_num, 3) # '''Down Sample''' # positions = positions[::ds_num]
'''Uniform Skeleton''' positions = uniform_skeleton(positions, tgt_offsets)
'''Put on Floor''' floor_height = positions.min(axis=0).min(axis=0)[1] positions[:, :, 1] -= floor_height # print(floor_height)
# plot_3d_motion("./positions_1.mp4", kinematic_chain, positions, 'title', fps=20)
'''XZ at origin''' root_pos_init = positions[0] root_pose_init_xz = root_pos_init[0] * np.array([1, 0, 1]) positions = positions - root_pose_init_xz
# '''Move the first pose to origin ''' # root_pos_init = positions[0] # positions = positions - root_pos_init[0]
'''All initially face Z+''' r_hip, l_hip, sdr_r, sdr_l = face_joint_indx across1 = root_pos_init[r_hip] - root_pos_init[l_hip] across2 = root_pos_init[sdr_r] - root_pos_init[sdr_l] across = across1 + across2 across = across / np.sqrt((across ** 2).sum(axis=-1))[..., np.newaxis]
# forward (3,), rotate around y-axis forward_init = np.cross(np.array([[0, 1, 0]]), across, axis=-1) # forward (3,) forward_init = forward_init / np.sqrt((forward_init ** 2).sum(axis=-1))[..., np.newaxis]
# print(forward_init)
target = np.array([[0, 0, 1]]) root_quat_init = qbetween_np(forward_init, target) root_quat_init = np.ones(positions.shape[:-1] + (4,)) * root_quat_init
positions_b = positions.copy()
positions = qrot_np(root_quat_init, positions)
# plot_3d_motion("./positions_2.mp4", kinematic_chain, positions, 'title', fps=20)
'''New ground truth positions''' global_positions = positions.copy()
# plt.plot(positions_b[:, 0, 0], positions_b[:, 0, 2], marker='*') # plt.plot(positions[:, 0, 0], positions[:, 0, 2], marker='o', color='r') # plt.xlabel('x') # plt.ylabel('z') # plt.axis('equal') # plt.show()
""" Get Foot Contacts """
def foot_detect(positions, thres): velfactor, heightfactor = np.array([thres, thres]), np.array([3.0, 2.0])
feet_l_x = (positions[1:, fid_l, 0] - positions[:-1, fid_l, 0]) ** 2 feet_l_y = (positions[1:, fid_l, 1] - positions[:-1, fid_l, 1]) ** 2 feet_l_z = (positions[1:, fid_l, 2] - positions[:-1, fid_l, 2]) ** 2 # feet_l_h = positions[:-1,fid_l,1] # feet_l = (((feet_l_x + feet_l_y + feet_l_z) < velfactor) & (feet_l_h < heightfactor)).astype(np.float) feet_l = ((feet_l_x + feet_l_y + feet_l_z) < velfactor).astype(np.float)
feet_r_x = (positions[1:, fid_r, 0] - positions[:-1, fid_r, 0]) ** 2 feet_r_y = (positions[1:, fid_r, 1] - positions[:-1, fid_r, 1]) ** 2 feet_r_z = (positions[1:, fid_r, 2] - positions[:-1, fid_r, 2]) ** 2 # feet_r_h = positions[:-1,fid_r,1] # feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor) & (feet_r_h < heightfactor)).astype(np.float) feet_r = (((feet_r_x + feet_r_y + feet_r_z) < velfactor)).astype(np.float) return feet_l, feet_r # feet_l, feet_r = foot_detect(positions, feet_thre) # feet_l, feet_r = foot_detect(positions, 0.002)
'''Quaternion and Cartesian representation''' r_rot = None
def get_rifke(positions): '''Local pose''' positions[..., 0] -= positions[:, 0:1, 0] positions[..., 2] -= positions[:, 0:1, 2] '''All pose face Z+''' positions = qrot_np(np.repeat(r_rot[:, None], positions.shape[1], axis=1), positions) return positions
def get_quaternion(positions): skel = Skeleton(n_raw_offsets, kinematic_chain, "cpu") # (seq_len, joints_num, 4) quat_params = skel.inverse_kinematics_np(positions, face_joint_indx, smooth_forward=False)
'''Fix Quaternion Discontinuity''' quat_params = qfix(quat_params) # (seq_len, 4) r_rot = quat_params[:, 0].copy() # print(r_rot[0]) '''Root Linear Velocity''' # (seq_len - 1, 3) velocity = (positions[1:, 0] - positions[:-1, 0]).copy() # print(r_rot.shape, velocity.shape) velocity = qrot_np(r_rot[1:], velocity) '''Root Angular Velocity''' # (seq_len - 1, 4) r_velocity = qmul_np(r_rot[1:], qinv_np(r_rot[:-1])) quat_params[1:, 0] = r_velocity # (seq_len, joints_num, 4) return quat_params, r_velocity, velocity, r_rot
def get_cont6d_params(positions): skel = Skeleton(n_raw_offsets, kinematic_chain, "cpu") # (seq_len, joints_num, 4) quat_params = skel.inverse_kinematics_np(positions, face_joint_indx, smooth_forward=True)
'''Quaternion to continuous 6D''' cont_6d_params = quaternion_to_cont6d_np(quat_params) # (seq_len, 4) r_rot = quat_params[:, 0].copy() # print(r_rot[0]) '''Root Linear Velocity''' # (seq_len - 1, 3) velocity = (positions[1:, 0] - positions[:-1, 0]).copy() # print(r_rot.shape, velocity.shape) velocity = qrot_np(r_rot[1:], velocity) '''Root Angular Velocity''' # (seq_len - 1, 4) r_velocity = qmul_np(r_rot[1:], qinv_np(r_rot[:-1])) # (seq_len, joints_num, 4) return cont_6d_params, r_velocity, velocity, r_rot
cont_6d_params, r_velocity, velocity, r_rot = get_cont6d_params(positions) positions = get_rifke(positions)
# trejec = np.cumsum(np.concatenate([np.array([[0, 0, 0]]), velocity], axis=0), axis=0) # r_rotations, r_pos = recover_ric_glo_np(r_velocity, velocity[:, [0, 2]])
# plt.plot(positions_b[:, 0, 0], positions_b[:, 0, 2], marker='*') # plt.plot(ground_positions[:, 0, 0], ground_positions[:, 0, 2], marker='o', color='r') # plt.plot(trejec[:, 0], trejec[:, 2], marker='^', color='g') # plt.plot(r_pos[:, 0], r_pos[:, 2], marker='s', color='y') # plt.xlabel('x') # plt.ylabel('z') # plt.axis('equal') # plt.show()
'''Root height''' root_y = positions[:, 0, 1:2]
'''Root rotation and linear velocity''' # (seq_len-1, 1) rotation velocity along y-axis # (seq_len-1, 2) linear velovity on xz plane r_velocity = np.arcsin(r_velocity[:, 2:3]) l_velocity = velocity[:, [0, 2]] # print(r_velocity.shape, l_velocity.shape, root_y.shape) root_data = np.concatenate([r_velocity, l_velocity, root_y[:-1]], axis=-1)
'''Get Joint Rotation Representation''' # (seq_len, (joints_num-1) *6) quaternion for skeleton joints rot_data = cont_6d_params[:, 1:].reshape(len(cont_6d_params), -1)
'''Get Joint Rotation Invariant Position Represention''' # (seq_len, (joints_num-1)*3) local joint position ric_data = positions[:, 1:].reshape(len(positions), -1)
'''Get Joint Velocity Representation''' # (seq_len-1, joints_num*3) local_vel = qrot_np(np.repeat(r_rot[:-1, None], global_positions.shape[1], axis=1), global_positions[1:] - global_positions[:-1]) local_vel = local_vel.reshape(len(local_vel), -1)
data = root_data data = np.concatenate([data, ric_data[:-1]], axis=-1) data = np.concatenate([data, rot_data[:-1]], axis=-1) # print(data.shape, local_vel.shape) data = np.concatenate([data, local_vel], axis=-1) data = np.concatenate([data, feet_l, feet_r], axis=-1)
return data, global_positions, positions, l_velocity
# Recover global angle and positions for rotation data# root_rot_velocity (B, seq_len, 1)# root_linear_velocity (B, seq_len, 2)# root_y (B, seq_len, 1)# ric_data (B, seq_len, (joint_num - 1)*3)# rot_data (B, seq_len, (joint_num - 1)*6)# local_velocity (B, seq_len, joint_num*3)# foot contact (B, seq_len, 4)def recover_root_rot_pos(data): rot_vel = data[..., 0] r_rot_ang = torch.zeros_like(rot_vel).to(data.device) '''Get Y-axis rotation from rotation velocity''' r_rot_ang[..., 1:] = rot_vel[..., :-1] r_rot_ang = torch.cumsum(r_rot_ang, dim=-1)
r_rot_quat = torch.zeros(data.shape[:-1] + (4,)).to(data.device) r_rot_quat[..., 0] = torch.cos(r_rot_ang) r_rot_quat[..., 2] = torch.sin(r_rot_ang)
r_pos = torch.zeros(data.shape[:-1] + (3,)).to(data.device) r_pos[..., 1:, [0, 2]] = data[..., :-1, 1:3] '''Add Y-axis rotation to root position''' r_pos = qrot(qinv(r_rot_quat), r_pos)
r_pos = torch.cumsum(r_pos, dim=-2)
r_pos[..., 1] = data[..., 3] return r_rot_quat, r_pos
def recover_from_rot(data, joints_num, skeleton): r_rot_quat, r_pos = recover_root_rot_pos(data)
r_rot_cont6d = quaternion_to_cont6d(r_rot_quat)
start_indx = 1 + 2 + 1 + (joints_num - 1) * 3 end_indx = start_indx + (joints_num - 1) * 6 cont6d_params = data[..., start_indx:end_indx] # print(r_rot_cont6d.shape, cont6d_params.shape, r_pos.shape) cont6d_params = torch.cat([r_rot_cont6d, cont6d_params], dim=-1) cont6d_params = cont6d_params.view(-1, joints_num, 6)
positions = skeleton.forward_kinematics_cont6d(cont6d_params, r_pos)
return positions
def recover_from_ric(data, joints_num): r_rot_quat, r_pos = recover_root_rot_pos(data) positions = data[..., 4:(joints_num - 1) * 3 + 4] positions = positions.view(positions.shape[:-1] + (-1, 3))
'''Add Y-axis rotation to local joints''' positions = qrot(qinv(r_rot_quat[..., None, :]).expand(positions.shape[:-1] + (4,)), positions)
'''Add root XZ to joints''' positions[..., 0] += r_pos[..., 0:1] positions[..., 2] += r_pos[..., 2:3]
'''Concate root and joints''' positions = torch.cat([r_pos.unsqueeze(-2), positions], dim=-2)
return positions'''For Text2Motion Dataset''''''if __name__ == "__main__": example_id = "000021" # Lower legs l_idx1, l_idx2 = 5, 8 # Right/Left foot fid_r, fid_l = [8, 11], [7, 10] # Face direction, r_hip, l_hip, sdr_r, sdr_l face_joint_indx = [2, 1, 17, 16] # l_hip, r_hip r_hip, l_hip = 2, 1 joints_num = 22 # ds_num = 8 data_dir = '../dataset/pose_data_raw/joints/' save_dir1 = '../dataset/pose_data_raw/new_joints/' save_dir2 = '../dataset/pose_data_raw/new_joint_vecs/'
n_raw_offsets = torch.from_numpy(t2m_raw_offsets) kinematic_chain = t2m_kinematic_chain
# Get offsets of target skeleton example_data = np.load(os.path.join(data_dir, example_id + '.npy')) example_data = example_data.reshape(len(example_data), -1, 3) example_data = torch.from_numpy(example_data) tgt_skel = Skeleton(n_raw_offsets, kinematic_chain, 'cpu') # (joints_num, 3) tgt_offsets = tgt_skel.get_offsets_joints(example_data[0]) # print(tgt_offsets)
source_list = os.listdir(data_dir) frame_num = 0 for source_file in tqdm(source_list): source_data = np.load(os.path.join(data_dir, source_file))[:, :joints_num] try: data, ground_positions, positions, l_velocity = process_file(source_data, 0.002) rec_ric_data = recover_from_ric(torch.from_numpy(data).unsqueeze(0).float(), joints_num) np.save(pjoin(save_dir1, source_file), rec_ric_data.squeeze().numpy()) np.save(pjoin(save_dir2, source_file), data) frame_num += data.shape[0] except Exception as e: print(source_file) print(e)
print('Total clips: %d, Frames: %d, Duration: %fm' % (len(source_list), frame_num, frame_num / 20 / 60))'''
if __name__ == "__main__": example_id = "03950_gt" # Lower legs l_idx1, l_idx2 = 17, 18 # Right/Left foot fid_r, fid_l = [14, 15], [19, 20] # Face direction, r_hip, l_hip, sdr_r, sdr_l face_joint_indx = [11, 16, 5, 8] # l_hip, r_hip r_hip, l_hip = 11, 16 joints_num = 21 # ds_num = 8 data_dir = '../dataset/kit_mocap_dataset/joints/' save_dir1 = '../dataset/kit_mocap_dataset/new_joints/' save_dir2 = '../dataset/kit_mocap_dataset/new_joint_vecs/'
n_raw_offsets = torch.from_numpy(kit_raw_offsets) kinematic_chain = kit_kinematic_chain
'''Get offsets of target skeleton''' example_data = np.load(os.path.join(data_dir, example_id + '.npy')) example_data = example_data.reshape(len(example_data), -1, 3) example_data = torch.from_numpy(example_data) tgt_skel = Skeleton(n_raw_offsets, kinematic_chain, 'cpu') # (joints_num, 3) tgt_offsets = tgt_skel.get_offsets_joints(example_data[0]) # print(tgt_offsets)
source_list = os.listdir(data_dir) frame_num = 0 '''Read source data''' for source_file in tqdm(source_list): source_data = np.load(os.path.join(data_dir, source_file))[:, :joints_num] try: name = ''.join(source_file[:-7].split('_')) + '.npy' data, ground_positions, positions, l_velocity = process_file(source_data, 0.05) rec_ric_data = recover_from_ric(torch.from_numpy(data).unsqueeze(0).float(), joints_num) if np.isnan(rec_ric_data.numpy()).any(): print(source_file) continue np.save(pjoin(save_dir1, name), rec_ric_data.squeeze().numpy()) np.save(pjoin(save_dir2, name), data) frame_num += data.shape[0] except Exception as e: print(source_file) print(e)
print('Total clips: %d, Frames: %d, Duration: %fm' % (len(source_list), frame_num, frame_num / 12.5 / 60))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import numpy as np
# Define a kinematic tree for the skeletal struturekit_kinematic_chain = [[0, 11, 12, 13, 14, 15], [0, 16, 17, 18, 19, 20], [0, 1, 2, 3, 4], [3, 5, 6, 7], [3, 8, 9, 10]]
kit_raw_offsets = np.array( [ [0, 0, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [0, 1, 0], [1, 0, 0], [0, -1, 0], [0, -1, 0], [-1, 0, 0], [0, -1, 0], [0, -1, 0], [1, 0, 0], [0, -1, 0], [0, -1, 0], [0, 0, 1], [0, 0, 1], [-1, 0, 0], [0, -1, 0], [0, -1, 0], [0, 0, 1], [0, 0, 1] ])
t2m_raw_offsets = np.array([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,-1,0], [0,-1,0], [0,1,0], [0,-1,0], [0,-1,0], [0,1,0], [0,0,1], [0,0,1], [0,1,0], [1,0,0], [-1,0,0], [0,0,1], [0,-1,0], [0,-1,0], [0,-1,0], [0,-1,0], [0,-1,0], [0,-1,0]])
t2m_kinematic_chain = [[0, 2, 5, 8, 11], [0, 1, 4, 7, 10], [0, 3, 6, 9, 12, 15], [9, 14, 17, 19, 21], [9, 13, 16, 18, 20]]t2m_left_hand_chain = [[20, 22, 23, 24], [20, 34, 35, 36], [20, 25, 26, 27], [20, 31, 32, 33], [20, 28, 29, 30]]t2m_right_hand_chain = [[21, 43, 44, 45], [21, 46, 47, 48], [21, 40, 41, 42], [21, 37, 38, 39], [21, 49, 50, 51]]
kit_tgt_skel_id = '03950'
t2m_tgt_skel_id = '000021'
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115import mathimport numpy as npimport matplotlibimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dfrom matplotlib.animation import FuncAnimation, FFMpegFileWriterfrom mpl_toolkits.mplot3d.art3d import Poly3DCollectionimport mpl_toolkits.mplot3d.axes3d as p3# import cv2
def list_cut_average(ll, intervals): if intervals == 1: return ll
bins = math.ceil(len(ll) * 1.0 / intervals) ll_new = [] for i in range(bins): l_low = intervals * i l_high = l_low + intervals l_high = l_high if l_high < len(ll) else len(ll) ll_new.append(np.mean(ll[l_low:l_high])) return ll_new
def plot_3d_motion(save_path, kinematic_tree, joints, title, figsize=(10, 10), fps=120, radius=4): matplotlib.use('Agg')
title_sp = title.split(' ') if len(title_sp) > 20: title = '\n'.join([' '.join(title_sp[:10]), ' '.join(title_sp[10:20]), ' '.join(title_sp[20:])]) elif len(title_sp) > 10: title = '\n'.join([' '.join(title_sp[:10]), ' '.join(title_sp[10:])])
def init(): ax.set_xlim3d([-radius / 4, radius / 4]) ax.set_ylim3d([0, radius / 2]) ax.set_zlim3d([0, radius / 2]) # print(title) fig.suptitle(title, fontsize=20) ax.grid(b=False)
def plot_xzPlane(minx, maxx, miny, minz, maxz): ## Plot a plane XZ verts = [ [minx, miny, minz], [minx, miny, maxz], [maxx, miny, maxz], [maxx, miny, minz] ] xz_plane = Poly3DCollection([verts]) xz_plane.set_facecolor((0.5, 0.5, 0.5, 0.5)) ax.add_collection3d(xz_plane)
# return ax
# (seq_len, joints_num, 3) data = joints.copy().reshape(len(joints), -1, 3) fig = plt.figure(figsize=figsize) ax = p3.Axes3D(fig) init() MINS = data.min(axis=0).min(axis=0) MAXS = data.max(axis=0).max(axis=0) colors = ['red', 'blue', 'black', 'red', 'blue', 'darkblue', 'darkblue', 'darkblue', 'darkblue', 'darkblue', 'darkred', 'darkred', 'darkred', 'darkred', 'darkred'] frame_number = data.shape[0] # print(data.shape)
height_offset = MINS[1] data[:, :, 1] -= height_offset trajec = data[:, 0, [0, 2]]
data[..., 0] -= data[:, 0:1, 0] data[..., 2] -= data[:, 0:1, 2]
# print(trajec.shape)
def update(index): # print(index) ax.lines = [] ax.collections = [] ax.view_init(elev=120, azim=-90) ax.dist = 7.5 # ax = plot_xzPlane(MINS[0] - trajec[index, 0], MAXS[0] - trajec[index, 0], 0, MINS[2] - trajec[index, 1], MAXS[2] - trajec[index, 1]) # ax.scatter(data[index, :22, 0], data[index, :22, 1], data[index, :22, 2], color='black', s=3)
if index > 1: ax.plot3D(trajec[:index, 0] - trajec[index, 0], np.zeros_like(trajec[:index, 0]), trajec[:index, 1] - trajec[index, 1], linewidth=1.0, color='blue') # ax = plot_xzPlane(ax, MINS[0], MAXS[0], 0, MINS[2], MAXS[2])
for i, (chain, color) in enumerate(zip(kinematic_tree, colors)): # print(color) if i < 5: linewidth = 4.0 else: linewidth = 2.0 ax.plot3D(data[index, chain, 0], data[index, chain, 1], data[index, chain, 2], linewidth=linewidth, color=color) # print(trajec[:index, 0].shape)
plt.axis('off') ax.set_xticklabels([]) ax.set_yticklabels([]) ax.set_zticklabels([])
ani = FuncAnimation(fig, update, frames=frame_number, interval=1000 / fps, repeat=False)
# writer = FFMpegFileWriter(fps=fps) ani.save(save_path, fps=fps) plt.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423# Copyright (c) 2018-present, Facebook, Inc.# All rights reserved.## This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.#
import torchimport numpy as np
_EPS4 = np.finfo(float).eps * 4.0
_FLOAT_EPS = np.finfo(float).eps
# PyTorch-backed implementationsdef qinv(q): assert q.shape[-1] == 4, 'q must be a tensor of shape (*, 4)' mask = torch.ones_like(q) mask[..., 1:] = -mask[..., 1:] return q * mask
def qinv_np(q): assert q.shape[-1] == 4, 'q must be a tensor of shape (*, 4)' return qinv(torch.from_numpy(q).float()).numpy()
def qnormalize(q): assert q.shape[-1] == 4, 'q must be a tensor of shape (*, 4)' return q / torch.norm(q, dim=-1, keepdim=True)
def qmul(q, r): """ Multiply quaternion(s) q with quaternion(s) r. Expects two equally-sized tensors of shape (*, 4), where * denotes any number of dimensions. Returns q*r as a tensor of shape (*, 4). """ assert q.shape[-1] == 4 assert r.shape[-1] == 4
original_shape = q.shape
# Compute outer product terms = torch.bmm(r.view(-1, 4, 1), q.view(-1, 1, 4))
w = terms[:, 0, 0] - terms[:, 1, 1] - terms[:, 2, 2] - terms[:, 3, 3] x = terms[:, 0, 1] + terms[:, 1, 0] - terms[:, 2, 3] + terms[:, 3, 2] y = terms[:, 0, 2] + terms[:, 1, 3] + terms[:, 2, 0] - terms[:, 3, 1] z = terms[:, 0, 3] - terms[:, 1, 2] + terms[:, 2, 1] + terms[:, 3, 0] return torch.stack((w, x, y, z), dim=1).view(original_shape)
def qrot(q, v): """ Rotate vector(s) v about the rotation described by quaternion(s) q. Expects a tensor of shape (*, 4) for q and a tensor of shape (*, 3) for v, where * denotes any number of dimensions. Returns a tensor of shape (*, 3). """ assert q.shape[-1] == 4 assert v.shape[-1] == 3 assert q.shape[:-1] == v.shape[:-1]
original_shape = list(v.shape) # print(q.shape) q = q.contiguous().view(-1, 4) v = v.contiguous().view(-1, 3)
qvec = q[:, 1:] uv = torch.cross(qvec, v, dim=1) uuv = torch.cross(qvec, uv, dim=1) return (v + 2 * (q[:, :1] * uv + uuv)).view(original_shape)
def qeuler(q, order, epsilon=0, deg=True): """ Convert quaternion(s) q to Euler angles. Expects a tensor of shape (*, 4), where * denotes any number of dimensions. Returns a tensor of shape (*, 3). """ assert q.shape[-1] == 4
original_shape = list(q.shape) original_shape[-1] = 3 q = q.view(-1, 4)
q0 = q[:, 0] q1 = q[:, 1] q2 = q[:, 2] q3 = q[:, 3]
if order == 'xyz': x = torch.atan2(2 * (q0 * q1 - q2 * q3), 1 - 2 * (q1 * q1 + q2 * q2)) y = torch.asin(torch.clamp(2 * (q1 * q3 + q0 * q2), -1 + epsilon, 1 - epsilon)) z = torch.atan2(2 * (q0 * q3 - q1 * q2), 1 - 2 * (q2 * q2 + q3 * q3)) elif order == 'yzx': x = torch.atan2(2 * (q0 * q1 - q2 * q3), 1 - 2 * (q1 * q1 + q3 * q3)) y = torch.atan2(2 * (q0 * q2 - q1 * q3), 1 - 2 * (q2 * q2 + q3 * q3)) z = torch.asin(torch.clamp(2 * (q1 * q2 + q0 * q3), -1 + epsilon, 1 - epsilon)) elif order == 'zxy': x = torch.asin(torch.clamp(2 * (q0 * q1 + q2 * q3), -1 + epsilon, 1 - epsilon)) y = torch.atan2(2 * (q0 * q2 - q1 * q3), 1 - 2 * (q1 * q1 + q2 * q2)) z = torch.atan2(2 * (q0 * q3 - q1 * q2), 1 - 2 * (q1 * q1 + q3 * q3)) elif order == 'xzy': x = torch.atan2(2 * (q0 * q1 + q2 * q3), 1 - 2 * (q1 * q1 + q3 * q3)) y = torch.atan2(2 * (q0 * q2 + q1 * q3), 1 - 2 * (q2 * q2 + q3 * q3)) z = torch.asin(torch.clamp(2 * (q0 * q3 - q1 * q2), -1 + epsilon, 1 - epsilon)) elif order == 'yxz': x = torch.asin(torch.clamp(2 * (q0 * q1 - q2 * q3), -1 + epsilon, 1 - epsilon)) y = torch.atan2(2 * (q1 * q3 + q0 * q2), 1 - 2 * (q1 * q1 + q2 * q2)) z = torch.atan2(2 * (q1 * q2 + q0 * q3), 1 - 2 * (q1 * q1 + q3 * q3)) elif order == 'zyx': x = torch.atan2(2 * (q0 * q1 + q2 * q3), 1 - 2 * (q1 * q1 + q2 * q2)) y = torch.asin(torch.clamp(2 * (q0 * q2 - q1 * q3), -1 + epsilon, 1 - epsilon)) z = torch.atan2(2 * (q0 * q3 + q1 * q2), 1 - 2 * (q2 * q2 + q3 * q3)) else: raise
if deg: return torch.stack((x, y, z), dim=1).view(original_shape) * 180 / np.pi else: return torch.stack((x, y, z), dim=1).view(original_shape)
# Numpy-backed implementations
def qmul_np(q, r): q = torch.from_numpy(q).contiguous().float() r = torch.from_numpy(r).contiguous().float() return qmul(q, r).numpy()
def qrot_np(q, v): q = torch.from_numpy(q).contiguous().float() v = torch.from_numpy(v).contiguous().float() return qrot(q, v).numpy()
def qeuler_np(q, order, epsilon=0, use_gpu=False): if use_gpu: q = torch.from_numpy(q).cuda().float() return qeuler(q, order, epsilon).cpu().numpy() else: q = torch.from_numpy(q).contiguous().float() return qeuler(q, order, epsilon).numpy()
def qfix(q): """ Enforce quaternion continuity across the time dimension by selecting the representation (q or -q) with minimal distance (or, equivalently, maximal dot product) between two consecutive frames.
Expects a tensor of shape (L, J, 4), where L is the sequence length and J is the number of joints. Returns a tensor of the same shape. """ assert len(q.shape) == 3 assert q.shape[-1] == 4
result = q.copy() dot_products = np.sum(q[1:] * q[:-1], axis=2) mask = dot_products < 0 mask = (np.cumsum(mask, axis=0) % 2).astype(bool) result[1:][mask] *= -1 return result
def euler2quat(e, order, deg=True): """ Convert Euler angles to quaternions. """ assert e.shape[-1] == 3
original_shape = list(e.shape) original_shape[-1] = 4
e = e.view(-1, 3)
## if euler angles in degrees if deg: e = e * np.pi / 180.
x = e[:, 0] y = e[:, 1] z = e[:, 2]
rx = torch.stack((torch.cos(x / 2), torch.sin(x / 2), torch.zeros_like(x), torch.zeros_like(x)), dim=1) ry = torch.stack((torch.cos(y / 2), torch.zeros_like(y), torch.sin(y / 2), torch.zeros_like(y)), dim=1) rz = torch.stack((torch.cos(z / 2), torch.zeros_like(z), torch.zeros_like(z), torch.sin(z / 2)), dim=1)
result = None for coord in order: if coord == 'x': r = rx elif coord == 'y': r = ry elif coord == 'z': r = rz else: raise if result is None: result = r else: result = qmul(result, r)
# Reverse antipodal representation to have a non-negative "w" if order in ['xyz', 'yzx', 'zxy']: result *= -1
return result.view(original_shape)
def expmap_to_quaternion(e): """ Convert axis-angle rotations (aka exponential maps) to quaternions. Stable formula from "Practical Parameterization of Rotations Using the Exponential Map". Expects a tensor of shape (*, 3), where * denotes any number of dimensions. Returns a tensor of shape (*, 4). """ assert e.shape[-1] == 3
original_shape = list(e.shape) original_shape[-1] = 4 e = e.reshape(-1, 3)
theta = np.linalg.norm(e, axis=1).reshape(-1, 1) w = np.cos(0.5 * theta).reshape(-1, 1) xyz = 0.5 * np.sinc(0.5 * theta / np.pi) * e return np.concatenate((w, xyz), axis=1).reshape(original_shape)
def euler_to_quaternion(e, order): """ Convert Euler angles to quaternions. """ assert e.shape[-1] == 3
original_shape = list(e.shape) original_shape[-1] = 4
e = e.reshape(-1, 3)
x = e[:, 0] y = e[:, 1] z = e[:, 2]
rx = np.stack((np.cos(x / 2), np.sin(x / 2), np.zeros_like(x), np.zeros_like(x)), axis=1) ry = np.stack((np.cos(y / 2), np.zeros_like(y), np.sin(y / 2), np.zeros_like(y)), axis=1) rz = np.stack((np.cos(z / 2), np.zeros_like(z), np.zeros_like(z), np.sin(z / 2)), axis=1)
result = None for coord in order: if coord == 'x': r = rx elif coord == 'y': r = ry elif coord == 'z': r = rz else: raise if result is None: result = r else: result = qmul_np(result, r)
# Reverse antipodal representation to have a non-negative "w" if order in ['xyz', 'yzx', 'zxy']: result *= -1
return result.reshape(original_shape)
def quaternion_to_matrix(quaternions): """ Convert rotations given as quaternions to rotation matrices. Args: quaternions: quaternions with real part first, as tensor of shape (..., 4). Returns: Rotation matrices as tensor of shape (..., 3, 3). """ r, i, j, k = torch.unbind(quaternions, -1) two_s = 2.0 / (quaternions * quaternions).sum(-1)
o = torch.stack( ( 1 - two_s * (j * j + k * k), two_s * (i * j - k * r), two_s * (i * k + j * r), two_s * (i * j + k * r), 1 - two_s * (i * i + k * k), two_s * (j * k - i * r), two_s * (i * k - j * r), two_s * (j * k + i * r), 1 - two_s * (i * i + j * j), ), -1, ) return o.reshape(quaternions.shape[:-1] + (3, 3))
def quaternion_to_matrix_np(quaternions): q = torch.from_numpy(quaternions).contiguous().float() return quaternion_to_matrix(q).numpy()
def quaternion_to_cont6d_np(quaternions): rotation_mat = quaternion_to_matrix_np(quaternions) cont_6d = np.concatenate([rotation_mat[..., 0], rotation_mat[..., 1]], axis=-1) return cont_6d
def quaternion_to_cont6d(quaternions): rotation_mat = quaternion_to_matrix(quaternions) cont_6d = torch.cat([rotation_mat[..., 0], rotation_mat[..., 1]], dim=-1) return cont_6d
def cont6d_to_matrix(cont6d): assert cont6d.shape[-1] == 6, "The last dimension must be 6" x_raw = cont6d[..., 0:3] y_raw = cont6d[..., 3:6]
x = x_raw / torch.norm(x_raw, dim=-1, keepdim=True) z = torch.cross(x, y_raw, dim=-1) z = z / torch.norm(z, dim=-1, keepdim=True)
y = torch.cross(z, x, dim=-1)
x = x[..., None] y = y[..., None] z = z[..., None]
mat = torch.cat([x, y, z], dim=-1) return mat
def cont6d_to_matrix_np(cont6d): q = torch.from_numpy(cont6d).contiguous().float() return cont6d_to_matrix(q).numpy()
def qpow(q0, t, dtype=torch.float): ''' q0 : tensor of quaternions t: tensor of powers ''' q0 = qnormalize(q0) theta0 = torch.acos(q0[..., 0])
## if theta0 is close to zero, add epsilon to avoid NaNs mask = (theta0 <= 10e-10) * (theta0 >= -10e-10) theta0 = (1 - mask) * theta0 + mask * 10e-10 v0 = q0[..., 1:] / torch.sin(theta0).view(-1, 1)
if isinstance(t, torch.Tensor): q = torch.zeros(t.shape + q0.shape) theta = t.view(-1, 1) * theta0.view(1, -1) else: ## if t is a number q = torch.zeros(q0.shape) theta = t * theta0
q[..., 0] = torch.cos(theta) q[..., 1:] = v0 * torch.sin(theta).unsqueeze(-1)
return q.to(dtype)
def qslerp(q0, q1, t): ''' q0: starting quaternion q1: ending quaternion t: array of points along the way
Returns: Tensor of Slerps: t.shape + q0.shape '''
q0 = qnormalize(q0) q1 = qnormalize(q1) q_ = qpow(qmul(q1, qinv(q0)), t)
return qmul(q_, q0.contiguous().view(torch.Size([1] * len(t.shape)) + q0.shape).expand(t.shape + q0.shape).contiguous())
def qbetween(v0, v1): ''' find the quaternion used to rotate v0 to v1 ''' assert v0.shape[-1] == 3, 'v0 must be of the shape (*, 3)' assert v1.shape[-1] == 3, 'v1 must be of the shape (*, 3)'
v = torch.cross(v0, v1) w = torch.sqrt((v0 ** 2).sum(dim=-1, keepdim=True) * (v1 ** 2).sum(dim=-1, keepdim=True)) + (v0 * v1).sum(dim=-1, keepdim=True) return qnormalize(torch.cat([w, v], dim=-1))
def qbetween_np(v0, v1): ''' find the quaternion used to rotate v0 to v1 ''' assert v0.shape[-1] == 3, 'v0 must be of the shape (*, 3)' assert v1.shape[-1] == 3, 'v1 must be of the shape (*, 3)'
v0 = torch.from_numpy(v0).float() v1 = torch.from_numpy(v1).float() return qbetween(v0, v1).numpy()
def lerp(p0, p1, t): if not isinstance(t, torch.Tensor): t = torch.Tensor([t])
new_shape = t.shape + p0.shape new_view_t = t.shape + torch.Size([1] * len(p0.shape)) new_view_p = torch.Size([1] * len(t.shape)) + p0.shape p0 = p0.view(new_view_p).expand(new_shape) p1 = p1.view(new_view_p).expand(new_shape) t = t.view(new_view_t).expand(new_shape)
return p0 + t * (p1 - p0)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199from utils.quaternion import *import scipy.ndimage.filters as filters
class Skeleton(object): def __init__(self, offset, kinematic_tree, device): self.device = device self._raw_offset_np = offset.numpy() self._raw_offset = offset.clone().detach().to(device).float() self._kinematic_tree = kinematic_tree self._offset = None self._parents = [0] * len(self._raw_offset) self._parents[0] = -1 for chain in self._kinematic_tree: for j in range(1, len(chain)): self._parents[chain[j]] = chain[j-1]
def njoints(self): return len(self._raw_offset)
def offset(self): return self._offset
def set_offset(self, offsets): self._offset = offsets.clone().detach().to(self.device).float()
def kinematic_tree(self): return self._kinematic_tree
def parents(self): return self._parents
# joints (batch_size, joints_num, 3) def get_offsets_joints_batch(self, joints): assert len(joints.shape) == 3 _offsets = self._raw_offset.expand(joints.shape[0], -1, -1).clone() for i in range(1, self._raw_offset.shape[0]): _offsets[:, i] = torch.norm(joints[:, i] - joints[:, self._parents[i]], p=2, dim=1)[:, None] * _offsets[:, i]
self._offset = _offsets.detach() return _offsets
# joints (joints_num, 3) def get_offsets_joints(self, joints): assert len(joints.shape) == 2 _offsets = self._raw_offset.clone() for i in range(1, self._raw_offset.shape[0]): # print(joints.shape) _offsets[i] = torch.norm(joints[i] - joints[self._parents[i]], p=2, dim=0) * _offsets[i]
self._offset = _offsets.detach() return _offsets
# face_joint_idx should follow the order of right hip, left hip, right shoulder, left shoulder # joints (batch_size, joints_num, 3) def inverse_kinematics_np(self, joints, face_joint_idx, smooth_forward=False): assert len(face_joint_idx) == 4 '''Get Forward Direction''' l_hip, r_hip, sdr_r, sdr_l = face_joint_idx across1 = joints[:, r_hip] - joints[:, l_hip] across2 = joints[:, sdr_r] - joints[:, sdr_l] across = across1 + across2 across = across / np.sqrt((across**2).sum(axis=-1))[:, np.newaxis] # print(across1.shape, across2.shape)
# forward (batch_size, 3) forward = np.cross(np.array([[0, 1, 0]]), across, axis=-1) if smooth_forward: forward = filters.gaussian_filter1d(forward, 20, axis=0, mode='nearest') # forward (batch_size, 3) forward = forward / np.sqrt((forward**2).sum(axis=-1))[..., np.newaxis]
'''Get Root Rotation''' target = np.array([[0,0,1]]).repeat(len(forward), axis=0) root_quat = qbetween_np(forward, target)
'''Inverse Kinematics''' # quat_params (batch_size, joints_num, 4) # print(joints.shape[:-1]) quat_params = np.zeros(joints.shape[:-1] + (4,)) # print(quat_params.shape) root_quat[0] = np.array([[1.0, 0.0, 0.0, 0.0]]) quat_params[:, 0] = root_quat # quat_params[0, 0] = np.array([[1.0, 0.0, 0.0, 0.0]]) for chain in self._kinematic_tree: R = root_quat for j in range(len(chain) - 1): # (batch, 3) u = self._raw_offset_np[chain[j+1]][np.newaxis,...].repeat(len(joints), axis=0) # print(u.shape) # (batch, 3) v = joints[:, chain[j+1]] - joints[:, chain[j]] v = v / np.sqrt((v**2).sum(axis=-1))[:, np.newaxis] # print(u.shape, v.shape) rot_u_v = qbetween_np(u, v)
R_loc = qmul_np(qinv_np(R), rot_u_v)
quat_params[:,chain[j + 1], :] = R_loc R = qmul_np(R, R_loc)
return quat_params
# Be sure root joint is at the beginning of kinematic chains def forward_kinematics(self, quat_params, root_pos, skel_joints=None, do_root_R=True): # quat_params (batch_size, joints_num, 4) # joints (batch_size, joints_num, 3) # root_pos (batch_size, 3) if skel_joints is not None: offsets = self.get_offsets_joints_batch(skel_joints) if len(self._offset.shape) == 2: offsets = self._offset.expand(quat_params.shape[0], -1, -1) joints = torch.zeros(quat_params.shape[:-1] + (3,)).to(self.device) joints[:, 0] = root_pos for chain in self._kinematic_tree: if do_root_R: R = quat_params[:, 0] else: R = torch.tensor([[1.0, 0.0, 0.0, 0.0]]).expand(len(quat_params), -1).detach().to(self.device) for i in range(1, len(chain)): R = qmul(R, quat_params[:, chain[i]]) offset_vec = offsets[:, chain[i]] joints[:, chain[i]] = qrot(R, offset_vec) + joints[:, chain[i-1]] return joints
# Be sure root joint is at the beginning of kinematic chains def forward_kinematics_np(self, quat_params, root_pos, skel_joints=None, do_root_R=True): # quat_params (batch_size, joints_num, 4) # joints (batch_size, joints_num, 3) # root_pos (batch_size, 3) if skel_joints is not None: skel_joints = torch.from_numpy(skel_joints) offsets = self.get_offsets_joints_batch(skel_joints) if len(self._offset.shape) == 2: offsets = self._offset.expand(quat_params.shape[0], -1, -1) offsets = offsets.numpy() joints = np.zeros(quat_params.shape[:-1] + (3,)) joints[:, 0] = root_pos for chain in self._kinematic_tree: if do_root_R: R = quat_params[:, 0] else: R = np.array([[1.0, 0.0, 0.0, 0.0]]).repeat(len(quat_params), axis=0) for i in range(1, len(chain)): R = qmul_np(R, quat_params[:, chain[i]]) offset_vec = offsets[:, chain[i]] joints[:, chain[i]] = qrot_np(R, offset_vec) + joints[:, chain[i - 1]] return joints
def forward_kinematics_cont6d_np(self, cont6d_params, root_pos, skel_joints=None, do_root_R=True): # cont6d_params (batch_size, joints_num, 6) # joints (batch_size, joints_num, 3) # root_pos (batch_size, 3) if skel_joints is not None: skel_joints = torch.from_numpy(skel_joints) offsets = self.get_offsets_joints_batch(skel_joints) if len(self._offset.shape) == 2: offsets = self._offset.expand(cont6d_params.shape[0], -1, -1) offsets = offsets.numpy() joints = np.zeros(cont6d_params.shape[:-1] + (3,)) joints[:, 0] = root_pos for chain in self._kinematic_tree: if do_root_R: matR = cont6d_to_matrix_np(cont6d_params[:, 0]) else: matR = np.eye(3)[np.newaxis, :].repeat(len(cont6d_params), axis=0) for i in range(1, len(chain)): matR = np.matmul(matR, cont6d_to_matrix_np(cont6d_params[:, chain[i]])) offset_vec = offsets[:, chain[i]][..., np.newaxis] # print(matR.shape, offset_vec.shape) joints[:, chain[i]] = np.matmul(matR, offset_vec).squeeze(-1) + joints[:, chain[i-1]] return joints
def forward_kinematics_cont6d(self, cont6d_params, root_pos, skel_joints=None, do_root_R=True): # cont6d_params (batch_size, joints_num, 6) # joints (batch_size, joints_num, 3) # root_pos (batch_size, 3) if skel_joints is not None: # skel_joints = torch.from_numpy(skel_joints) offsets = self.get_offsets_joints_batch(skel_joints) if len(self._offset.shape) == 2: offsets = self._offset.expand(cont6d_params.shape[0], -1, -1) joints = torch.zeros(cont6d_params.shape[:-1] + (3,)).to(cont6d_params.device) joints[..., 0, :] = root_pos for chain in self._kinematic_tree: if do_root_R: matR = cont6d_to_matrix(cont6d_params[:, 0]) else: matR = torch.eye(3).expand((len(cont6d_params), -1, -1)).detach().to(cont6d_params.device) for i in range(1, len(chain)): matR = torch.matmul(matR, cont6d_to_matrix(cont6d_params[:, chain[i]])) offset_vec = offsets[:, chain[i]].unsqueeze(-1) # print(matR.shape, offset_vec.shape) joints[:, chain[i]] = torch.matmul(matR, offset_vec).squeeze(-1) + joints[:, chain[i-1]] return joints
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156import mathimport osimport randomimport timeimport torch
import numpy as npimport torch as thfrom PIL import Imagefrom scipy.ndimage import gaussian_filter
from utils import paramUtil
def set_random_seed(seed: int, using_cuda: bool = False) -> None: """Seed the different random generators.
:param seed: :param using_cuda: """ # Seed python RNG random.seed(seed) # Seed numpy RNG np.random.seed(seed) # seed the RNG for all devices (both CPU and CUDA) th.manual_seed(seed)
if using_cuda: # Deterministic operations for CuDNN, it may impact performances th.backends.cudnn.deterministic = True th.backends.cudnn.benchmark = False
def mkdir(path): if not os.path.exists(path): os.makedirs(path)
COLORS = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
MISSING_VALUE = -1
def save_image(image_numpy, image_path): img_pil = Image.fromarray(image_numpy) img_pil.save(image_path)
def save_logfile(log_loss, save_path): with open(save_path, 'wt') as f: for k, v in log_loss.items(): w_line = k for digit in v: w_line += ' %.3f' % digit f.write(w_line + '\n')
def print_current_loss(start_time, niter_state, losses, epoch=None, inner_iter=None):
def as_minutes(s): m = math.floor(s / 60) s -= m * 60 return '%dm %ds' % (m, s)
def time_since(since, percent): now = time.time() s = now - since es = s / percent rs = es - s return '%s (- %s)' % (as_minutes(s), as_minutes(rs))
if epoch is not None: print('epoch: %3d niter: %6d inner_iter: %4d' % (epoch, niter_state, inner_iter), end=" ")
now = time.time() message = '%s'%(as_minutes(now - start_time))
for k, v in losses.items(): message += ' %s: %.4f ' % (k, v) print(message)
def compose_gif_img_list(img_list, fp_out, duration): img, *imgs = [Image.fromarray(np.array(image)) for image in img_list] img.save(fp=fp_out, format='GIF', append_images=imgs, optimize=False, save_all=True, loop=0, duration=duration)
def save_images(visuals, image_path): if not os.path.exists(image_path): os.makedirs(image_path)
for i, (label, img_numpy) in enumerate(visuals.items()): img_name = '%d_%s.jpg' % (i, label) save_path = os.path.join(image_path, img_name) save_image(img_numpy, save_path)
def save_images_test(visuals, image_path, from_name, to_name): if not os.path.exists(image_path): os.makedirs(image_path)
for i, (label, img_numpy) in enumerate(visuals.items()): img_name = "%s_%s_%s" % (from_name, to_name, label) save_path = os.path.join(image_path, img_name) save_image(img_numpy, save_path)
def compose_and_save_img(img_list, save_dir, img_name, col=4, row=1, img_size=(256, 200)): # print(col, row) compose_img = compose_image(img_list, col, row, img_size) if not os.path.exists(save_dir): os.makedirs(save_dir) img_path = os.path.join(save_dir, img_name) # print(img_path) compose_img.save(img_path)
def compose_image(img_list, col, row, img_size): to_image = Image.new('RGB', (col * img_size[0], row * img_size[1])) for y in range(0, row): for x in range(0, col): from_img = Image.fromarray(img_list[y * col + x]) # print((x * img_size[0], y*img_size[1], # (x + 1) * img_size[0], (y + 1) * img_size[1])) paste_area = (x * img_size[0], y*img_size[1], (x + 1) * img_size[0], (y + 1) * img_size[1]) to_image.paste(from_img, paste_area) # to_image[y*img_size[1]:(y + 1) * img_size[1], x * img_size[0] :(x + 1) * img_size[0]] = from_img return to_image
def list_cut_average(ll, intervals): if intervals == 1: return ll
bins = math.ceil(len(ll) * 1.0 / intervals) ll_new = [] for i in range(bins): l_low = intervals * i l_high = l_low + intervals l_high = l_high if l_high < len(ll) else len(ll) ll_new.append(np.mean(ll[l_low:l_high])) return ll_new
def motion_temporal_filter(motion, sigma=1): motion = motion.reshape(motion.shape[0], -1) # print(motion.shape) for i in range(motion.shape[1]): motion[:, i] = gaussian_filter(motion[:, i], sigma=sigma, mode="nearest") return motion.reshape(motion.shape[0], -1, 3)
def get_device(args): return torch.device('cuda:%d' % args.gpu_id if args.gpu_id != -1 else 'cpu')
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import numpy as npimport picklefrom os.path import join as pjoin
POS_enumerator = { 'VERB': 0, 'NOUN': 1, 'DET': 2, 'ADP': 3, 'NUM': 4, 'AUX': 5, 'PRON': 6, 'ADJ': 7, 'ADV': 8, 'Loc_VIP': 9, 'Body_VIP': 10, 'Obj_VIP': 11, 'Act_VIP': 12, 'Desc_VIP': 13, 'OTHER': 14,}
Loc_list = ('left', 'right', 'clockwise', 'counterclockwise', 'anticlockwise', 'forward', 'back', 'backward', 'up', 'down', 'straight', 'curve')
Body_list = ('arm', 'chin', 'foot', 'feet', 'face', 'hand', 'mouth', 'leg', 'waist', 'eye', 'knee', 'shoulder', 'thigh')
Obj_List = ('stair', 'dumbbell', 'chair', 'window', 'floor', 'car', 'ball', 'handrail', 'baseball', 'basketball')
Act_list = ('walk', 'run', 'swing', 'pick', 'bring', 'kick', 'put', 'squat', 'throw', 'hop', 'dance', 'jump', 'turn', 'stumble', 'dance', 'stop', 'sit', 'lift', 'lower', 'raise', 'wash', 'stand', 'kneel', 'stroll', 'rub', 'bend', 'balance', 'flap', 'jog', 'shuffle', 'lean', 'rotate', 'spin', 'spread', 'climb')
Desc_list = ('slowly', 'carefully', 'fast', 'careful', 'slow', 'quickly', 'happy', 'angry', 'sad', 'happily', 'angrily', 'sadly')
VIP_dict = { 'Loc_VIP': Loc_list, 'Body_VIP': Body_list, 'Obj_VIP': Obj_List, 'Act_VIP': Act_list, 'Desc_VIP': Desc_list,}
class WordVectorizer(object): def __init__(self, meta_root, prefix): vectors = np.load(pjoin(meta_root, '%s_data.npy'%prefix)) words = pickle.load(open(pjoin(meta_root, '%s_words.pkl'%prefix), 'rb')) word2idx = pickle.load(open(pjoin(meta_root, '%s_idx.pkl'%prefix), 'rb')) self.word2vec = {w: vectors[word2idx[w]] for w in words}
def _get_pos_ohot(self, pos): pos_vec = np.zeros(len(POS_enumerator)) if pos in POS_enumerator: pos_vec[POS_enumerator[pos]] = 1 else: pos_vec[POS_enumerator['OTHER']] = 1 return pos_vec
def __len__(self): return len(self.word2vec)
def __getitem__(self, item): word, pos = item.split('/') if word in self.word2vec: word_vec = self.word2vec[word] vip_pos = None for key, values in VIP_dict.items(): if word in values: vip_pos = key break if vip_pos is not None: pos_vec = self._get_pos_ohot(vip_pos) else: pos_vec = self._get_pos_ohot(pos) else: word_vec = self.word2vec['unk'] pos_vec = self._get_pos_ohot('OTHER') return word_vec, pos_vec.gitattributesAdded+2
.gitignoreAdded+6
.python-versionAdded+1
text2motion/MakefileAdded+131
text2motion/data/GRAB/grab_all.txtAdded+1335
text2motion/data/GRAB/grab_test.txtAdded+201
text2motion/data/GRAB/grab_train.txtAdded+1068
text2motion/data/GRAB/grab_val.txtAdded+66
text2motion/data/GRAB/test.txtAdded+1
text2motion/data/GRAB/train.txtAdded+1068
text2motion/data/GRAB/train_long.txtAdded+8
text2motion/data/GRAB/train_short.txtAdded+1
text2motion/data/GRAB/train_val.txtAdded+1
text2motion/datasets/__init__.pyAdded+16
text2motion/datasets/combine_gifs.pyAdded+87
text2motion/datasets/dataloader.pyAdded+128
text2motion/datasets/dataset.pyAdded+194
text2motion/datasets/evaluator.pyAdded+469
text2motion/datasets/evaluator_models.pyAdded+438
text2motion/datasets/mean_mesh.pyAdded+231
text2motion/datasets/motionx_explorer.pyAdded+554
text2motion/datasets/rendering.pyAdded+126
text2motion/datasets/statistics_writer.pyAdded+56
text2motion/datasets/train_explorer.ipynbAdded
text2motion/datasets/utils.pyAdded+18
text2motion/dtu_README.mdAdded+58
text2motion/install.mdAdded+154
text2motion/jobscript.shAdded+40
text2motion/models/__init__.pyAdded+4
text2motion/models/gaussian_diffusion.pyAdded+1147
text2motion/models/transformer.pyAdded+429
text2motion/options/base_options.pyAdded+91
text2motion/options/evaluate_options.pyAdded+27
text2motion/options/train_options.pyAdded+32
text2motion/requirements.txtAdded+11
text2motion/tools/__init__.pyAdded
text2motion/tools/arguments.pyAdded+37
text2motion/tools/evaluation.pyAdded+278
text2motion/tools/inference.pyAdded+105
text2motion/tools/train.pyAdded+134
text2motion/utils/__init__.pyAdded
text2motion/utils/get_opt.pyAdded+102
text2motion/utils/metrics.pyAdded+146
text2motion/utils/motion_process.pyAdded+515
text2motion/utils/paramUtil.pyAdded+63
text2motion/utils/plot_script.pyAdded+115
text2motion/utils/quaternion.pyAdded+423
text2motion/utils/skeleton.pyAdded+199
text2motion/utils/utils.pyAdded+156
text2motion/utils/word_vectorizer.pyAdded+80