diff --git a/11887_pesto-pasta_Rita-1x1-1-501c953b29074ab193e2b5ad36e64648.jpg b/11887_pesto-pasta_Rita-1x1-1-501c953b29074ab193e2b5ad36e64648.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9acb1ecd9cfc3287d69c31c9351f84d84ad6d80c Binary files /dev/null and b/11887_pesto-pasta_Rita-1x1-1-501c953b29074ab193e2b5ad36e64648.jpg differ diff --git a/4645808729_2dfc59b6a5_z.jpg b/4645808729_2dfc59b6a5_z.jpg new file mode 100644 index 0000000000000000000000000000000000000000..eff20c3d7f705dcfddc5eeea0b7be104370de386 Binary files /dev/null and b/4645808729_2dfc59b6a5_z.jpg differ diff --git a/5944609705_4664531909_z.jpg b/5944609705_4664531909_z.jpg new file mode 100644 index 0000000000000000000000000000000000000000..a5acafad87cdeb4eba96a40c004d289bde698d14 Binary files /dev/null and b/5944609705_4664531909_z.jpg differ diff --git a/900.jpeg b/900.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..32c19c883a40a5718d7bd970aa3439bf892568de Binary files /dev/null and b/900.jpeg differ diff --git a/COCO_train2014_000000194806.jpg b/COCO_train2014_000000194806.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d26e39459ba8eab5dc60289459d76b7b04446800 Binary files /dev/null and b/COCO_train2014_000000194806.jpg differ diff --git a/COCO_train2014_000000318365.jpg b/COCO_train2014_000000318365.jpg new file mode 100644 index 0000000000000000000000000000000000000000..303ec17e861ceec96e84a4d4a393720234b4b275 Binary files /dev/null and b/COCO_train2014_000000318365.jpg differ diff --git a/COCO_train2014_000000572279.jpg b/COCO_train2014_000000572279.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0c34a1a5638d0864bdea2a93b07920d1d2436fc0 Binary files /dev/null and b/COCO_train2014_000000572279.jpg differ diff --git a/bad_words.txt b/bad_words.txt new file mode 100644 index 0000000000000000000000000000000000000000..1a9899b4ec9b65ac9f5d33139d3f09d848829a1d --- /dev/null +++ b/bad_words.txt @@ -0,0 +1,403 @@ +2g1c +2 girls 1 cup +acrotomophilia +alabama hot pocket +alaskan pipeline +anal +anilingus +anus +apeshit +arsehole +ass +asshole +assmunch +auto erotic +autoerotic +babeland +baby batter +baby juice +ball gag +ball gravy +ball kicking +ball licking +ball sack +ball sucking +bangbros +bangbus +bareback +barely legal +barenaked +bastard +bastardo +bastinado +bbw +bdsm +beaner +beaners +beaver cleaver +beaver lips +beastiality +bestiality +big black +big breasts +big knockers +big tits +bimbos +birdlock +bitch +bitches +black cock +blonde action +blonde on blonde action +blowjob +blow job +blow your load +blue waffle +blumpkin +bollocks +bondage +boner +boob +boobs +booty call +brown showers +brunette action +bukkake +bulldyke +bullet vibe +bullshit +bung hole +bunghole +busty +butt +buttcheeks +butthole +camel toe +camgirl +camslut +camwhore +carpet muncher +carpetmuncher +chocolate rosebuds +cialis +circlejerk +cleveland steamer +clit +clitoris +clover clamps +clusterfuck +cock +cocks +coprolagnia +coprophilia +cornhole +coon +coons +creampie +cum +cumming +cumshot +cumshots +cunnilingus +cunt +darkie +date rape +daterape +deep throat +deepthroat +dendrophilia +dick +dildo +dingleberry +dingleberries +dirty pillows +dirty sanchez +doggie style +doggiestyle +doggy style +doggystyle +dog style +dolcett +domination +dominatrix +dommes +donkey punch +double dong +double penetration +dp action +dry hump +dvda +eat my ass +ecchi +ejaculation +erotic +erotism +escort +eunuch +fag +faggot +fecal +felch +fellatio +feltch +female squirting +femdom +figging +fingerbang +fingering +fisting +foot fetish +footjob +frotting +fuck +fuck buttons +fuckin +fucking +fucktards +fudge packer +fudgepacker +futanari +gangbang +gang bang +gay sex +genitals +giant cock +girl on +girl on top +girls gone wild +goatcx +goatse +god damn +gokkun +golden shower +goodpoop +goo girl +goregasm +grope +group sex +g-spot +guro +hand job +handjob +hard core +hardcore +hentai +homoerotic +honkey +hooker +horny +hot carl +hot chick +how to kill +how to murder +huge fat +humping +incest +intercourse +jack off +jail bait +jailbait +jelly donut +jerk off +jigaboo +jiggaboo +jiggerboo +jizz +juggs +kike +kinbaku +kinkster +kinky +knobbing +leather restraint +leather straight jacket +lemon party +livesex +lolita +lovemaking +make me come +male squirting +masturbate +masturbating +masturbation +menage a trois +milf +missionary position +mong +motherfucker +mound of venus +mr hands +muff diver +muffdiving +nambla +nawashi +negro +neonazi +nigga +nigger +nig nog +nimphomania +nipple +nipples +nsfw +nsfw images +nude +nudity +nutten +nympho +nymphomania +octopussy +omorashi +one cup two girls +one guy one jar +orgasm +orgy +paedophile +paki +panties +panty +pedobear +pedophile +pegging +penis +phone sex +piece of shit +pikey +pissing +piss pig +pisspig +playboy +pleasure chest +pole smoker +ponyplay +poof +poon +poontang +punany +poop chute +poopchute +porn +porno +pornography +prince albert piercing +pthc +pubes +pussy +queaf +queef +quim +raghead +raging boner +rape +raping +rapist +rectum +reverse cowgirl +rimjob +rimming +rosy palm +rosy palm and her 5 sisters +rusty trombone +sadism +santorum +scat +schlong +scissoring +semen +sex +sexcam +sexo +sexy +sexual +sexually +sexuality +shaved beaver +shaved pussy +shemale +shibari +shit +shitblimp +shitty +shota +shrimping +skeet +slanteye +slut +s&m +smut +snatch +snowballing +sodomize +sodomy +spastic +spic +splooge +splooge moose +spooge +spread legs +spunk +strap on +strapon +strappado +strip club +style doggy +suck +sucks +suicide girls +sultry women +swastika +swinger +tainted love +taste my +tea bagging +threesome +throating +thumbzilla +tied up +tight white +tit +tits +titties +titty +tongue in a +topless +tosser +towelhead +tranny +tribadism +tub girl +tubgirl +tushy +twat +twink +twinkie +two girls one cup +undressing +upskirt +urethra play +urophilia +vagina +venus mound +viagra +vibrator +violet wand +vorarephilia +voyeur +voyeurweb +voyuer +vulva +wank +wetback +wet dream +white power +whore +worldsex +wrapping men +wrinkled starfish +xx +xxx +yaoi +yellow showers +yiffy +zoophilia +🖕 \ No newline at end of file diff --git a/bcee7a-20190225-a-london-underground-sign.jpg b/bcee7a-20190225-a-london-underground-sign.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e6aa9c040a1c01798d1e4d45cf3fa01622054f2d Binary files /dev/null and b/bcee7a-20190225-a-london-underground-sign.jpg differ diff --git a/chinchilla_web-1024x683.jpg b/chinchilla_web-1024x683.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ac4480f167619d79c4b628a81072497eb34dbc6b Binary files /dev/null and b/chinchilla_web-1024x683.jpg differ diff --git a/dogs.jpeg b/dogs.jpeg new file mode 100644 index 0000000000000000000000000000000000000000..b8f1b45c6f699323673a8c37cdd9f99eaf3a5558 Binary files /dev/null and b/dogs.jpeg differ diff --git a/hummus.jpg b/hummus.jpg new file mode 100644 index 0000000000000000000000000000000000000000..95cc143fad75e94580c597e3d9d4032a5a376956 Binary files /dev/null and b/hummus.jpg differ diff --git a/icl_demo.py b/icl_demo.py new file mode 100644 index 0000000000000000000000000000000000000000..522a44f719f39f87d8b4baa741c65826476f9c15 --- /dev/null +++ b/icl_demo.py @@ -0,0 +1,325 @@ +import gradio as gr +import torch +from PIL import Image + +demo_imgs = [ + ["chinchilla_web-1024x683.jpg", "shiba-inu-dog-in-the-snow.jpg"], + ["4645808729_2dfc59b6a5_z.jpg", "5944609705_4664531909_z.jpg"], + ["COCO_train2014_000000310472.jpg", "COCO_train2014_000000194806.jpg"], + [ + "bcee7a-20190225-a-london-underground-sign.jpg", + "istockphoto-622434332-1024x1024.jpg", + ], + ["dogs.jpeg", "pandas.jpg"], + ["11887_pesto-pasta_Rita-1x1-1-501c953b29074ab193e2b5ad36e64648.jpg", "hummus.jpg"], +] +demo_texts = [ + [ + "Output: This is a chinchilla. They are mainly found in Chile.", + "Output: This is a shiba. They are very popular in Japan.", + ], + [ + "Output: a man and a woman on a train looking at their cell phones.", + "Output: a lavish reception room with black and white tiled floor.", + ], + [ + "Question: Describe the scene. Answer: A black and yellow fire hydrant sitting on a sidewalk. The sidewalk is made from red bricks.", + "Question: What is the man trying to catch? Answer: The man is catching a white kite that his friend is flying. The two men are on a beach.", + ], + ['Output: "Underground"', 'Output: "Congress Ave"'], + ["Output: 2 dogs", "Output: 3 pandas"], + [ + "Output: Step 1: Cook 8 oz. of pasta until al dente, then drain and set aside. Step 2: In a food processor, blend 2 cups fresh basil leaves, 1/2 cup grated Parmesan cheese, 1/2 cup pine nuts, 2 cloves garlic, and 1/4 cup olive oil until smooth. Step 3: Toss the pesto sauce with the cooked pasta until evenly coated. Step 4: Serve hot and enjoy!", + "Output: Step 1: Drain and rinse a can of chickpeas. Step 2: Add chickpeas to a food processor along with 2-3 cloves of garlic, 2 tbsp of tahini, 2 tbsp of lemon juice, and 1/4 cup of olive oil. Step 3: Process until smooth, scraping down the sides as needed. Step 4: Add salt and pepper to taste. Step 5: If the hummus is too thick, add water 1 tbsp at a time until desired consistency is reached. Step 6: Serve with a drizzle of olive oil and some paprika for garnish. Enjoy!", + ], +] + +# cd to open_flamingo dir and pip install . +import os +os.system("cd open_flamingo && pip install .") + +from open_flamingo import create_model_and_transforms + +# read bad_words.txt +with open("bad_words.txt", "r") as f: + bad_words = f.read().splitlines() + bad_words = set([word.strip().lower() for word in bad_words]) + +model, image_processor, tokenizer = create_model_and_transforms( + clip_vision_encoder_pretrained="openai", + clip_vision_encoder_path="ViT-L-14", + lang_encoder_path="togethercomputer/RedPajama-INCITE-Base-3B-v1", + tokenizer_path="togethercomputer/RedPajama-INCITE-Base-3B-v1", + cross_attn_every_n_layers=2, +) + +model.eval() + + +def generate( + idx, + image, + text, + example_one_image=None, + example_one_text=None, + example_two_image=None, + example_two_text=None, + tc=True +): + if not tc: + raise gr.Error("Please read the terms and conditions.") + + if image is None: + raise gr.Error("Please upload an image.") + + example_one_image = ( + Image.open(demo_imgs[idx][0]) + if example_one_image is None + else example_one_image + ) + example_one_text = ( + demo_texts[idx][0] + if example_one_text is None + else f"Output: {example_one_text}" + ) + + example_two_image = ( + Image.open(demo_imgs[idx][1]) + if example_two_image is None + else example_two_image + ) + example_two_text = ( + demo_texts[idx][1] + if example_two_text is None + else f"Output: {example_two_text}" + ) + + if ( + example_one_image is None + or example_one_text is None + or example_two_image is None + or example_two_text is None + ): + raise gr.Error("Please fill in all the fields (image and text).") + + demo_plus_text = f"{example_one_text}<|endofchunk|>{example_two_text}<|endofchunk|>" + demo_plus_text += ( + "Output:" if idx != 2 else f"Question: {text.strip()} Answer:" + ) + # demo_plus_image = [example_one_image, example_two_image, image] + + # print(demo_plus_image) + print(demo_plus_text) + + lang_x = tokenizer(demo_plus_text, return_tensors="pt") + input_ids = lang_x["input_ids"] + attention_mask = lang_x["attention_mask"] + + vision_x = [image_processor(example_one_image).unsqueeze(0), image_processor(example_two_image).unsqueeze(0), image_processor(image).unsqueeze(0)] + vision_x = torch.cat(vision_x, dim=0) + vision_x = vision_x.unsqueeze(1).unsqueeze(0) + print(vision_x.shape) + + # with torch.cuda.amp.autocast(dtype=torch.bfloat16): + output = model.generate( + vision_x=vision_x, + lang_x=input_ids, + attention_mask=attention_mask, + max_new_tokens=100, + num_beams=1, + ) + + gen_text = tokenizer.decode( + output[0][len(input_ids[0]):], skip_special_tokens=True + ) + + print(gen_text) + gen_text = gen_text.split("Output")[0] + gen_text = gen_text.split("Question")[0] + + for word in gen_text.split(" "): + word = ( + word.strip() + .lower() + .replace(".", "") + .replace(",", "") + .replace("?", "") + .replace("!", "") + ) + if word in bad_words: + print("Found bad word: ", word) + raise gr.Error( + "We found harmful language in the generated text. Please try again." + ) + + return ( + f"Output:{gen_text}" + if idx != 2 + else f"Question: {text.strip()} Answer: {gen_text}" + ) + + +with gr.Blocks() as demo: + # As a consequence, you should treat this model as a research prototype and not as a production-ready model. Before using this demo please familiarize yourself with our [model card](https://github.com/mlfoundations/open_flamingo/blob/main/MODEL_CARD.md) and [terms and conditions](https://github.com/mlfoundations/open_flamingo/blob/main/TERMS_AND_CONDITIONS.md) + gr.Markdown( + """ + # 🦩 OpenFlamingo-9B Demo + + Blog post: [An open-source framework for training vision-language models with in-context learning (like GPT-4!)]() + GitHub: [open_flamingo](https://github.com/mlfoundations/open_flamingo) + + In this demo we implement an interactive interface that showcases the in-context learning capabilities of the OpenFlamingo-9B model, a large multimodal model trained on top of LLaMA-7B. + The model is trained on an interleaved mixture of text and images and is able to generate text conditioned on sequences of images/text. To safeguard against harmful generations, we detect toxic text in the model output and reject it. However, we understand that this is not a perfect solution and we encourage you to use this demo responsibly. If you find that the model is generating harmful text, please report it using this [form](https://forms.gle/StbcPvyyW2p3Pc7z6). + + Note: This model is still a work in progress and is not fully trained. We are releasing it to showcase the capabilities of the framework and to get feedback from the community. + """ + ) + + with gr.Accordion("See terms and conditions"): + gr.Markdown("""**Please read the following information carefully before proceeding.** +OpenFlamingo is a **research prototype** that aims to enable users to interact with AI through both language and images. AI agents equipped with both language and visual understanding can be useful on a larger variety of tasks compared to models that communicate solely via language. By releasing an open-source research prototype, we hope to help the research community better understand the risks and limitations of modern visual-language AI models and accelerate the development of safer and more reliable methods. +**Limitations.** OpenFlamingo is built on top of the LLaMA large language model developed by Meta AI. Large language models, including LLaMA, are trained on mostly unfiltered internet data, and have been shown to be able to produce toxic, unethical, inaccurate, and harmful content. On top of this, OpenFlamingo’s ability to support visual inputs creates additional risks, since it can be used in a wider variety of applications; image+text models may carry additional risks specific to multimodality. Please use discretion when assessing the accuracy or appropriateness of the model’s outputs, and be mindful before sharing its results. +**Privacy and data collection.** This demo does NOT store any personal information on its users, and it does NOT store user queries. +**Licensing.** As OpenFlamingo is built on top of the LLaMA large language model from Meta AI, the LLaMA license agreement (as documented in the Meta request form) also applies.""") + read_tc = gr.Checkbox( + label="I have read and agree to the terms and conditions") + + with gr.Tab("📷 Image Captioning"): + with gr.Row(): + with gr.Column(scale=1): + demo_image_one = gr.Image(value=Image.open(demo_imgs[1][0]) + ) + demo_text_one = gr.Textbox( + value=demo_texts[1][0], label="Demonstration sample 1", lines=2 + ) + with gr.Column(scale=1): + demo_image_two = gr.Image(value=Image.open(demo_imgs[1][1]) + ) + demo_text_two = gr.Textbox( + value=demo_texts[1][1], label="Demonstration sample 2", lines=2 + ) + with gr.Column(scale=1): + query_image = gr.Image(type="pil") + text_output = gr.Textbox(value="Output:", label="Model output") + + run_btn = gr.Button("Run model") + + def on_click_fn(img): return generate(1, img, "", tc=read_tc) + run_btn.click(on_click_fn, inputs=[query_image], outputs=[text_output]) + + with gr.Tab("🦓 Animal recognition"): + with gr.Row(): + with gr.Column(scale=1): + demo_image_one = gr.Image( + value=Image.open(demo_imgs[0][0]) + ) + demo_text_one = gr.Textbox( + value=demo_texts[0][0], label="Demonstration sample 1", lines=2 + ) + with gr.Column(scale=1): + demo_image_two = gr.Image( + value=Image.open(demo_imgs[0][1]) + ) + demo_text_two = gr.Textbox( + value=demo_texts[0][1], label="Demonstration sample 2", lines=2 + ) + with gr.Column(scale=1): + query_image = gr.Image(type="pil") + text_output = gr.Textbox(value="Output:", label="Model output") + + run_btn = gr.Button("Run model") + + def on_click_fn(img): return generate(0, img, "", tc=read_tc) + run_btn.click(on_click_fn, inputs=[query_image], outputs=[text_output]) + + with gr.Tab("🔢 Counting objects"): + with gr.Row(): + with gr.Column(scale=1): + demo_image_one = gr.Image( + value=Image.open(demo_imgs[4][0]) + ) + demo_text_one = gr.Textbox( + value=demo_texts[4][0], label="Demonstration sample 1", lines=2 + ) + with gr.Column(scale=1): + demo_image_two = gr.Image( + value=Image.open(demo_imgs[4][1]) + ) + demo_text_two = gr.Textbox( + value=demo_texts[4][1], label="Demonstration sample 2", lines=2 + ) + with gr.Column(scale=1): + query_image = gr.Image(type="pil") + text_output = gr.Textbox(value="Output:", label="Model output") + + run_btn = gr.Button("Run model") + + def on_click_fn(img): return generate(4, img, "", tc=read_tc) + run_btn.click(on_click_fn, inputs=[query_image], outputs=[text_output]) + + with gr.Tab("🕵️ Visual Question Answering"): + with gr.Row(): + with gr.Column(scale=1): + demo_image_one = gr.Image( + value=Image.open(demo_imgs[2][0]) + ) + demo_text_one = gr.Textbox( + value=demo_texts[2][0], label="Demonstration sample 1", lines=2 + ) + with gr.Column(scale=1): + demo_image_two = gr.Image( + value=Image.open(demo_imgs[2][1]) + ) + demo_text_two = gr.Textbox( + value=demo_texts[2][1], label="Demonstration sample 2", lines=2 + ) + with gr.Column(scale=1): + query_image = gr.Image(type="pil") + question = gr.Textbox( + label="Question: (e.g. 'What is the color of the object?' without \"Question:\" prefix)" + ) + text_output = gr.Textbox(value="", label="Model output") + + run_btn = gr.Button("Run model") + def on_click_fn(img, txt): return generate(2, img, txt, tc=read_tc) + run_btn.click( + on_click_fn, inputs=[query_image, question], outputs=[text_output] + ) + + with gr.Tab("🌎 Custom"): + gr.Markdown( + """### Customize the demonstration by uploading your own images and text samples. + ### **Note: Any text prompt you use will be prepended with an 'Output:', so you don't need to include it in your prompt.**""" + ) + with gr.Row(): + with gr.Column(scale=1): + demo_image_one = gr.Image(type="pil") + demo_text_one = gr.Textbox( + label="Demonstration sample 1", lines=2) + with gr.Column(scale=1): + demo_image_two = gr.Image(type="pil") + demo_text_two = gr.Textbox( + label="Demonstration sample 2", lines=2) + with gr.Column(scale=1): + query_image = gr.Image(type="pil") + text_output = gr.Textbox(value="Output:", label="Model output") + + run_btn = gr.Button("Run model") + + def on_click_fn(img, example_img_1, example_txt_1, example_img_2, example_txt_2): return generate( + -1, img, "", example_img_1, example_txt_1, example_img_2, example_txt_2, tc=read_tc + ) + run_btn.click( + on_click_fn, + inputs=[ + query_image, + demo_image_one, + demo_text_one, + demo_image_two, + demo_text_two, + ], + outputs=[text_output], + ) + +demo.queue(concurrency_count=1) +demo.launch() diff --git a/istockphoto-622434332-1024x1024.jpg b/istockphoto-622434332-1024x1024.jpg new file mode 100644 index 0000000000000000000000000000000000000000..f0cd9539dc35783ef2db84827a95aa278e6d4a82 Binary files /dev/null and b/istockphoto-622434332-1024x1024.jpg differ diff --git a/open_flamingo/.DS_Store b/open_flamingo/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..06d29533fadb19f6fe30e49ef6f111408397a6f4 Binary files /dev/null and b/open_flamingo/.DS_Store differ diff --git a/open_flamingo/.github/workflows/black.yml b/open_flamingo/.github/workflows/black.yml new file mode 100644 index 0000000000000000000000000000000000000000..b04fb15cb2d92d449b133ffd1c8fbf4baa621a7b --- /dev/null +++ b/open_flamingo/.github/workflows/black.yml @@ -0,0 +1,10 @@ +name: Lint + +on: [push, pull_request] + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: psf/black@stable diff --git a/open_flamingo/.gitignore b/open_flamingo/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..72a4f7921c777fe253c4a242eaf2b108458f1f22 --- /dev/null +++ b/open_flamingo/.gitignore @@ -0,0 +1,141 @@ +*.pt +*.json + +wandb/ + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Pycharm project settings +.idea + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +*.out +src/wandb +wandb + +# Pyre type checker +.pyre/ diff --git a/open_flamingo/HISTORY.md b/open_flamingo/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..f32b7294df489eb87c0d520ea58c555a492ed872 --- /dev/null +++ b/open_flamingo/HISTORY.md @@ -0,0 +1,15 @@ +## 2.0.0 +* Add gradient checkpointing, FullyShardedDataParallel +* Model releases + * (CLIP ViT-L-14 / MPT-1B) + * (CLIP ViT-L-14 / MPT-1B Dolly) + * (CLIP ViT-L-14 / RedPajama-3B) + * (CLIP ViT-L-14 / RedPajama-3B Instruct) + * (CLIP ViT-L-14 / MPT-7B) +* Remove color jitter when training +* Fix cross-attention bug when calling generate() + +## 1.0.0 + +* Initial code release +* Early model release (CLIP ViT-L-14 / LLaMA-7B) \ No newline at end of file diff --git a/open_flamingo/LICENSE b/open_flamingo/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..206be3ebbf3a41276af664447106615b0a954814 --- /dev/null +++ b/open_flamingo/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Anas Awadalla, Irena Gao, Joshua Gardner, Jack Hessel, Yusuf Hanafy, Wanrong Zhu, Kalyani Marathe, Yonatan Bitton, Samir Gadre, Jenia Jitsev, Simon Kornblith, Pang Wei Koh, Gabriel Ilharco, Mitchell Wortsman, Ludwig Schmidt. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/open_flamingo/Makefile b/open_flamingo/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..d5cc3840bce9ce0e5aebc435f63ffa5b534d4a8f --- /dev/null +++ b/open_flamingo/Makefile @@ -0,0 +1,19 @@ +install: ## [Local development] Upgrade pip, install requirements, install package. + python -m pip install -U pip + python -m pip install -e . + +install-dev: ## [Local development] Install test requirements + python -m pip install -r requirements-test.txt + +lint: ## [Local development] Run mypy, pylint and black + python -m mypy open_flamingo + python -m pylint open_flamingo + python -m black --check -l 120 open_flamingo + +black: ## [Local development] Auto-format python code using black + python -m black -l 120 . + +.PHONY: help + +help: # Run `make help` to get help on the make commands + @grep -E '^[0-9a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' \ No newline at end of file diff --git a/open_flamingo/README.md b/open_flamingo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b00fbff18bfc774501740b2af17d7f9d710f2cd4 --- /dev/null +++ b/open_flamingo/README.md @@ -0,0 +1,247 @@ +# 🦩 OpenFlamingo + +[![PyPI version](https://badge.fury.io/py/open_flamingo.svg)](https://badge.fury.io/py/open_flamingo) + +Blog posts: [1](https://laion.ai/blog/open-flamingo/), [2]() | Paper (coming soon) + +Welcome to our open source implementation of DeepMind's [Flamingo](https://www.deepmind.com/blog/tackling-multiple-tasks-with-a-single-visual-language-model)! + +In this repository, we provide a PyTorch implementation for training and evaluating OpenFlamingo models. +If you have any questions, please feel free to open an issue. We also welcome contributions! + +# Table of Contents +- [Installation](#installation) +- [Approach](#approach) + * [Model architecture](#model-architecture) +- [Usage](#usage) + * [Initializing an OpenFlamingo model](#initializing-an-openflamingo-model) + * [Generating text](#generating-text) +- [Training](#training) + * [Dataset](#dataset) +- [Evaluation](#evaluation) +- [Future plans](#future-plans) +- [Team](#team) +- [Acknowledgments](#acknowledgments) +- [Citing](#citing) + +# Installation + +To install the package in an existing environment, run +``` +pip install open-flamingo +``` + +or to create a conda environment for running OpenFlamingo, run +``` +conda env create -f environment.yml +``` + +# Approach +OpenFlamingo is a multimodal language model that can be used for a variety of tasks. It is trained on a large multimodal dataset (e.g. Multimodal C4) and can be used to generate text conditioned on interleaved images/text. For example, OpenFlamingo can be used to generate a caption for an image, or to generate a question given an image and a text passage. The benefit of this approach is that we are able to rapidly adapt to new tasks using in-context learning. + +## Model architecture +OpenFlamingo combines a pretrained vision encoder and a language model using cross attention layers. The model architecture is shown below. + +![OpenFlamingo architecture](docs/flamingo.png) +Credit: [Flamingo](https://www.deepmind.com/blog/tackling-multiple-tasks-with-a-single-visual-language-model) + +# Usage +## Initializing an OpenFlamingo model +We support pretrained vision encoders from the [OpenCLIP](https://github.com/mlfoundations/open_clip) package, which includes OpenAI's pretrained models. +We also support pretrained language models from the `transformers` package, such as [MPT](https://huggingface.co/models?search=mosaicml%20mpt), [RedPajama](https://huggingface.co/models?search=redpajama), [LLaMA](https://huggingface.co/models?search=llama), [OPT](https://huggingface.co/models?search=opt), [GPT-Neo](https://huggingface.co/models?search=gpt-neo), [GPT-J](https://huggingface.co/models?search=gptj), and [Pythia](https://huggingface.co/models?search=pythia) models. + +``` python +from open_flamingo import create_model_and_transforms + +model, image_processor, tokenizer = create_model_and_transforms( + clip_vision_encoder_path="ViT-L-14", + clip_vision_encoder_pretrained="openai", + lang_encoder_path="anas-awadalla/mpt-1b-redpajama-200b", + tokenizer_path="anas-awadalla/mpt-1b-redpajama-200b", + cross_attn_every_n_layers=1 +) +``` + +## Released OpenFlamingo models +We have trained the following OpenFlamingo models so far. + +|# params|Language model|Vision encoder|Xattn frequency*|COCO 4-shot CIDEr**|VQAv2 4-shot Accuracy**|Weights| +|------------|--------------|--------------|----------|-----------|-------|----| +|3B| mosaicml/mpt-1b-redpajama-200b | openai CLIP ViT-L/14 | 1 | - | - |[Link](https://huggingface.co/openflamingo/OpenFlamingo-3B-vitl-mpt1b)| +|3B| mosaicml/mpt-1b-redpajama-200b-dolly | openai CLIP ViT-L/14 | 1 | 82.7 | - |[Link](https://huggingface.co/openflamingo/OpenFlamingo-3B-vitl-mpt1b-langinstruct)| +|4B| togethercomputer/RedPajama-INCITE-Base-3B-v1 | openai CLIP ViT-L/14 | 2 | 81.8 | -| [Link](https://huggingface.co/openflamingo/OpenFlamingo-4B-vitl-rpj3b)| +|4B| togethercomputer/RedPajama-INCITE-Instruct-3B-v1 | openai CLIP ViT-L/14 | 2 | 85.8 | - | [Link](https://huggingface.co/openflamingo/OpenFlamingo-4B-vitl-rpj3b-langinstruct)| +|9B| mosaicml/mpt-7b | openai CLIP ViT-L/14 | 4 | 89.0 | - | [Link](https://huggingface.co/openflamingo/OpenFlamingo-9B-vitl-mpt7b)| + +*\* Xattn frequency refers to the `--cross_attn_every_n_layers` argument.* + +*\*\* 4-shot COCO and VQAv2 performances were calculated over a sample of 5000 test split examples, following the [Flamingo paper](https://arxiv.org/abs/2204.14198).* + +Note: as part of our v2 release, we have deprecated a previous LLaMA-based checkpoint. However, you can continue to use our older checkpoint using the new codebase. + +## Downloading pretrained weights + +To instantiate an OpenFlamingo model with one of our released weights, initialize the model as above and use the following code. + +```python +# grab model checkpoint from huggingface hub +from huggingface_hub import hf_hub_download +import torch + +checkpoint_path = hf_hub_download("openflamingo/OpenFlamingo-3B-vitl-mpt1b", "checkpoint.pt") +model.load_state_dict(torch.load(checkpoint_path), strict=False) +``` + +## Generating text +Below is an example of generating text conditioned on interleaved images/text. In particular, let's try few-shot image captioning. + +``` python +from PIL import Image +import requests + +""" +Step 1: Load images +""" +demo_image_one = Image.open( + requests.get( + "http://images.cocodataset.org/val2017/000000039769.jpg", stream=True + ).raw +) + +demo_image_two = Image.open( + requests.get( + "http://images.cocodataset.org/test-stuff2017/000000028137.jpg", + stream=True + ).raw +) + +query_image = Image.open( + requests.get( + "http://images.cocodataset.org/test-stuff2017/000000028352.jpg", + stream=True + ).raw +) + + +""" +Step 2: Preprocessing images +Details: For OpenFlamingo, we expect the image to be a torch tensor of shape + batch_size x num_media x num_frames x channels x height x width. + In this case batch_size = 1, num_media = 3, num_frames = 1, + channels = 3, height = 224, width = 224. +""" +vision_x = [image_processor(demo_image_one).unsqueeze(0), image_processor(demo_image_two).unsqueeze(0), image_processor(query_image).unsqueeze(0)] +vision_x = torch.cat(vision_x, dim=0) +vision_x = vision_x.unsqueeze(1).unsqueeze(0) + +""" +Step 3: Preprocessing text +Details: In the text we expect an special token to indicate where an image is. + We also expect an <|endofchunk|> special token to indicate the end of the text + portion associated with an image. +""" +tokenizer.padding_side = "left" # For generation padding tokens should be on the left +lang_x = tokenizer( + ["An image of two cats.<|endofchunk|>An image of a bathroom sink.<|endofchunk|>An image of"], + return_tensors="pt", +) + + +""" +Step 4: Generate text +""" +generated_text = model.generate( + vision_x=vision_x, + lang_x=lang_x["input_ids"], + attention_mask=lang_x["attention_mask"], + max_new_tokens=20, + num_beams=3, +) + +print("Generated text: ", tokenizer.decode(generated_text[0])) +``` + +# Training +We provide training scripts in `open_flamingo/train`. We provide an example Slurm script in `open_flamingo/scripts/run_train.py`, as well as the following example command: +``` +torchrun --nnodes=1 --nproc_per_node=4 open_flamingo/train/train.py \ + --lm_path anas-awadalla/mpt-1b-redpajama-200b \ + --tokenizer_path anas-awadalla/mpt-1b-redpajama-200b \ + --cross_attn_every_n_layers 1 \ + --dataset_resampled \ + --batch_size_mmc4 32 \ + --batch_size_laion 64 \ + --train_num_samples_mmc4 125000\ + --train_num_samples_laion 250000 \ + --loss_multiplier_laion 0.2 \ + --workers=4 \ + --run_name OpenFlamingo-3B-vitl-mpt1b \ + --num_epochs 480 \ + --warmup_steps 1875 \ + --mmc4_textsim_threshold 0.24 \ + --laion_shards "/path/to/shards/shard-{0000..0999}.tar" \ + --mmc4_shards "/path/to/shards/shard-{0000..0999}.tar" \ + --report_to_wandb +``` + +*Note: The MPT-1B [base](https://huggingface.co/mosaicml/mpt-1b-redpajama-200b) and [instruct](https://huggingface.co/mosaicml/mpt-1b-redpajama-200b-dolly) modeling code does not accept the `labels` kwarg or compute cross-entropy loss directly within `forward()`, as expected by our codebase. We suggest using a modified version of the MPT-1B models found [here](https://huggingface.co/anas-awadalla/mpt-1b-redpajama-200b) and [here](https://huggingface.co/anas-awadalla/mpt-1b-redpajama-200b-dolly).* + +For more details, see our [training README](https://github.com/mlfoundations/open_flamingo/tree/main/open_flamingo/train). + + +# Evaluation +An example evaluation script is at `open_flamingo/scripts/run_eval.sh`. Please see our [evaluation README](https://github.com/mlfoundations/open_flamingo/tree/main/open_flamingo/eval) for more details. + +Before evaluating the model, you will need to install the coco evaluation package by running the following command: +``` +pip install pycocoevalcap +``` + +To run evaluations on OKVQA you will need to run the following command: +``` +import nltk +nltk.download('wordnet') +``` + + +# Future plans +- [ ] Add support for video input + +# Team + +OpenFlamingo is developed by: + +[Anas Awadalla*](https://anas-awadalla.streamlit.app/), [Irena Gao*](https://i-gao.github.io/), [Joshua Gardner](https://homes.cs.washington.edu/~jpgard/), [Jack Hessel](https://jmhessel.com/), [Yusuf Hanafy](https://www.linkedin.com/in/yusufhanafy/), [Wanrong Zhu](https://wanrong-zhu.com/), [Kalyani Marathe](https://sites.google.com/uw.edu/kalyanimarathe/home?authuser=0), [Yonatan Bitton](https://yonatanbitton.github.io/), [Samir Gadre](https://sagadre.github.io/), [Shiori Sagawa](https://cs.stanford.edu/~ssagawa/), [Jenia Jitsev](https://scholar.google.de/citations?user=p1FuAMkAAAAJ&hl=en), [Simon Kornblith](https://simonster.com/), [Pang Wei Koh](https://koh.pw/), [Gabriel Ilharco](https://gabrielilharco.com/), [Mitchell Wortsman](https://mitchellnw.github.io/), [Ludwig Schmidt](https://people.csail.mit.edu/ludwigs/). + +The team is primarily from the University of Washington, Stanford, AI2, UCSB, and Google. + +# Acknowledgments +This code is based on Lucidrains' [flamingo implementation](https://github.com/lucidrains/flamingo-pytorch) and David Hansmair's [flamingo-mini repo](https://github.com/dhansmair/flamingo-mini). Thank you for making your code public! We also thank the [OpenCLIP](https://github.com/mlfoundations/open_clip) team as we use their data loading code and take inspiration from their library design. + +We would also like to thank [Jean-Baptiste Alayrac](https://www.jbalayrac.com) and [Antoine Miech](https://antoine77340.github.io) for their advice, [Rohan Taori](https://www.rohantaori.com/), [Nicholas Schiefer](https://nicholasschiefer.com/), [Deep Ganguli](https://hai.stanford.edu/people/deep-ganguli), [Thomas Liao](https://thomasliao.com/), [Tatsunori Hashimoto](https://thashim.github.io/), and [Nicholas Carlini](https://nicholas.carlini.com/) for their help with assessing the safety risks of our release, and to [Stability AI](https://stability.ai) for providing us with compute resources to train these models. + +# Citing +If you found this repository useful, please consider citing: + +``` +@software{anas_awadalla_2023_7733589, + author = {Awadalla, Anas and Gao, Irena and Gardner, Joshua and Hessel, Jack and Hanafy, Yusuf and Zhu, Wanrong and Marathe, Kalyani and Bitton, Yonatan and Gadre, Samir and Jitsev, Jenia and Kornblith, Simon and Koh, Pang Wei and Ilharco, Gabriel and Wortsman, Mitchell and Schmidt, Ludwig}, + title = {OpenFlamingo}, + month = mar, + year = 2023, + publisher = {Zenodo}, + version = {v0.1.1}, + doi = {10.5281/zenodo.7733589}, + url = {https://doi.org/10.5281/zenodo.7733589} +} +``` + +``` +@article{Alayrac2022FlamingoAV, + title={Flamingo: a Visual Language Model for Few-Shot Learning}, + author={Jean-Baptiste Alayrac and Jeff Donahue and Pauline Luc and Antoine Miech and Iain Barr and Yana Hasson and Karel Lenc and Arthur Mensch and Katie Millican and Malcolm Reynolds and Roman Ring and Eliza Rutherford and Serkan Cabi and Tengda Han and Zhitao Gong and Sina Samangooei and Marianne Monteiro and Jacob Menick and Sebastian Borgeaud and Andy Brock and Aida Nematzadeh and Sahand Sharifzadeh and Mikolaj Binkowski and Ricardo Barreira and Oriol Vinyals and Andrew Zisserman and Karen Simonyan}, + journal={ArXiv}, + year={2022}, + volume={abs/2204.14198} +} +``` diff --git a/open_flamingo/TERMS_AND_CONDITIONS.md b/open_flamingo/TERMS_AND_CONDITIONS.md new file mode 100644 index 0000000000000000000000000000000000000000..3571e77642db32609a56ebf010b2445dd71f6a74 --- /dev/null +++ b/open_flamingo/TERMS_AND_CONDITIONS.md @@ -0,0 +1,15 @@ +**Please read the following information carefully before proceeding.** + +OpenFlamingo is a **research prototype** that aims to enable users to interact with AI through both language and images. AI agents equipped with both language and visual understanding can be useful on a larger variety of tasks compared to models that communicate solely via language. By releasing an open-source research prototype, we hope to help the research community better understand the risks and limitations of modern visual-language AI models and accelerate the development of safer and more reliable methods. + +- [ ] I understand that OpenFlamingo is a research prototype and I will only use it for non-commercial research purposes. + +**Limitations.** OpenFlamingo is built on top of the LLaMA large language model developed by Meta AI. Large language models, including LLaMA, are trained on mostly unfiltered internet data, and have been shown to be able to produce toxic, unethical, inaccurate, and harmful content. On top of this, OpenFlamingo’s ability to support visual inputs creates additional risks, since it can be used in a wider variety of applications; image+text models may carry additional risks specific to multimodality. Please use discretion when assessing the accuracy or appropriateness of the model’s outputs, and be mindful before sharing its results. + +- [ ] I understand that OpenFlamingo may produce unintended, inappropriate, offensive, and/or inaccurate results. I agree to take full responsibility for any use of the OpenFlamingo outputs that I generate. + +**Privacy and data collection.** This demo does NOT store any personal information on its users, and it does NOT store user queries. + +**Licensing.** As OpenFlamingo is built on top of the LLaMA large language model from Meta AI, the LLaMA license agreement (as documented in the Meta request form) also applies. + +- [ ] I have read and agree to the terms of the LLaMA license agreement. diff --git a/open_flamingo/_optim_utils.py b/open_flamingo/_optim_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4b61c1d0dd2594436914b1d3290bbeff09107a2f --- /dev/null +++ b/open_flamingo/_optim_utils.py @@ -0,0 +1,1741 @@ +import copy +import functools +import warnings +from dataclasses import dataclass +from typing import ( + Any, + cast, + Dict, + Iterable, + Iterator, + List, + NamedTuple, + Optional, + Sequence, + Set, + Tuple, + Union, +) + +import torch +import torch.distributed as dist +import torch.distributed.fsdp._traversal_utils as traversal_utils +import torch.nn as nn +from torch.distributed._shard.sharded_tensor import ShardedTensor +from torch.distributed.fsdp._common_utils import ( + _apply_to_modules, + _FSDPState, + _get_module_fsdp_state_if_fully_sharded_module, + _get_param_to_fqns, + _module_handles, + clean_tensor_name, +) +from torch.distributed.fsdp._fsdp_extensions import _ext_chunk_tensor +from torch.distributed.fsdp._runtime_utils import _clear_grads_if_needed, _lazy_init +from torch.distributed.fsdp._shard_utils import _gather_state_dict +from torch.distributed.fsdp.api import ShardingStrategy +from torch.distributed.fsdp.flat_param import FlatParameter, FlatParamHandle + + +@dataclass +class FSDPParamInfo: + state: _FSDPState + flat_param: FlatParameter + param_indices: Dict[str, int] + + +def sorted_items(dictionary: Dict[str, Any]) -> Iterator[Tuple[str, Any]]: + keys = sorted(dictionary.keys()) + for k in keys: + yield k, dictionary[k] + + +class _ConsolidatedOptimState: + """ + This holds the consolidated optimizer state on the target rank. Positive- + dimension tensor state is communicated across ranks, while zero-dimension + tensor state and non-tensor state is taken directly from the target rank. + + PyTorch version 1.12 moved to using zero-dimension tensors for scalar + values, but user implemented optimizers may still use float (i.e. a + non-tensor). Thus, we support both and handle them identically. + + Attributes: + tensor_state (Dict[str, torch.Tensor]): Mapping from positive-dimension + tensor state name to the unsharded flattened tensor representing + the state. + zero_dim_tensor_state (Dict[str, torch.Tensor]): Mapping from zero- + dimension tensor state name to its value. + non_tensor_state (Dict[str, Any]): Mapping from non-tensor state + name to its value. + """ + + tensor_state: Dict[str, torch.Tensor] = {} + zero_dim_tensor_state: Dict[str, torch.Tensor] = {} + non_tensor_state: Dict[str, Any] = {} + + +class _PosDimTensorInfo(NamedTuple): + """ + Meatadata for positive-dimension tensors used internally for + :meth:`scatter_full_optim_state_dict`. + + Attributes: + shape (torch.Size): Sharded tensor shape (which is equal to the + unsharded tensor shape if the tensor is optimizer state for a + non-FSDP parameter and is hence not sharded). + dtype (torch.dtype): Data type of the tensor. + """ + + shape: torch.Size + dtype: torch.dtype + + +class _OptimStateKey(NamedTuple): + """ + This represents an optimizer state key that may be used commonly across + ranks. It is based on the unflattened parameter names rather than parameter + IDs to make it indepenendent of each rank's own optimizer construction. + """ + + unflat_param_names: Tuple[str, ...] + is_fsdp_managed: bool + + +def _unflatten_optim_state( + fsdp_param_info: FSDPParamInfo, + flat_param_state: Dict[str, Any], + to_save: bool, + shard_state: bool, +) -> List[Dict[str, Any]]: + """ + Unflattens the optimizer state, consisting of the "state" part and the + "param_groups" part. Unflattening the "state" part involves consolidating + the state on the target rank and remapping from flattened to unflattened + parameter IDs, and the "param_groups" part only involves remapping from + flattened to unflattened parameter IDs. + + Args: + fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten + parameter. + flat_param_state (Dict[str, Any]): Entry for the flattened parameter + in the "state" part of the optimizer state dict. + to_save (bool): Whether to save the state on this rank. + + Returns: + List[Dict[str, Any]]: A :class:`list` holding the entries in the + "state" part of the optimizer state dict corresponding to the + unflattened parameters comprising the flattened parameter if on the + target rank or an empty :class:`list` otherwise. The final optimizer + state dict will need to map these entries using the proper unflattened + parameter IDs. + """ + assert ( + not shard_state or to_save + ), "If ``shard_state`` is True, ``to_save`` has to be True." + consolidated_state = _communicate_optim_state( + fsdp_param_info, + flat_param_state, + ) + if to_save: + unflat_param_state = _unflatten_communicated_optim_state( + fsdp_param_info, + consolidated_state, + shard_state, + ) + for optim_state in unflat_param_state: + for key in list(optim_state.keys()): + state = optim_state[key] + if isinstance(state, torch.Tensor): + optim_state[key] = state.cpu() + return unflat_param_state + else: + return [] + + +def _is_zero_dim_tensor(x: Any) -> bool: + return torch.is_tensor(x) and x.dim() == 0 + + +def _communicate_optim_state( + fsdp_param_info: FSDPParamInfo, + flat_param_state: Dict[str, Any], +) -> _ConsolidatedOptimState: + """ + Communicates the optimizer state for a flattened parameter across ranks. + All ranks will hold the entire non-sharded optimizer state on GPU. + + If ``N`` is the number of tensor optimizer states in the optimizer state + dict, then the communication complexity is 0 if ``N = 0`` and ``N + 1`` + otherwise (where the plus 1 comes from all-gathering the padding per rank). + + Args: + fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten + parameter. + flat_param_state (Dict[str, Any]): The entry in the "state" part of the + optimizer state dict corresponding to the flattened parameter. + + Returns: + ConsolidatedOptimState: Consolidated optimizer state for the target + flattened parameter. + """ + fsdp_state = fsdp_param_info.state + flat_param = fsdp_param_info.flat_param + state = _ConsolidatedOptimState() + tensor_state, zero_dim_tensor_state, non_tensor_state = ( + state.tensor_state, + state.zero_dim_tensor_state, + state.non_tensor_state, + ) + + for state_name, value in sorted_items(flat_param_state): + # Positive-dimension tensor state: communicate across ranks + if torch.is_tensor(value) and value.dim() > 0: + # If the parameter is not sharded, then neither is the + # positive-dimension tensor state, so no need to communicate it -- + # we take the target rank's value + if ( + fsdp_state.world_size == 1 + or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD + ): + tensor_state[state_name] = value + continue + if not value.is_cuda: + value = value.to(fsdp_state.compute_device) + # Assume that positive-dimension tensor optimizer state + # has the same shape as the sharded flattened parameter + buffer_size = flat_param._full_param_padded.size() # type: ignore[attr-defined] + tensor_buffer = value.new_zeros(*buffer_size) + dist.all_gather_into_tensor( + tensor_buffer, value, group=fsdp_state.process_group + ) + torch.cuda.synchronize() + unpadded_numel = cast( + nn.Parameter, flat_param._unpadded_unsharded_size + ).numel() + tensor_state[state_name] = tensor_buffer[:unpadded_numel] + # Zero-dimension tensor state and non-tensor state: take this rank's + # value directly + else: + if _is_zero_dim_tensor(value): + zero_dim_tensor_state[state_name] = value + else: + non_tensor_state[state_name] = value + return state + + +def _unflatten_communicated_optim_state( + fsdp_param_info: FSDPParamInfo, + state: _ConsolidatedOptimState, + shard_state: bool, +) -> List[Dict[str, Any]]: + """ + Unflattens the communicated optimizer state (given by ``tensor_state``, + ``non_tensor_state``, and ``zero_dim_tensor_state``) for a single flattened + parameter. This should only be called on the target rank. + + Args: + fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten + parameter. + state (_ConsolidatedOptimState): Consolidated optimizer state. + + Returns: + List[Dict[str, Any]]: A :class:`list` holding the entries in the + "state" part of the optimizer state dict corresponding to the + unflattened parameters comprising the flattened parameter. The final + optimizer state dict will need to map these entries using the proper + unflattened parameter IDs. + """ + fsdp_state = fsdp_param_info.state + flat_param = fsdp_param_info.flat_param + unflat_param_state: List[Dict[str, Any]] = [] + flat_param_views: Dict[str, Iterator] = {} + num_unflat_params = flat_param._num_params + tensor_state, zero_dim_tensor_state, non_tensor_state = ( + state.tensor_state, + state.zero_dim_tensor_state, + state.non_tensor_state, + ) + + for _ in range(num_unflat_params): + unflat_state_param = {} + # Add positive-dimension tensor state: unflatten with views + for state_name, flat_tensor in sorted_items(tensor_state): + views_generated = state_name in flat_param_views + if not views_generated: + views = FlatParamHandle._get_unflat_views(flat_param, flat_tensor) + flat_param_views[state_name] = views + else: + views = flat_param_views[state_name] + optim_state: Union[torch.Tensor, ShardedTensor] = next(views) + if shard_state: + assert fsdp_state.process_group is not None + optim_state = _ext_chunk_tensor( + optim_state, + fsdp_state.rank, + fsdp_state.world_size, + torch.cuda.device_count(), + fsdp_state.process_group, + ) + unflat_state_param[state_name] = optim_state + + # Add zero-dimension tensor state: take the target rank's value + for state_name, zero_dim_tensor in sorted_items(zero_dim_tensor_state): + unflat_state_param[state_name] = zero_dim_tensor + # Add non-tensor state: take the target rank's value + for state_name, non_tensor in sorted_items(non_tensor_state): + unflat_state_param[state_name] = non_tensor + unflat_param_state.append(unflat_state_param) + return unflat_param_state + + +def _flatten_optim_state_dict( + optim_state_dict: Dict[str, Any], + model: nn.Module, + shard_state: bool, + use_orig_params: bool = False, + optim: Optional[torch.optim.Optimizer] = None, +) -> Dict[str, Any]: + """ + Flattens the full optimizer state dict, still keying by unflattened + parameter names. If ``shard_state=True``, then FSDP-managed + ``FlatParameter`` 's optimizer states are sharded, and otherwise, they are + kept unsharded. + + If ``use_orig_params`` is True, each rank will have all FSDP-managed + parameters but some of these parameters may be empty due to the sharding. + For a regular optim.Optimizer, states for those empty parameters will + not be initialized. So, when aggregating the FQNs across ranks, no assert + will be raised on a rank even if it does not have all the states -- it is + valid and FSDP know how to aggregate them. However, FSDP has to ignore + handling those parameters that are not managed by FSDP and do not exist on + the local rank -- it is managed by other parallelism and FSDP does not + know ho to handle/aggregate them. + + Note that ``_flatten_tensor_optim_state`` does not need ``optim`` to + flatten/shard the state. However, NamedOptimizer and KeyedOptimizer require + all the states even if the corresponding parameters are empty. To this end, + ``optim`` will be used to to get the initial state of the empty parameters. + ``optim`` should only be non-None if the ``optim` is KeyedOptimizer or + NamedOptimizer. + + Returns: + Dict[str, Any]: The flattened optimizer state dict. + """ + unflat_osd = optim_state_dict + if "state" not in unflat_osd or "param_groups" not in unflat_osd: + raise ValueError( + '`optim_state_dict` must have the keys "state" and ' + '"param_groups" to be a valid optimizer state dict' + ) + param_to_fqns = _get_param_to_fqns(model) + fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model) + + # Construct the "state" part + flat_osd_state: Dict[Union[_OptimStateKey, str], Any] = {} + unflat_osd_state = unflat_osd["state"] + all_state_keys = set(unflat_osd_state.keys()) + + # local_state_dict is used to construct states of empty parameters. + # This should only be used if is_named_optimizer=True. + local_state_dict: Dict[str, Any] = {} + local_state_clean_fqns: Dict[str, str] = {} + if optim is not None: + local_state_dict = optim.state_dict()["state"] + for fqn in local_state_dict.keys(): + clean_fqn = clean_tensor_name(fqn) + local_state_clean_fqns[clean_fqn] = fqn + + for param, unflat_param_names in param_to_fqns.items(): + fqn = unflat_param_names[0] + if fqn not in unflat_osd_state: + continue + all_state_keys.difference_update(unflat_param_names) + if fqn in fqn_to_fsdp_param_info: + fsdp_param_info = fqn_to_fsdp_param_info[fqn] + if use_orig_params: + assert ( + shard_state + ), "If use_orig_params is True, shard_state must be True." + flat_state = _shard_orig_param_state( + fsdp_param_info, + fqn, + unflat_osd_state[fqn], + ) + else: + flat_state = _flatten_optim_state( + fsdp_param_info, + unflat_osd_state, + unflat_param_names, + shard_state, + ) + key = _OptimStateKey(tuple(unflat_param_names), True) + # Only include non-empty states since as expected by + # `torch.optim.Optimizer` s unless the optimizer is KeyedOptimizer + # or NamedOptimizer. + if flat_state: + flat_osd_state[key] = flat_state + elif optim is not None: # NamedOptimizer or KeyedOptimizer case. + assert len(unflat_param_names) == 1 + local_wrapped_fqn = local_state_clean_fqns.get(fqn, "") + if local_wrapped_fqn: + flat_osd_state[key] = copy.deepcopy( + local_state_dict[local_wrapped_fqn] + ) + else: # do not flatten non-FSDP parameters' states + assert len(unflat_param_names) == 1 + key = _OptimStateKey(tuple(unflat_param_names), False) + flat_osd_state[key] = copy.copy(unflat_osd_state[fqn]) + + # Handle user-defined state, states that are not accosiated with parameters. + for key in all_state_keys: + flat_osd_state[key] = copy.copy(unflat_osd_state[key]) + + # Construct the "param_groups" part -- copy as is since it will be + # rekeyed later according to the target rank's optimizer + flat_osd_param_groups = copy.deepcopy(unflat_osd["param_groups"]) + return {"state": flat_osd_state, "param_groups": flat_osd_param_groups} + + +def _flatten_optim_state( + fsdp_param_info: FSDPParamInfo, + unflat_osd_state: Dict[str, Dict[str, Any]], + unflat_param_names: List[str], + shard_state: bool, +) -> Dict[str, Any]: + """ + Flattens the optimizer state in ``full_optim_state_dict`` for a single + flattened parameter in ``fsdp_param_info`` corresponding to the unflattened + parameter names in ``unflat_param_names``. + + Args: + unflat_osd_state (Dict[str, Dict[str, Any]]): The "state" part of the + optimizer state dict corresponding to the unflattened parameters. + unflat_param_names (List[str]): A :class:`list` of unflattened + parameter names corresponding to the flattened parameter + ``flat_param``. + fsdp_param_info (FSDPParamInfo): The fsdp state and the target flatten + parameter. + shard_state (bool): Whether to shard flattened positive-dimension + tensor state; if ``False``, then the full flattened tensor is + kept in the returned :class:`dict. + + Returns: + Dict[str, Any]: A :class:`dict` mapping state names to their values for + a particular flattened parameter. The sharded optimizer state dict's + "state" part will map a key to this returned value. + """ + fsdp_state = fsdp_param_info.state + flat_param = fsdp_param_info.flat_param + num_unflat_params = len(unflat_param_names) + assert num_unflat_params > 0, ( + "Expects at least one unflattened parameter corresponding to the " + "flattened parameter" + ) + unflat_param_shapes = flat_param._shapes + num_unflat_param_shapes = len(unflat_param_shapes) + assert ( + num_unflat_params == num_unflat_param_shapes + ), f"Expects {num_unflat_params} shapes but got {num_unflat_param_shapes}" + + # Check if these unflattened parameters have any optimizer state + has_state = [ + bool(unflat_param_name in unflat_osd_state) + for unflat_param_name in unflat_param_names + ] + # If none of the unflattened parameters comprising this flattened parameter + # have any state, then we do not want an entry in the optimizer state dict + if not any(has_state): + return {} # no need to flatten any state + # There may still be some unflattened parameters with state and some + # without + unflat_param_states = [ + _gather_state_dict( + unflat_osd_state[unflat_param_name], pg=fsdp_state.process_group + ) + if unflat_param_name in unflat_osd_state + else None + for unflat_param_name in unflat_param_names + ] + # Check that the unflattened parameters have the same state names + state_names = None + for unflat_param_state in unflat_param_states: + if unflat_param_state is None: + continue + if state_names is None: + state_names = set(unflat_param_state.keys()) + else: + if state_names != set(unflat_param_state.keys()): + raise ValueError( + "Differing optimizer state names for the unflattened " + f"parameters: {unflat_param_names}" + ) + assert state_names is not None + + # Flatten the state + flat_state: Dict[str, Any] = {} + for state_name in state_names: + state_values = [ + unflat_param_state[state_name] if unflat_param_state is not None else None + for unflat_param_state in unflat_param_states + ] + non_none_state_values = [v for v in state_values if v is not None] + are_pos_dim_tensors = are_zero_dim_tensors = are_non_tensors = True + for v in non_none_state_values: + are_pos_dim_tensors &= torch.is_tensor(v) and v.dim() > 0 + are_zero_dim_tensors &= _is_zero_dim_tensor(v) + are_non_tensors &= not torch.is_tensor(v) + types = {type(v) for v in non_none_state_values} + if len(types) != 1 or not ( + are_pos_dim_tensors or are_zero_dim_tensors or are_non_tensors + ): + raise ValueError( + f"Differing optimizer state types for state {state_name}, " + f"values {non_none_state_values}, and unflattened parameter " + f"names {unflat_param_names}" + ) + if are_pos_dim_tensors: + flat_tensor = _flatten_tensor_optim_state( + state_name, + state_values, + unflat_param_names, + unflat_param_shapes, + flat_param, + ) + if shard_state: + # Shard the flattened tensor immediately to minimize max memory + # usage + sharded_flat_tensor, _ = FlatParamHandle._get_shard( + flat_tensor, + fsdp_state.rank, + fsdp_state.world_size, + ) + flat_state[state_name] = sharded_flat_tensor + else: + flat_state[state_name] = flat_tensor + elif are_zero_dim_tensors: + flat_state[state_name] = _flatten_zero_dim_tensor_optim_state( + state_name, + state_values, + unflat_param_names, + ) + else: + assert are_non_tensors + flat_state[state_name] = _flatten_non_tensor_optim_state( + state_name, + state_values, + unflat_param_names, + ) + + return flat_state + + +def _flatten_tensor_optim_state( + state_name: str, + pos_dim_tensors: List[torch.Tensor], + unflat_param_names: List[str], + unflat_param_shapes: Sequence[torch.Size], + flat_param: FlatParameter, +) -> torch.Tensor: + """ + Flattens the positive-dimension tensor optimizer state given by the values + ``tensors`` for the state ``state_name`` for a single flattened parameter + ``flat_param`` corresponding to the unflattened parameter names + ``unflat_param_names`` and unflatted parameter shapes + ``unflat_param_shapes``. This flattens each unflattened parameter's tensor + state into one tensor. + + NOTE: We use zero tensors for any unflattened parameters without state + since some value is required to fill those entries. This assumes that the + zero tensor is mathematically equivalent to having no state, which is true + for Adam's "exp_avg" and "exp_avg_sq" but may not be true for all + optimizers. + + Args: + state_name (str): Optimizer state name. + pos_dim_tensors (List[torch.Tensor]): Positive-dimension tensor + optimizer state values for the unflattened parameters corresponding + to the single flattened parameter. + unflat_param_names (List[str]): A :class:`list` of unflattened + parameter names corresponding to the single flattened parameter. + unflat_param_shapes (List[torch.Size]): Unflattened parameter shapes + corresponding to the single flattened parameter. + flat_param (FlatParameter): The flattened parameter. + + Returns: + torch.Tensor: A flattened tensor containing the optimizer state + corresponding to ``state_name`` constructed by concatenating the + unflattened parameter tensor states in ``pos_dim_tensors`` (using zero + tensors for any unflattened parameters without the state). + """ + non_none_tensors = [t for t in pos_dim_tensors if t is not None] + # Check that all are tensors with the same dtype + dtypes = {t.dtype for t in non_none_tensors} + if len(dtypes) != 1: + raise ValueError( + "All unflattened parameters comprising a single flattened " + "parameter must have positive-dimension tensor state with the " + f"same dtype but got dtypes {dtypes} for state {state_name} and " + f"unflattened parameter names {unflat_param_names}" + ) + dtype = next(iter(dtypes)) + # Check that each tensor state matches its parameter's shape + for tensor, shape in zip(pos_dim_tensors, unflat_param_shapes): + if tensor is None and len(shape) == 0: + raise ValueError("Flattening a zero-dimension parameter is not supported") + elif tensor is not None and tensor.shape != shape: + raise ValueError( + "Tensor optimizer state does not have same shape as its " + f"parameter: {tensor.shape} {shape}" + ) + # Flatten the tensor states: we do not need to add any padding since the + # flattened optimizer state tensor sharded via `_get_shard()`, which pads + # the shard as needed (just like for the flattened parameter) + cpu_device = torch.device("cpu") + tensors = [ + torch.flatten(state_value.to(cpu_device)) + if state_value is not None + else torch.flatten( + torch.zeros( + size=shape, + dtype=dtype, + device=cpu_device, + ) + ) + for state_value, shape in zip(pos_dim_tensors, unflat_param_shapes) + ] + flat_tensor = torch.cat(tensors) + flat_param_shape = flat_param._unpadded_unsharded_size # type: ignore[attr-defined] + assert flat_tensor.shape == flat_param_shape, ( + f"tensor optim state: {flat_tensor.shape} " + f"flattened parameter: {flat_param_shape}" + ) + return flat_tensor + + +def _flatten_zero_dim_tensor_optim_state( + state_name: str, + zero_dim_tensors: List[torch.Tensor], + unflat_param_names: List[str], +) -> torch.Tensor: + """ + Flattens the zero-dimension tensor optimizer state given by the values + ``zero_dim_tensors`` for the state ``state_name`` for a single flattened + parameter corresponding to the unflattened parameter names + ``unflat_param_names`` by enforcing that all tensors are the same and using + that common value. + + NOTE: The requirement that the tensors are the same across all unflattened + parameters comprising the flattened parameter is needed to maintain the + invariant that FSDP performs the same computation as its non-sharded + equivalent. This means that none of the unflattened parameters can be + missing this state since imposing a value may differ from having no value. + For example, for Adam's "step", no value means maximum bias correction, + while having some positive value means less bias correction. + + Args: + state_name (str): Optimizer state name. + zero_dim_tensors (List[torch.Tensor]): Zero-dimension optimizer state + for the unflattened parameters corresponding to the single + flattened parameter. + unflat_param_names (List[str]): A :class:`list` of unflattened + parameter names corresponding to the single flattened parameter. + + Returns: + torch.Tensor: A zero-dimensional tensor giving the value of the state + ``state_name`` for all unflattened parameters corresponding to the + names ``unflat_param_names``. + """ + non_none_tensors = [t for t in zero_dim_tensors if t is not None] + # Enforce that all have the same value and dtype + values_set = {t.item() if t is not None else None for t in zero_dim_tensors} + dtypes = {t.dtype if t is not None else None for t in zero_dim_tensors} + if ( + len(non_none_tensors) != len(zero_dim_tensors) + or len(values_set) != 1 + or len(dtypes) != 1 + ): + raise ValueError( + "All unflattened parameters comprising a single flattened " + "parameter must have scalar state with the same value and dtype " + f"but got values {values_set} and dtypes {dtypes} for state " + f"{state_name} and unflattened parameter names " + f"{unflat_param_names}" + ) + value = next(iter(values_set)) + dtype = next(iter(dtypes)) + return torch.tensor(value, dtype=dtype, device=torch.device("cpu")) + + +def _flatten_non_tensor_optim_state( + state_name: str, + non_tensors: List[Any], + unflat_param_names: List[str], +) -> Any: + """ + Flattens the non-tensor optimizer state given by the values ``non_tensors`` + for the state ``state_name`` for a single flattened parameter corresponding + to the unflattened parameter names ``unflat_param_names`` by enforcing that + all values are the same and using that common value. + + See the note in :func:`_flatten_zero_dim_tensor_optim_state`. + + Args: + state_name (str): Optimizer state name. + non_tensors (List[Any]): Non-tensor optimizer state for the unflattened + parameters corresponding to the single flattened parameter. + unflat_param_names (List[str]): A :class:`list` of unflattened + parameter names corresponding to the single flattened parameter. + + Returns: + Any: A non-tensor giving the value of the state ``state_name`` for all + unflattened parameters corresponding to the names + ``unflat_param_names``. + """ + non_none_non_tensors = [nt for nt in non_tensors if nt is not None] + # Enforce that all have the same value (same type already checked) + non_tensor_set = set(non_tensors) + if len(non_none_non_tensors) != len(non_tensors) or len(non_tensor_set) != 1: + raise ValueError( + "All unflattened parameters comprising a single flattened " + "parameter must have scalar state with the same value and dtype " + f"but got values {non_tensor_set} for state {state_name} and " + f"unflattened parameter names {unflat_param_names}" + ) + non_tensor = next(iter(non_tensor_set)) + return non_tensor + + +def _process_pos_dim_tensor_state( + flat_optim_state_dict: Dict[str, Any], + world_size: int, +) -> Dict[str, Any]: + """ + Processes positive-dimension tensor states in ``flat_optim_state_dict`` by + replacing them with metadata. This is done so the processed optimizer state + dict can be broadcast from rank 0 to all ranks without copying those tensor + states, and thus, this is meant to only be called on rank 0. + + Args: + flat_optim_state_dict (Dict[str, Any]): Flattened optimizer state dict + with the positive-dimension tensor states unsharded. + + Returns: + Dict[str, Any]: The flattened optimizer state dict with positive- + dimension tensor states replaced by metadata. + """ + flat_osd = flat_optim_state_dict # alias + no_tensor_osd: Dict[str, Any] = {"state": {}} + for key, param_state in flat_osd["state"].items(): + no_tensor_osd["state"][key] = {} + for state_name, value in sorted_items(param_state): + is_pos_dim_tensor_state = torch.is_tensor(value) and value.dim() > 0 + if not is_pos_dim_tensor_state: + no_tensor_osd["state"][key][state_name] = value + continue + if key.is_fsdp_managed: # FSDP parameter + sharded_size = FlatParamHandle._get_sharded_size( + value, rank=0, world_size=world_size + ) + assert len(sharded_size) == 1, f"{sharded_size}" + info = _PosDimTensorInfo(sharded_size, value.dtype) + else: # non-FSDP parameter + info = _PosDimTensorInfo(value.shape, value.dtype) + no_tensor_osd["state"][key][state_name] = info + no_tensor_osd["param_groups"] = flat_osd["param_groups"] + return no_tensor_osd + + +def _broadcast_processed_optim_state_dict( + processed_optim_state_dict: Optional[Dict[str, Any]], + rank: int, + group, +) -> Dict[str, Any]: + """ + Broadcasts the processed optimizer state dict from rank 0 to all ranks. + + Args: + processed_optim_state_dict (Optional[Dict[str, Any]]): The flattened + optimizer state dict with positive-dimension tensor states replaced + with metadata if on rank 0; ignored otherwise. + + Returns: + Dict[str, Any]: The processed optimizer state dict. + """ + # Broadcast the two data structures rank 0 to all ranks + obj_list = [processed_optim_state_dict] if rank == 0 else [None] + dist.broadcast_object_list(obj_list, src=0, group=group) + processed_optim_state_dict = obj_list[0] # type: ignore[assignment] + assert processed_optim_state_dict is not None + # Keep zero-dimension tensors on CPU + return processed_optim_state_dict + + +def _broadcast_pos_dim_tensor_states( + processed_optim_state_dict: Dict[str, Any], + flat_optim_state_dict: Optional[Dict[str, Any]], + rank: int, + world_size: int, + group, + broadcast_device: torch.device, +) -> Dict[str, Any]: + """ + Takes ``processed_optim_state_dict``, which has metadata in place of + positive-dimension tensor states, and broadcasts those tensor states from + rank 0 to all ranks. For tensor states corresponding to FSDP parameters, + rank 0 shards the tensor and broadcasts shard-by-shard, and for tensor + states corresponding to non-FSDP parameters, rank 0 broadcasts the full + tensor. + + Args: + processed_optim_state_dict (Dict[str, Any]): The flattened optimizer + state dict with positive-dimension tensor states replaced with + metadata; this should be returned by + :meth:`_process_pos_dim_tensor_state` and non-empty on all ranks. + flat_optim_state_dict (Optional[Dict[str, Any]]): The flattened + unsharded optimizer state dict with the actual positive-dimension + tensor states if on rank 0; ignored on nonzero ranks. + + Returns: + Dict[str, Any]: The optimizer state dict with the positive-dimension + tensor state correctly populated via ``broadcast()`` s from rank 0. + """ + assert ( + rank != 0 or flat_optim_state_dict is not None + ), "Expects rank 0 to pass in the flattened optimizer state dict" + no_tensor_osd = processed_optim_state_dict # alias + flat_osd = flat_optim_state_dict # alias + for key, param_state in no_tensor_osd["state"].items(): + for state_name, value in sorted_items(param_state): + is_pos_dim_tensor_state = isinstance(value, _PosDimTensorInfo) + if not is_pos_dim_tensor_state: + continue + if rank == 0: + assert flat_osd is not None + unsharded_tensor = flat_osd["state"][key][state_name] + else: + unsharded_tensor = None + shape, dtype = value.shape, value.dtype + if key.is_fsdp_managed: # FSDP parameter + _broadcast_sharded_pos_dim_tensor_state( + unsharded_tensor, + param_state, + state_name, + shape, + dtype, + broadcast_device, + rank, + world_size, + group, + ) # modify `param_state` destructively + else: # non-FSDP parameter + _broadcast_unsharded_pos_dim_tensor_state( + unsharded_tensor, + param_state, + state_name, + shape, + dtype, + broadcast_device, + rank, + group, + ) # modify `param_state` destructively + return no_tensor_osd + + +def _broadcast_sharded_pos_dim_tensor_state( + unsharded_tensor: Optional[torch.Tensor], + param_state: Dict[str, Any], + state_name: str, + shape: torch.Size, + dtype: torch.dtype, + broadcast_device: torch.device, + rank: int, + world_size: int, + group, +) -> None: + """ + Broadcasts positive-dimension tensor state for the state ``state_name`` + corresponding to an FSDP parameter shard-by-shard, only to be saved on the + relevant rank. This modifies ``param_state`` destructively. + + Args: + unsharded_tensor (Optional[torch.Tensor]): Unsharded tensor from which + to broadcast shards if on rank 0; ignored otherwise. + shape (torch.Size): Shape of the sharded tensor; same on all ranks. + """ + get_shard: Optional[functools.partial[Tuple[torch.Tensor, int]]] = None + if rank == 0: + assert ( + unsharded_tensor is not None + ), "Expects rank 0 to pass in the unsharded tensor" + get_shard = functools.partial( + FlatParamHandle._get_shard, + unsharded_tensor, + ) + for target_rank in range(1, world_size): + if rank == 0: + assert get_shard is not None + sharded_tensor = get_shard(target_rank, world_size)[0].to(broadcast_device) + else: + sharded_tensor = torch.zeros( + shape, + requires_grad=False, + dtype=dtype, + device=broadcast_device, + ) + dist.broadcast(sharded_tensor, src=0, group=group) + # Only keep the shard on the target rank and keep it on the broadcast + # device, which is typically GPU + if rank == target_rank: + param_state[state_name] = sharded_tensor + else: + del sharded_tensor + # Lastly, shard on rank 0 + if rank != 0: + return + param_state[state_name] = get_shard(0, world_size)[0].to(broadcast_device) # type: ignore[misc] + + +def _broadcast_unsharded_pos_dim_tensor_state( + unsharded_tensor: Optional[torch.Tensor], + param_state: Dict[str, Any], + state_name: str, + shape: torch.Size, + dtype: torch.dtype, + broadcast_device: torch.device, + rank: int, + group, +) -> None: + """ + Broadcasts positive-dimension tensor state for the state ``state_name`` + corresponding to an unsharded non-FSDP parameter from rank 0 to all ranks. + This modifies ``param_state`` destructively. + + Args: + unsharded_tensor (Optional[torch.Tensor]): Unsharded tensor to + broadcast if on rank 0; ignored otherwise. + """ + if rank == 0: + assert ( + unsharded_tensor is not None + ), "Expects rank 0 to pass in the unsharded tensor" + assert ( + shape == unsharded_tensor.shape + ), f"Shape mismatch: {shape} {unsharded_tensor.shape}" + assert ( + dtype == unsharded_tensor.dtype + ), f"dtype mismatch: {dtype} {unsharded_tensor.dtype}" + unsharded_tensor = unsharded_tensor.to(broadcast_device) + else: + unsharded_tensor = torch.zeros( + shape, + requires_grad=False, + dtype=dtype, + device=broadcast_device, + ) + dist.broadcast(unsharded_tensor, src=0, group=group) + # Keep the tensor on the broadcast device, which is typically GPU + param_state[state_name] = unsharded_tensor + + +def _rekey_sharded_optim_state_dict( + sharded_osd: Dict[str, Any], + model: nn.Module, + optim: torch.optim.Optimizer, + optim_input: Optional[ + Union[ + List[Dict[str, Any]], + Iterable[nn.Parameter], + ] + ], + using_optim_input: bool, + is_named_optimizer: bool = False, +) -> Dict[str, Any]: + """ + Rekeys the optimizer state dict from unflattened parameter names to + flattened parameter IDs according to the calling rank's ``optim``, which + may be different across ranks. In particular, the unflattened parameter + names are represented as :class:`_OptimStateKey` s. + """ + param_to_fqns = _get_param_to_fqns(model) + flat_param_to_fqn = _get_flat_param_to_fqn(model) + param_to_param_key: Dict[nn.Parameter, Union[int, str]] = cast( + Dict[nn.Parameter, Union[int, str]], + ( + _get_param_to_param_id_from_optim_input(model, optim_input) + if using_optim_input + else _get_param_to_param_key( + optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn + ) + ), + ) + # All parameter keys in `param_to_param_key` should be in + # `param_to_fqns` -- strict inequality follows when not all parameters are + # passed to the optimizer + assert len(param_to_param_key) <= len(param_to_fqns) + + unflat_param_names_to_flat_param_key: Dict[ + Tuple[str, ...], Union[int, str] + ] = {} # for "state" + unflat_param_name_to_flat_param_key: Dict[ + str, Union[int, str] + ] = {} # for "param_groups" + for param, unflat_param_names in param_to_fqns.items(): + if param not in param_to_param_key: + # This parameter was not passed to the optimizer + continue + flat_param_key = param_to_param_key[param] + unflat_param_names_to_flat_param_key[tuple(unflat_param_names)] = flat_param_key + for unflat_param_name in unflat_param_names: + unflat_param_name_to_flat_param_key[unflat_param_name] = flat_param_key + + sharded_osd_state = sharded_osd["state"] + rekeyed_osd_state: Dict[Union[str, int], Any] = {} + for key, param_state in sharded_osd_state.items(): + if isinstance(key, str): + rekeyed_osd_state[key] = param_state + continue + flat_param_key = unflat_param_names_to_flat_param_key.get( + key.unflat_param_names, key.unflat_param_names + ) + rekeyed_osd_state[flat_param_key] = param_state + + rekeyed_osd_param_groups: List[Dict[str, Any]] = [] + for unflat_param_group in sharded_osd["param_groups"]: + flat_param_group = copy.deepcopy(unflat_param_group) + flat_param_keys = sorted( + { + unflat_param_name_to_flat_param_key[unflat_param_name] + for unflat_param_name in unflat_param_group["params"] + } + ) + flat_param_group["params"] = flat_param_keys + rekeyed_osd_param_groups.append(flat_param_group) + + return {"state": rekeyed_osd_state, "param_groups": rekeyed_osd_param_groups} + + +def _get_param_id_to_param_from_optim_input( + model: nn.Module, + optim_input: Optional[ + Union[ + List[Dict[str, Any]], + Iterable[nn.Parameter], + ] + ] = None, +) -> Dict[int, nn.Parameter]: + """ + Constructs a mapping from parameter IDs to parameters. This may be used + both for models with ``FlatParameter`` s and without. + + NOTE: This method is only preserved for backward compatibility. The method + :meth:`_get_param_key_to_param` is the preferred code path that does not + rely on ``optim_input``. + + NOTE: We critically assume that, whether the optimizer input is a list of + parameters or a list of parameter groups, :class:`torch.optim.Optimizer` + enumerates the parameter IDs in order. In other words, for a parameter list + input, the parameter IDs should be in that list order, and for a parameter + groups input, the parameter IDs should be in order within each parameter + group and in order across parameter groups. + + Args: + model (nn.Module): Model whose parameters are passed into the + optimizer. + optim_input (Optional[Union[List[Dict[str, Any]], + Iterable[nn.Parameter]]]): Input passed into the optimizer + representing either a :class:`list` of parameter groups or an + iterable of parameters; if ``None``, then this method assumes the + input was ``model.parameters()``. (Default: ``None``) + + Returns: + List[nn.Parameter]: Mapping from parameter IDs to parameters, + where the parameter ID is implicitly the index in the :class:`list`. + """ + # Assume the standard case of passing `model.parameters()` to the optimizer + # if `optim_input` is not specified + if optim_input is None: + return {pid: param for pid, param in enumerate(model.parameters())} + try: + params = cast(List[nn.Parameter], list(optim_input)) + except TypeError as e: + raise TypeError( + "Optimizer input should be an iterable of Tensors or dicts, " + f"but got {optim_input}" + ) from e + if len(params) == 0: + raise ValueError("Optimizer input should not be empty") + + # Check if the optimizer input represents tensors or parameter groups + all_tensors = True + all_dicts = True + for param in params: + all_tensors &= isinstance(param, torch.Tensor) + all_dicts &= isinstance(param, dict) + if not all_tensors and not all_dicts: + raise TypeError("Optimizer input should be an iterable of Tensors or dicts") + if all_tensors: + return {pid: param for pid, param in enumerate(params)} + assert all_dicts + param_id_to_param: List[nn.Parameter] = [] + for param_group in params: + has_params_key = "params" in param_group # type: ignore[operator] + assert has_params_key, ( + 'A parameter group should map "params" to a list of the ' + "parameters in the group" + ) + for param in param_group["params"]: # type: ignore[index] + # Implicitly map `flat_param_id` (current length of the list) to + # `param` + param_id_to_param.append(param) + return {pid: param for pid, param in enumerate(param_id_to_param)} + + +def _get_flat_param_to_fqn(model: torch.nn.Module) -> Dict[nn.Parameter, str]: + def module_fn(module, prefix, flat_param_to_fqn): + for param_name, param in module.named_parameters(recurse=False): + if type(param) is not FlatParameter: + continue + fqn = clean_tensor_name(prefix + param_name) + flat_param_to_fqn[param] = fqn + + def return_fn(flat_param_to_fqn): + return flat_param_to_fqn + + flat_param_to_fqn_ret: Dict[torch.nn.Parameter, str] = {} + return _apply_to_modules( + model, + module_fn, + return_fn, + [fqn for fqn, _ in model.named_parameters()], + flat_param_to_fqn_ret, + ) + + +def _get_param_key_to_param( + optim: torch.optim.Optimizer, + model: Optional[nn.Module] = None, + is_named_optimizer: bool = False, + param_to_fqns: Optional[Dict[nn.Parameter, List[str]]] = None, + flat_param_to_fqn: Optional[Dict[nn.Parameter, str]] = None, +) -> Dict[Union[int, str], nn.Parameter]: + """ + Constructs a mapping from parameter keys to parameters. For the regular + optimizers, the keys are parameter IDs. For NamedOptimizer, the keys + are FQNs. This API may be used both for models with ``FlatParameter`` s and + without. + """ + clean_fqn_to_curr_fqn: Dict[str, str] = {} + if is_named_optimizer: + assert ( + param_to_fqns is not None and flat_param_to_fqn is not None + ), "The optimizer is a NamedOptimizer, `param_to_fqns` must not be None." + assert model is not None + for key, _ in model.named_parameters(): + clean_fqn_to_curr_fqn[clean_tensor_name(key)] = key + + param_key_to_param: Dict[Union[str, int], nn.Parameter] = {} + pid = 0 + for param_group in optim.param_groups: + if is_named_optimizer: + for param in param_group["params"]: + assert flat_param_to_fqn is not None + if param in flat_param_to_fqn: + # FlatParameter case + key = flat_param_to_fqn[param] + else: + assert param_to_fqns is not None + # use_orig_params case + assert len(param_to_fqns[param]) == 1 + key = param_to_fqns[param][0] + key = clean_fqn_to_curr_fqn[key] + param_key_to_param[key] = param + else: + for param in param_group["params"]: + param_key_to_param[pid] = param + pid += 1 + + return param_key_to_param + + +def _get_param_to_param_key( + optim: torch.optim.Optimizer, + model: Optional[nn.Module] = None, + is_named_optimizer: bool = False, + param_to_fqns: Optional[Dict[nn.Parameter, List[str]]] = None, + flat_param_to_fqn: Optional[Dict[nn.Parameter, str]] = None, +) -> Dict[nn.Parameter, Union[int, str]]: + """ + Constructs the inverse mapping of :func:`_get_param_key_to_param`. This API + only supports the case where `optim` is a regular optimizer, not NamedOptimizer. + So the parameter keys will be parameter id. + """ + param_id_to_param = _get_param_key_to_param( + optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn + ) + return {param: param_id for param_id, param in param_id_to_param.items()} + + +def _get_param_to_param_id_from_optim_input( + model: nn.Module, + optim_input: Optional[ + Union[ + List[Dict[str, Any]], + Iterable[nn.Parameter], + ] + ] = None, +) -> Dict[nn.Parameter, int]: + """Constructs the inverse mapping of :func:`_get_param_id_to_param_from_optim_input`.""" + param_id_to_param = _get_param_id_to_param_from_optim_input(model, optim_input) + return {param: param_id for param_id, param in param_id_to_param.items()} + + +def _check_missing_keys_on_rank( + r0_optim_state_keys: List[_OptimStateKey], + optim_state_key_to_param_key: Dict[_OptimStateKey, Union[str, int]], + param_key_to_param: Dict[Union[str, int], nn.Parameter], + group: Optional[dist.ProcessGroup], +) -> None: + # Ensure that all ranks have at least the optimizer states needed by + # rank 0's optimizer + missing_keys: List[_OptimStateKey] = [] + for r0_optim_state_key in r0_optim_state_keys: + if r0_optim_state_key not in optim_state_key_to_param_key: + # A parameter from rank 0's optimizer does not exist for this + # rank's optimizer + missing_keys.append(r0_optim_state_key) + continue + param_key = optim_state_key_to_param_key[r0_optim_state_key] + if isinstance(param_key, int): + assert param_key >= 0 and param_key < len( + param_key_to_param + ), "Check the `param_key_to_param` construction" + device = torch.device("cuda", torch.cuda.current_device()) + num_missing = torch.tensor([len(missing_keys)], dtype=torch.int32, device=device) + dist.all_reduce(num_missing, group=group) + if num_missing.item() > 0: + obj_list = [None for _ in range(dist.get_world_size(group))] + dist.all_gather_object(obj_list, missing_keys, group=group) + error_msg = ( + "FSDP currently requires each rank to have at least the " + "optimizer states needed by rank 0's optimizer but some ranks " + "are missing some of those states" + ) + for rank, keys in enumerate(obj_list): + keys = cast(List[_OptimStateKey], keys) + if len(keys) > 0: + error_msg += ( + f"\nRank {rank} is missing states for the parameters: " + f"{[key.unflat_param_names for key in keys]}" + ) + raise RuntimeError(error_msg) + + +def _map_param_key_to_optim_keys( + optim_state_dict: Dict[str, Any], + group: Optional[dist.ProcessGroup], + param_key_to_param: Dict[Union[int, str], nn.Parameter], + param_to_fqns: Dict[nn.Parameter, List[str]], + fqn_to_fsdp_param_info: Dict[str, FSDPParamInfo], + merge_keys: bool = False, +) -> Tuple[List[_OptimStateKey], Dict[_OptimStateKey, Union[int, str]]]: + """ + Construct the local mapping between the ``_OptimStateKey`` and parameter keys + and all the ``_OptimStateKey`` across ranks. If ``merge_keys`` is False, rank0 + must contain all the ``_OptimStateKey``, an exception will be raised otherwise. + Note that ``merge_keys`` should equal to ``use_orig_params``. + """ + rank = dist.get_rank(group) + optim_state_key_to_param_key: Dict[_OptimStateKey, Union[int, str]] = {} # local + all_optim_state_keys: List[_OptimStateKey] = [] + + for param_key, param in param_key_to_param.items(): + # Do not include parameters without state to avoid empty mappings + # just like in normal `torch.optim.Optimizer.state_dict()` + if param_key not in optim_state_dict["state"]: + continue + fqns = param_to_fqns[param] + is_fsdp_managed = isinstance(param, FlatParameter) + if is_fsdp_managed: + assert fqns[0] in fqn_to_fsdp_param_info, ( + fqns[0], + list(fqn_to_fsdp_param_info.keys()), + ) + is_fsdp_managed = fqns[0] in fqn_to_fsdp_param_info + optim_state_key = _OptimStateKey( + unflat_param_names=tuple(fqns), + is_fsdp_managed=is_fsdp_managed, + ) + if rank == 0 or merge_keys: + all_optim_state_keys.append(optim_state_key) + optim_state_key_to_param_key[optim_state_key] = param_key + + if merge_keys: + all_keys: List[List[_OptimStateKey]] = [ + [] for _ in range(dist.get_world_size(group)) + ] + dist.all_gather_object(all_keys, all_optim_state_keys, group=group) + merge_all_optim_state_keys = [ + key for local_keys in all_keys for key in local_keys + ] + all_optim_state_keys = sorted(set(merge_all_optim_state_keys)) + else: + key_obj_list: List[Optional[List[_OptimStateKey]]] = ( + [all_optim_state_keys] if rank == 0 else [None] + ) + dist.broadcast_object_list(key_obj_list, src=0, group=group) + assert key_obj_list[0] is not None + all_optim_state_keys = key_obj_list[0] + _check_missing_keys_on_rank( + all_optim_state_keys, + optim_state_key_to_param_key, + param_key_to_param, + group, + ) + + return all_optim_state_keys, optim_state_key_to_param_key + + +def _unflatten_param_groups( + state_dict: Dict[str, Any], + param_key_to_param: Dict[Union[int, str], nn.Parameter], + param_to_fqns: Dict[nn.Parameter, List[str]], +) -> List[Dict[str, Any]]: + param_groups: List[Dict[str, Any]] = [] + for flat_param_group in state_dict["param_groups"]: + unflat_param_group = copy.deepcopy(flat_param_group) + param_group_params = [ + param_key_to_param[flat_param_key] + for flat_param_key in flat_param_group["params"] + ] + nested_unflat_param_names = [ + param_to_fqns[param] for param in param_group_params + ] + unflat_param_group["params"] = [ + unflat_param_name + for unflat_param_names in nested_unflat_param_names + for unflat_param_name in unflat_param_names + ] # flatten the list of lists + param_groups.append(unflat_param_group) + return param_groups + + +def _is_named_optimizer(optim_state_dict: Dict[str, Any]) -> bool: + state = optim_state_dict.get("state", None) + if not state: + # If we cannot find a state, assume it is not NamedOptimizer as + # NamedOptimizer has eagerly initialization. + return False + try: + key = next(iter(state.keys())) + except Exception as e: + raise Exception(optim_state_dict) from e + return isinstance(key, str) + + +def _optim_state_dict( + model: nn.Module, + optim: torch.optim.Optimizer, + optim_state_dict: Dict[str, Any], + optim_input: Optional[ + Union[ + List[Dict[str, Any]], + Iterable[nn.Parameter], + ] + ], + rank0_only: bool, + shard_state: bool, + group: Optional[dist.ProcessGroup], + using_optim_input: bool, + use_orig_params: bool = False, +) -> Dict[str, Any]: + """ + Consolidates the optimizer state and returns it as a :class:`dict` + following the convention of :meth:`torch.optim.Optimizer.state_dict`, + i.e. with keys ``"state"`` and ``"param_groups"``. + The flattened parameters in ``FSDP`` modules contained in ``model`` + are mapped back to their unflattened parameters. + + Parameter keys are not well-defined. For a regular optimizer, the optimizer + state_dict contains a mapping from parameter IDs to parameter states. + Parameter IDs are the order of parameters in ``optim.param_groups()`` across + all the groups. This API also allows user to pass ``optim_input`` for the + mapping between parameters and parameter IDs. Using ``optim_input`` is being + deprecated. + + If the optimizer is a ``NamedOptimizer``, the optimizer state_dict does not + contain parameter IDs mapping but a mapping from parameter FQNs to parameter + states. This API finds the mapping from FQNs to parameters if the optimizer + is a ``NamedOptimizer``. + + If ``use_orig_params`` is True, each rank will have all FSDP-managed + parameters but some of these parameters may be empty due to the sharding. + For a regular optim.Optimizer, states for those empty parameters will + not be initialized. So, when aggregating the FQNs across ranks, no assert + will be raised on a rank even if it does not have all the states -- it is + valid and FSDP know how to aggregate them. However, FSDP has to ignore + handling those parameters that are not managed by FSDP and do not exist on + the local rank -- it is managed by other parallelism and FSDP does not + know ho to handle/aggregate them. + + Args: + model (nn.Module): Root module (which may or may not be a + :class:`FullyShardedDataParallel` instance) whose parameters + were passed into the optimizer ``optim``. + optim (torch.optim.Optimizer): Optimizer for ``model`` 's + parameters. + rank0_only (bool): If ``True``, saves the populated :class:`dict` + only on rank 0; if ``False``, saves it on all ranks. (Default: + ``True``) + shard_state (bool): If ``True``, shard and distribute all + non-zero-dimension states. + + Returns: + Dict[str, Any]: A :class:`dict` containing the optimizer state for + ``model`` 's original unflattened parameters and including keys + "state" and "param_groups" following the convention of + :meth:`torch.optim.Optimizer.state_dict`. If ``rank0_only=False``, + then nonzero ranks return an empty :class:`dict`. + """ + _clear_grads_if_needed(traversal_utils._get_fsdp_handles(model)) + to_save = not rank0_only or (dist.get_rank(group) == 0 or shard_state) + fsdp_osd: Dict[str, Any] = {"state": {}, "param_groups": []} if to_save else {} + fsdp_osd_state: Dict[str, Any] = fsdp_osd["state"] if to_save else {} + param_to_fqns = _get_param_to_fqns(model) + flat_param_to_fqn = _get_flat_param_to_fqn(model) + is_named_optimizer = _is_named_optimizer(optim_state_dict) + + param_key_to_param = cast( + Dict[Union[int, str], nn.Parameter], + ( + _get_param_id_to_param_from_optim_input(model, optim_input) + if using_optim_input + else _get_param_key_to_param( + optim, model, is_named_optimizer, param_to_fqns, flat_param_to_fqn + ) + ), + ) + fqn_to_fsdp_param_info = _get_fqn_to_fsdp_param_info(model) + + all_optim_state_keys, optim_state_key_to_param_key = _map_param_key_to_optim_keys( + optim_state_dict, + group, + param_key_to_param, + param_to_fqns, + fqn_to_fsdp_param_info, + merge_keys=use_orig_params, + ) + + # Iterate in rank 0's flattened parameter ID order to ensure aligned + # all-gathers across ranks + for optim_state_key in all_optim_state_keys: + param_key: Union[str, int, None] = optim_state_key_to_param_key.get( + optim_state_key, None + ) + + if param_key is None: + assert use_orig_params, ( + "If use_orig_params is False, we must be able to find the " + f"corresponding param id. {optim_state_key} {param_key}" + ) + if not optim_state_key.is_fsdp_managed: + continue + + if optim_state_key.is_fsdp_managed: + # If there are multiple unflat_param_names (not use_orig_params), + # they share the same FSDPParamInfo. So the first unflat_param_name + # is sufficient to fetch the FSDPParamInfo. + fqn = optim_state_key.unflat_param_names[0] + fsdp_param_info = fqn_to_fsdp_param_info[fqn] + if use_orig_params: + state = ( + {} if param_key is None else optim_state_dict["state"][param_key] + ) + unflat_state = [ + _gather_orig_param_state( + fsdp_param_info, fqn, state, shard_state, group + ) + ] + else: + unflat_state = _unflatten_optim_state( + fsdp_param_info, + optim_state_dict["state"][param_key], + to_save, + shard_state, + ) + if to_save: + assert len(unflat_state) == len(optim_state_key.unflat_param_names) + for unflat_param_name, unflat_param_state in zip( + optim_state_key.unflat_param_names, + unflat_state, + ): + fsdp_osd_state[unflat_param_name] = unflat_param_state + elif to_save: + assert len(optim_state_key.unflat_param_names) == 1 + unflat_param_name = optim_state_key.unflat_param_names[0] + fsdp_osd_state[unflat_param_name] = copy.copy( + optim_state_dict["state"][param_key] + ) + for state_name, value in sorted_items(fsdp_osd_state[unflat_param_name]): + if torch.is_tensor(value): + fsdp_osd_state[unflat_param_name][state_name] = value.cpu() + + if to_save: + flat_param_fqns = set(flat_param_to_fqn.values()) + for key, value in optim_state_dict["state"].items(): + if key in fsdp_osd_state: + continue + if key in flat_param_fqns: + continue + if key in param_key_to_param: + continue + # This key is not recognized by FSDP. It may be a user-defined state + # or some parameters state that FSDP is unable to map from + # ``optim.param_groups``. + warnings.warn( + f"Found a optim state, {key}, that FSDP cannot process. FSDP " + "will directly copy everything to the returned state_dict. In " + "most cases, this is a user-defined state that is not " + "associated with any particular parameter. Another possible " + "case is this state is managed by DMP. Otherwise, there may " + " be a mismatched assumption of optim_state_dict of this mode." + ) + fsdp_osd_state[key] = value + + fsdp_osd["param_groups"] = _unflatten_param_groups( + optim_state_dict, param_key_to_param, param_to_fqns + ) + + return fsdp_osd + + +def _get_fqn_to_fsdp_param_info(model: nn.Module) -> Dict[str, FSDPParamInfo]: + """ + Construct the mapping from a param's fqn to its corresponding ``FSDPParamInfo`` + if the param is managed by FSDP. ``FlatParameter._fqns`` only stores the first + FQN of a shared parameter. So the keys in the mapping are guaranteed to map + to unique parameters. + """ + + def module_fn(module, prefix, fqn_to_param_info): + fsdp_state = _get_module_fsdp_state_if_fully_sharded_module(module) + if fsdp_state is None: + return + _lazy_init(fsdp_state, module) + handles = _module_handles(fsdp_state, module) + if not handles: + return + flat_param = handles[0].flat_param + fsdp_param_info = FSDPParamInfo(fsdp_state, flat_param, {}) + for idx, local_fqn in enumerate(flat_param._fqns): + fqn = clean_tensor_name(prefix + local_fqn) + if fqn in fqn_to_param_info: + assert fqn_to_param_info[fqn].flat_param == flat_param + fqn_to_param_info[fqn] = fsdp_param_info + fsdp_param_info.param_indices[fqn] = idx + + def return_fn(fqn_to_param_info): + return fqn_to_param_info + + fqn_to_param_info: Dict[str, FSDPParamInfo] = {} + # FlatParameter._fqns stores the local fqn, starting from the root of the + # FSDP. Using _apply_to_modules() with model (may not be the FSDP root + # module) allows us to construct the global fqn. + return _apply_to_modules( + model, + module_fn, + return_fn, + [fqn for fqn, _ in model.named_parameters()], + fqn_to_param_info, + ) + + +@dataclass +class StateInfo: + tensors: Dict[str, _PosDimTensorInfo] + scalar_tensors: Dict[str, torch.Tensor] + non_tensors: Dict[str, Any] + + +@dataclass +class AllGatherInfo: + tensors: List[torch.Tensor] + numels: List[int] + work: Optional[dist.Work] + + +def _all_gather_optim_state( + fsdp_state: _FSDPState, + optim_state: Dict[str, Any], + group=None, +) -> Dict[str, Any]: + """ + All-gathering state from all the ranks. This API is slow as it uses + ``all_gather_object``. However, optim state_dict is not in the critical path. + We can fuse the communication across differnt state if the performance + becomes a problem. + """ + # Allgather the scalar tensor state, non-tensor states and tensors metadata. + processed_state = StateInfo({}, {}, {}) + for state_name, value in sorted_items(optim_state): + if torch.is_tensor(value): + if value.dim() == 0: + # Ensure that `step` is on CPU. + processed_state.scalar_tensors[state_name] = value.cpu() + else: + processed_state.tensors[state_name] = _PosDimTensorInfo( + value.shape, value.dtype + ) + else: + processed_state.non_tensors = value + object_list: List[StateInfo] = [ + processed_state for _ in range(fsdp_state.world_size) + ] + dist.all_gather_object(object_list, processed_state, group=group) + + # Convert the gathered, pre-proccessed state of each rank to the original one. + gathered_state: Dict[str, Any] = {} + + all_tensor_states = sorted( + {n for state in object_list for n in state.tensors.keys()} + ) + empty_ranks: Set[int] = set() + for name in all_tensor_states: + numels = [] + dtype = torch.float + _empty_ranks: Set[int] = set() + for rank, object_state in enumerate(object_list): + numels.append(0) + info = object_state.tensors.get(name, None) + if info is not None: + numels[-1] = info.shape.numel() + dtype = info.dtype + if numels[-1] == 0: + _empty_ranks.add(rank) + + empty_func = functools.partial( + torch.empty, dtype=dtype, device=fsdp_state.compute_device + ) + if empty_ranks: + assert empty_ranks == _empty_ranks + empty_ranks = _empty_ranks + local_state = optim_state.get(name, empty_func(0)) + local_state = local_state.to(fsdp_state.compute_device) + tensors = [ + empty_func(numel) if rank != fsdp_state.rank else local_state + for rank, numel in enumerate(numels) + ] + work = dist.all_gather( + tensors, local_state, group=fsdp_state.process_group, async_op=True + ) + gathered_state[name] = AllGatherInfo(tensors, numels, work) + + for rank, object_state in enumerate(object_list): + if rank in empty_ranks: + continue + for name, non_tensor_value in object_state.non_tensors.items(): + curr_non_tensor_value = gathered_state.get(name, None) + assert ( + curr_non_tensor_value is None + or curr_non_tensor_value == non_tensor_value + ), f"Different ranks have different values for {name}." + gathered_state[name] = non_tensor_value + + for name, scalar_tensor_value in object_state.scalar_tensors.items(): + curr_scalar_tensor_value = gathered_state.get(name, None) + assert curr_scalar_tensor_value is None or torch.equal( + scalar_tensor_value, curr_scalar_tensor_value + ), f"Different ranks have different values for {name}." + gathered_state[name] = scalar_tensor_value + + for name, value in list(gathered_state.items()): + if not isinstance(value, AllGatherInfo): + continue + assert value.work is not None + value.work.wait() + gathered_state[name] = torch.cat( + [ + rank_tensor[:rank_numel] + for rank_tensor, rank_numel in zip(value.tensors, value.numels) + if rank_numel > 0 + ] + ) + + return gathered_state + + +def _gather_orig_param_state( + fsdp_param_info: FSDPParamInfo, + fqn: str, + optim_state: Dict[str, Any], + shard_state: bool, + group=None, +) -> Dict[str, Any]: + """ + Gather the optimizer state for the original parameter with the name ``fqn``. + This API should only be used when ``use_orig_params`` is True. + """ + fsdp_state = fsdp_param_info.state + assert ( + fsdp_state._use_orig_params + ), "_gather_orig_param_state only support use_orig_params=True case" + flat_param = fsdp_param_info.flat_param + param_idx = fsdp_param_info.param_indices[fqn] + if ( + fsdp_state.world_size == 1 + or fsdp_state.sharding_strategy == ShardingStrategy.NO_SHARD + ): + return optim_state + + gathered_state = _all_gather_optim_state(fsdp_state, optim_state, group=group) + + # Unflatten state values. + for state_name, value in list(gathered_state.items()): + if not torch.is_tensor(value) or value.dim() == 0: + continue + + value = value[: flat_param._numels[param_idx]].reshape( + flat_param._shapes[param_idx] + ) + if shard_state: + assert fsdp_state.process_group is not None + value = _ext_chunk_tensor( + value, + fsdp_state.rank, + fsdp_state.world_size, + torch.cuda.device_count(), + fsdp_state.process_group, + ) + value = value.cpu() + gathered_state[state_name] = value + return gathered_state + + +def _shard_orig_param_state( + fsdp_param_info: FSDPParamInfo, + fqn: str, + optim_state: Dict[str, Any], +) -> Dict[str, Any]: + """ + Shard the optimizer state for the original parameter with the name ``fqn``. + This API should only be used when ``use_orig_params`` is True. + """ + if not optim_state: + return {} + fsdp_state = fsdp_param_info.state + flat_param = fsdp_param_info.flat_param + param_idx = fsdp_param_info.param_indices[fqn] + + optim_state = _gather_state_dict(optim_state, fsdp_state.process_group) + start, end = flat_param._shard_indices # type: ignore[attr-defined] + if not (start <= param_idx <= end and flat_param._shard_param_offsets): # type: ignore[attr-defined] + return {} + param_start, param_end = flat_param._shard_param_offsets[param_idx - start] # type: ignore[attr-defined] + + # Flatten and shard the state. + new_optim_state: Dict[str, Any] = {} + for state_name, value in optim_state.items(): + if torch.is_tensor(value) and value.dim() > 0: + value = value.flatten()[param_start : param_end + 1] + new_optim_state[state_name] = value + return new_optim_state diff --git a/open_flamingo/docs/flamingo.png b/open_flamingo/docs/flamingo.png new file mode 100644 index 0000000000000000000000000000000000000000..ab154474ea6c49dadb0b8fb113004bd29a7f267e Binary files /dev/null and b/open_flamingo/docs/flamingo.png differ diff --git a/open_flamingo/environment.yml b/open_flamingo/environment.yml new file mode 100644 index 0000000000000000000000000000000000000000..1d477e5bf5ca956bdfb18f44b24305d7d818f4b7 --- /dev/null +++ b/open_flamingo/environment.yml @@ -0,0 +1,10 @@ +name: openflamingo +channels: + - defaults +dependencies: + - python=3.9 + - conda-forge::openjdk + - pip + - pip: + - -r requirements.txt + - -e . diff --git a/open_flamingo/open_flamingo/__init__.py b/open_flamingo/open_flamingo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ab67750bb75534afaeb8876c065e32d4861f3052 --- /dev/null +++ b/open_flamingo/open_flamingo/__init__.py @@ -0,0 +1,2 @@ +from .src.flamingo import Flamingo +from .src.factory import create_model_and_transforms diff --git a/open_flamingo/open_flamingo/eval/README.md b/open_flamingo/open_flamingo/eval/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dde686b79e6d9fdbc4b0e94ea710be9a126a5cdf --- /dev/null +++ b/open_flamingo/open_flamingo/eval/README.md @@ -0,0 +1,47 @@ +# OpenFlamingo Evaluation Suite + +This is the evaluation module of OpenFlamingo. It contains a set of utilities for evaluating multimodal models on various benchmarking datasets. + +*This module is a work in progress! We will be updating this README as it develops. In the meantime, if you notice an issue, please file a Bug Report or Feature Request [here](https://github.com/mlfoundations/open_flamingo/issues/new/choose).* + +## Supported datasets + +|Dataset|Task|Metric|Evaluation method| +|-------|----|------|-----------------| +|[COCO](https://arxiv.org/abs/1405.0312)|Captioning|CIDEr|Generation| +|[Flickr-30K](https://aclanthology.org/Q14-1006/)|Captioning|CIDEr|Generation| +|[VQAv2](https://arxiv.org/abs/1612.00837v3)|VQA|VQA accuracy|Generation| +|[OK-VQA](https://arxiv.org/abs/1906.00067)|VQA|VQA accuracy|Generation| +|[TextVQA](https://arxiv.org/abs/1904.08920)|VQA|VQA accuracy|Generation| +|[VizWiz](https://arxiv.org/abs/1802.08218)|VQA|VQA accuracy|Generation| +|[Hateful Memes](https://arxiv.org/abs/2005.04790)|Classification|ROC AUC|Logprobs| +|[ImageNet](https://arxiv.org/abs/1409.0575)|Classification|Top-1 accuracy|Logprobs| + +When evaluating a model using `num_shots` shots, we sample the exemplars from the training split. Performance is evaluated on a disjoint test split, subsampled to `--num_samples` examples (or using the full test split if `--num_samples=-1`). + +## Sample scripts +Our codebase uses DistributedDataParallel to parallelize evaluation by default, so please make sure to set the `MASTER_ADDR` and `MASTER_PORT` environment variables or use `torchrun`. We provide a sample Slurm evaluation script in `open_flamingo/open_flamingo/scripts/run_eval.sh`. + +We also support evaluating at a lower precision using the `--precision` flag. We find minimal difference between evaluating at full precision vs. amp_bf16. + +To evaluate one of our pretrained checkpoints, we suggest first downloading a local copy of the weights, as follows: + +``` +# grab model checkpoint from huggingface hub +from huggingface_hub import hf_hub_download +HF_TOKEN="" + +checkpoint_path = hf_hub_download("openflamingo/OpenFlamingo-3B-vitl-mpt1b", "checkpoint.pt") +checkpoint_path= hf_hub_download("openflamingo/OpenFlamingo-3B-vitl-mpt1b", + "checkpoint.pt", + local_dir="openflamingo/OpenFlamingo-3B-vitl-mpt1b", + cache_dir="openflamingo/OpenFlamingo-3B-vitl-mpt1b", + local_dir_use_symlinks=False, + token=HF_TOKEN) +print(checkpoint_path) +## openflamingo/OpenFlamingo-3B-vitl-mpt1b/checkpoint.pt +``` + +This should place the OpenFlamingo model at the expected location in the evaluation script. + +For TextVQA and VizWiz we expect annotations to be formatted differently than the original datasets. We provide the custom annotations in `open_flamingo/open_flamingo/eval/data/`. \ No newline at end of file diff --git a/open_flamingo/open_flamingo/eval/__init__.py b/open_flamingo/open_flamingo/eval/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/open_flamingo/open_flamingo/eval/__init__.py @@ -0,0 +1 @@ + diff --git a/open_flamingo/open_flamingo/eval/classification.py b/open_flamingo/open_flamingo/eval/classification.py new file mode 100644 index 0000000000000000000000000000000000000000..a6503b30a370faeb98410f158e50a8bc0e4484b2 --- /dev/null +++ b/open_flamingo/open_flamingo/eval/classification.py @@ -0,0 +1,147 @@ +from typing import Dict, Sequence, Tuple +import re +import numpy as np +import torch + + +def postprocess_classification_generation(predictions) -> str: + return re.split("Prompt|Completion", predictions, 1)[0] + + +def compute_classification_accuracy(predictions: Sequence[Dict[str, str]]) -> float: + """Compute the accuracy of a sequence of predictions.""" + + def _preprocess_fn(s): + """Function to preprocess both targets and predictions.""" + return s.lower() + + is_correct = [ + _preprocess_fn(x["prediction"]) == _preprocess_fn(x["class_label"]) + for x in predictions + ] + + return np.mean(is_correct).item() + + +def compute_shifted_logits_and_labels( + logits: torch.Tensor, encodings, tokenizer, eoc_token_id +) -> Tuple[torch.Tensor, torch.Tensor]: + """Helper function to compute shifted logits and labels. + + This allows for straightforward computation of the loss on shift_logits + and shift_labels such that the nth element of logits computes the n-1th + element of the original labels (in the outputs, the nth element of logits + corresponds to the nth element of the labels). + + Elements in shift_labels that correspond to inputs are masked with values + of -100 (by default in hf, loss is only computed on token IDs >= 0). + + Returns: tuple containing two elements: + shift_logits: a float Tensor of shape [batch_size, seq_len - 1]. + shift_labels: an integer Tensor of shape [batch_size, seq_len - 1] + """ + + labels = encodings["input_ids"].clone() + + # convert padding and EOC tokens to -100 so they are ignored in loss + labels[labels == tokenizer.pad_token_id] = -100 + labels[labels == eoc_token_id] = -100 + + # Convert all tokens in prefix until separator to -100 so they are + # ignored in loss + for idx in range(len(labels)): + # Find the location of the last token of prefix *from right*, + # since the first non-padding token of the sequence will also be + # eos_token (because bos_token and eos_token are the same for + # the tokenizer). + end_of_prefix = -labels[idx].tolist()[::-1].index(tokenizer.eos_token_id) - 1 + labels[idx, : end_of_prefix + 1] = -100 + + # Shift so that tokens < n predict n. The shifted tensors both have + # shape [batch_size, seq_len - 1]. + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + + return shift_logits, shift_labels + + +def compute_per_sample_probs( + encodings, tokenizer, logits: torch.Tensor, eoc_token_id +) -> torch.Tensor: + """Helper function to compute per-sample probability of the input sequence. + + Assumes is used to separate inputs from targets in the + prompt text + """ + shift_logits, shift_labels = compute_shifted_logits_and_labels( + logits, encodings, tokenizer, eoc_token_id + ) + + # Tuple of tensors for unmasked label tokens. The first element of the + # tuple contains the batch indices; the second element contains the + # sequence indices. + unmasked_indices = torch.nonzero(shift_labels != -100, as_tuple=True) + # Tensor where the i^th element is the token_id corresponding to the i^th + # element of unmasked_indices + unmasked_token_ids = shift_labels[unmasked_indices] + + # 3d tensor of [batch_idx, sequence_position, token_id] for unmasked tokens. + target_idxs = torch.column_stack([*unmasked_indices, unmasked_token_ids]) + target_idxs = target_idxs.to(shift_logits.device) + + # Sanity check that every element in batch has at least one unmasked + # target token + assert torch.all( + torch.bincount(target_idxs[:, 0]) != 0 + ), "At least one element in batch has no unmasked target tokens." + + # Renormalize over tokens to make sure they are proper probabilities via + # softmax over the token dimension. + shift_probs = torch.nn.functional.softmax(shift_logits, 2) + + # Compute the probability of the target sequence (as the product of the + # probability of the individual tokens in the sequence). + target_probs = torch.ones(len(shift_labels), device=shift_logits.device) + for i, j, k in target_idxs: + target_probs[i] *= shift_probs[i, j, k] + + return target_probs + + +def compute_per_sample_loss(encodings, tokenizer, logits, eoc_token_id) -> torch.Tensor: + """Helper function to compute per-sample classification loss. + + Assumes is used to separate inputs from targets in the + prompt text + """ + shift_logits, shift_labels = compute_shifted_logits_and_labels( + logits, encodings, tokenizer, eoc_token_id + ) + + device = shift_logits.device + + # Loss is computed token-wise, on Tensors of shape + # [batch_size * (seq_len - 1), vocab_size] + # and returns a loss tensor of shape + # [batch_size * (seq_len - 1)]. Most of the tokens will be masked + # in this computation. + loss = torch.nn.functional.cross_entropy( + shift_logits.view(-1, shift_logits.size(-1)), + shift_labels.view(-1).to(device), + reduction="none", + ) + + # Reshape to [batch_size, seq_len - 1] + loss = loss.view(shift_logits.size(0), shift_logits.size(1)).cpu() + + # loss_mask is 1 for tokens we want included in the loss, and 0 for tokens + # that should be ignored in the loss. + loss_mask = (shift_labels != -100).int().cpu() + + loss *= loss_mask + + # Compute per-element loss : sum loss over all (unmasked) tokens and + # divide by number of variable tokens to obtain tensor of + # shape [batch_size,] + loss = loss.sum(dim=1) / (shift_labels != -100).sum(dim=1).float() + return loss diff --git a/open_flamingo/open_flamingo/eval/classification_utils.py b/open_flamingo/open_flamingo/eval/classification_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..01782568cc9f277bd227b4c7113e7abfc63e77e9 --- /dev/null +++ b/open_flamingo/open_flamingo/eval/classification_utils.py @@ -0,0 +1,1014 @@ +# classnames via https://github.com/mlfoundations/wise-ft/blob/master/src/datasets/imagenet_classnames.py#L1 +IMAGENET_CLASSNAMES = [ + "tench", + "goldfish", + "great white shark", + "tiger shark", + "hammerhead shark", + "electric ray", + "stingray", + "rooster", + "hen", + "ostrich", + "brambling", + "goldfinch", + "house finch", + "junco", + "indigo bunting", + "American robin", + "bulbul", + "jay", + "magpie", + "chickadee", + "American dipper", + "kite (bird of prey)", + "bald eagle", + "vulture", + "great grey owl", + "fire salamander", + "smooth newt", + "newt", + "spotted salamander", + "axolotl", + "American bullfrog", + "tree frog", + "tailed frog", + "loggerhead sea turtle", + "leatherback sea turtle", + "mud turtle", + "terrapin", + "box turtle", + "banded gecko", + "green iguana", + "Carolina anole", + "desert grassland whiptail lizard", + "agama", + "frilled-necked lizard", + "alligator lizard", + "Gila monster", + "European green lizard", + "chameleon", + "Komodo dragon", + "Nile crocodile", + "American alligator", + "triceratops", + "worm snake", + "ring-necked snake", + "eastern hog-nosed snake", + "smooth green snake", + "kingsnake", + "garter snake", + "water snake", + "vine snake", + "night snake", + "boa constrictor", + "African rock python", + "Indian cobra", + "green mamba", + "sea snake", + "Saharan horned viper", + "eastern diamondback rattlesnake", + "sidewinder rattlesnake", + "trilobite", + "harvestman", + "scorpion", + "yellow garden spider", + "barn spider", + "European garden spider", + "southern black widow", + "tarantula", + "wolf spider", + "tick", + "centipede", + "black grouse", + "ptarmigan", + "ruffed grouse", + "prairie grouse", + "peafowl", + "quail", + "partridge", + "african grey parrot", + "macaw", + "sulphur-crested cockatoo", + "lorikeet", + "coucal", + "bee eater", + "hornbill", + "hummingbird", + "jacamar", + "toucan", + "duck", + "red-breasted merganser", + "goose", + "black swan", + "tusker", + "echidna", + "platypus", + "wallaby", + "koala", + "wombat", + "jellyfish", + "sea anemone", + "brain coral", + "flatworm", + "nematode", + "conch", + "snail", + "slug", + "sea slug", + "chiton", + "chambered nautilus", + "Dungeness crab", + "rock crab", + "fiddler crab", + "red king crab", + "American lobster", + "spiny lobster", + "crayfish", + "hermit crab", + "isopod", + "white stork", + "black stork", + "spoonbill", + "flamingo", + "little blue heron", + "great egret", + "bittern bird", + "crane bird", + "limpkin", + "common gallinule", + "American coot", + "bustard", + "ruddy turnstone", + "dunlin", + "common redshank", + "dowitcher", + "oystercatcher", + "pelican", + "king penguin", + "albatross", + "grey whale", + "killer whale", + "dugong", + "sea lion", + "Chihuahua", + "Japanese Chin", + "Maltese", + "Pekingese", + "Shih Tzu", + "King Charles Spaniel", + "Papillon", + "toy terrier", + "Rhodesian Ridgeback", + "Afghan Hound", + "Basset Hound", + "Beagle", + "Bloodhound", + "Bluetick Coonhound", + "Black and Tan Coonhound", + "Treeing Walker Coonhound", + "English foxhound", + "Redbone Coonhound", + "borzoi", + "Irish Wolfhound", + "Italian Greyhound", + "Whippet", + "Ibizan Hound", + "Norwegian Elkhound", + "Otterhound", + "Saluki", + "Scottish Deerhound", + "Weimaraner", + "Staffordshire Bull Terrier", + "American Staffordshire Terrier", + "Bedlington Terrier", + "Border Terrier", + "Kerry Blue Terrier", + "Irish Terrier", + "Norfolk Terrier", + "Norwich Terrier", + "Yorkshire Terrier", + "Wire Fox Terrier", + "Lakeland Terrier", + "Sealyham Terrier", + "Airedale Terrier", + "Cairn Terrier", + "Australian Terrier", + "Dandie Dinmont Terrier", + "Boston Terrier", + "Miniature Schnauzer", + "Giant Schnauzer", + "Standard Schnauzer", + "Scottish Terrier", + "Tibetan Terrier", + "Australian Silky Terrier", + "Soft-coated Wheaten Terrier", + "West Highland White Terrier", + "Lhasa Apso", + "Flat-Coated Retriever", + "Curly-coated Retriever", + "Golden Retriever", + "Labrador Retriever", + "Chesapeake Bay Retriever", + "German Shorthaired Pointer", + "Vizsla", + "English Setter", + "Irish Setter", + "Gordon Setter", + "Brittany dog", + "Clumber Spaniel", + "English Springer Spaniel", + "Welsh Springer Spaniel", + "Cocker Spaniel", + "Sussex Spaniel", + "Irish Water Spaniel", + "Kuvasz", + "Schipperke", + "Groenendael dog", + "Malinois", + "Briard", + "Australian Kelpie", + "Komondor", + "Old English Sheepdog", + "Shetland Sheepdog", + "collie", + "Border Collie", + "Bouvier des Flandres dog", + "Rottweiler", + "German Shepherd Dog", + "Dobermann", + "Miniature Pinscher", + "Greater Swiss Mountain Dog", + "Bernese Mountain Dog", + "Appenzeller Sennenhund", + "Entlebucher Sennenhund", + "Boxer", + "Bullmastiff", + "Tibetan Mastiff", + "French Bulldog", + "Great Dane", + "St. Bernard", + "husky", + "Alaskan Malamute", + "Siberian Husky", + "Dalmatian", + "Affenpinscher", + "Basenji", + "pug", + "Leonberger", + "Newfoundland dog", + "Great Pyrenees dog", + "Samoyed", + "Pomeranian", + "Chow Chow", + "Keeshond", + "brussels griffon", + "Pembroke Welsh Corgi", + "Cardigan Welsh Corgi", + "Toy Poodle", + "Miniature Poodle", + "Standard Poodle", + "Mexican hairless dog (xoloitzcuintli)", + "grey wolf", + "Alaskan tundra wolf", + "red wolf or maned wolf", + "coyote", + "dingo", + "dhole", + "African wild dog", + "hyena", + "red fox", + "kit fox", + "Arctic fox", + "grey fox", + "tabby cat", + "tiger cat", + "Persian cat", + "Siamese cat", + "Egyptian Mau", + "cougar", + "lynx", + "leopard", + "snow leopard", + "jaguar", + "lion", + "tiger", + "cheetah", + "brown bear", + "American black bear", + "polar bear", + "sloth bear", + "mongoose", + "meerkat", + "tiger beetle", + "ladybug", + "ground beetle", + "longhorn beetle", + "leaf beetle", + "dung beetle", + "rhinoceros beetle", + "weevil", + "fly", + "bee", + "ant", + "grasshopper", + "cricket insect", + "stick insect", + "cockroach", + "praying mantis", + "cicada", + "leafhopper", + "lacewing", + "dragonfly", + "damselfly", + "red admiral butterfly", + "ringlet butterfly", + "monarch butterfly", + "small white butterfly", + "sulphur butterfly", + "gossamer-winged butterfly", + "starfish", + "sea urchin", + "sea cucumber", + "cottontail rabbit", + "hare", + "Angora rabbit", + "hamster", + "porcupine", + "fox squirrel", + "marmot", + "beaver", + "guinea pig", + "common sorrel horse", + "zebra", + "pig", + "wild boar", + "warthog", + "hippopotamus", + "ox", + "water buffalo", + "bison", + "ram (adult male sheep)", + "bighorn sheep", + "Alpine ibex", + "hartebeest", + "impala (antelope)", + "gazelle", + "arabian camel", + "llama", + "weasel", + "mink", + "European polecat", + "black-footed ferret", + "otter", + "skunk", + "badger", + "armadillo", + "three-toed sloth", + "orangutan", + "gorilla", + "chimpanzee", + "gibbon", + "siamang", + "guenon", + "patas monkey", + "baboon", + "macaque", + "langur", + "black-and-white colobus", + "proboscis monkey", + "marmoset", + "white-headed capuchin", + "howler monkey", + "titi monkey", + "Geoffroy's spider monkey", + "common squirrel monkey", + "ring-tailed lemur", + "indri", + "Asian elephant", + "African bush elephant", + "red panda", + "giant panda", + "snoek fish", + "eel", + "silver salmon", + "rock beauty fish", + "clownfish", + "sturgeon", + "gar fish", + "lionfish", + "pufferfish", + "abacus", + "abaya", + "academic gown", + "accordion", + "acoustic guitar", + "aircraft carrier", + "airliner", + "airship", + "altar", + "ambulance", + "amphibious vehicle", + "analog clock", + "apiary", + "apron", + "trash can", + "assault rifle", + "backpack", + "bakery", + "balance beam", + "balloon", + "ballpoint pen", + "Band-Aid", + "banjo", + "baluster / handrail", + "barbell", + "barber chair", + "barbershop", + "barn", + "barometer", + "barrel", + "wheelbarrow", + "baseball", + "basketball", + "bassinet", + "bassoon", + "swimming cap", + "bath towel", + "bathtub", + "station wagon", + "lighthouse", + "beaker", + "military hat (bearskin or shako)", + "beer bottle", + "beer glass", + "bell tower", + "baby bib", + "tandem bicycle", + "bikini", + "ring binder", + "binoculars", + "birdhouse", + "boathouse", + "bobsleigh", + "bolo tie", + "poke bonnet", + "bookcase", + "bookstore", + "bottle cap", + "hunting bow", + "bow tie", + "brass memorial plaque", + "bra", + "breakwater", + "breastplate", + "broom", + "bucket", + "buckle", + "bulletproof vest", + "high-speed train", + "butcher shop", + "taxicab", + "cauldron", + "candle", + "cannon", + "canoe", + "can opener", + "cardigan", + "car mirror", + "carousel", + "tool kit", + "cardboard box / carton", + "car wheel", + "automated teller machine", + "cassette", + "cassette player", + "castle", + "catamaran", + "CD player", + "cello", + "mobile phone", + "chain", + "chain-link fence", + "chain mail", + "chainsaw", + "storage chest", + "chiffonier", + "bell or wind chime", + "china cabinet", + "Christmas stocking", + "church", + "movie theater", + "cleaver", + "cliff dwelling", + "cloak", + "clogs", + "cocktail shaker", + "coffee mug", + "coffeemaker", + "spiral or coil", + "combination lock", + "computer keyboard", + "candy store", + "container ship", + "convertible", + "corkscrew", + "cornet", + "cowboy boot", + "cowboy hat", + "cradle", + "construction crane", + "crash helmet", + "crate", + "infant bed", + "Crock Pot", + "croquet ball", + "crutch", + "cuirass", + "dam", + "desk", + "desktop computer", + "rotary dial telephone", + "diaper", + "digital clock", + "digital watch", + "dining table", + "dishcloth", + "dishwasher", + "disc brake", + "dock", + "dog sled", + "dome", + "doormat", + "drilling rig", + "drum", + "drumstick", + "dumbbell", + "Dutch oven", + "electric fan", + "electric guitar", + "electric locomotive", + "entertainment center", + "envelope", + "espresso machine", + "face powder", + "feather boa", + "filing cabinet", + "fireboat", + "fire truck", + "fire screen", + "flagpole", + "flute", + "folding chair", + "football helmet", + "forklift", + "fountain", + "fountain pen", + "four-poster bed", + "freight car", + "French horn", + "frying pan", + "fur coat", + "garbage truck", + "gas mask or respirator", + "gas pump", + "goblet", + "go-kart", + "golf ball", + "golf cart", + "gondola", + "gong", + "gown", + "grand piano", + "greenhouse", + "radiator grille", + "grocery store", + "guillotine", + "hair clip", + "hair spray", + "half-track", + "hammer", + "hamper", + "hair dryer", + "hand-held computer", + "handkerchief", + "hard disk drive", + "harmonica", + "harp", + "combine harvester", + "hatchet", + "holster", + "home theater", + "honeycomb", + "hook", + "hoop skirt", + "gymnastic horizontal bar", + "horse-drawn vehicle", + "hourglass", + "iPod", + "clothes iron", + "carved pumpkin", + "jeans", + "jeep", + "T-shirt", + "jigsaw puzzle", + "rickshaw", + "joystick", + "kimono", + "knee pad", + "knot", + "lab coat", + "ladle", + "lampshade", + "laptop computer", + "lawn mower", + "lens cap", + "letter opener", + "library", + "lifeboat", + "lighter", + "limousine", + "ocean liner", + "lipstick", + "slip-on shoe", + "lotion", + "music speaker", + "loupe magnifying glass", + "sawmill", + "magnetic compass", + "messenger bag", + "mailbox", + "tights", + "one-piece bathing suit", + "manhole cover", + "maraca", + "marimba", + "mask", + "matchstick", + "maypole", + "maze", + "measuring cup", + "medicine cabinet", + "megalith", + "microphone", + "microwave oven", + "military uniform", + "milk can", + "minibus", + "miniskirt", + "minivan", + "missile", + "mitten", + "mixing bowl", + "mobile home", + "ford model t", + "modem", + "monastery", + "monitor", + "moped", + "mortar and pestle", + "graduation cap", + "mosque", + "mosquito net", + "vespa", + "mountain bike", + "tent", + "computer mouse", + "mousetrap", + "moving van", + "muzzle", + "metal nail", + "neck brace", + "necklace", + "baby pacifier", + "notebook computer", + "obelisk", + "oboe", + "ocarina", + "odometer", + "oil filter", + "pipe organ", + "oscilloscope", + "overskirt", + "bullock cart", + "oxygen mask", + "product packet / packaging", + "paddle", + "paddle wheel", + "padlock", + "paintbrush", + "pajamas", + "palace", + "pan flute", + "paper towel", + "parachute", + "parallel bars", + "park bench", + "parking meter", + "railroad car", + "patio", + "payphone", + "pedestal", + "pencil case", + "pencil sharpener", + "perfume", + "Petri dish", + "photocopier", + "plectrum", + "Pickelhaube", + "picket fence", + "pickup truck", + "pier", + "piggy bank", + "pill bottle", + "pillow", + "ping-pong ball", + "pinwheel", + "pirate ship", + "drink pitcher", + "block plane", + "planetarium", + "plastic bag", + "plate rack", + "farm plow", + "plunger", + "Polaroid camera", + "pole", + "police van", + "poncho", + "pool table", + "soda bottle", + "plant pot", + "potter's wheel", + "power drill", + "prayer rug", + "printer", + "prison", + "missile", + "projector", + "hockey puck", + "punching bag", + "purse", + "quill", + "quilt", + "race car", + "racket", + "radiator", + "radio", + "radio telescope", + "rain barrel", + "recreational vehicle", + "fishing casting reel", + "reflex camera", + "refrigerator", + "remote control", + "restaurant", + "revolver", + "rifle", + "rocking chair", + "rotisserie", + "eraser", + "rugby ball", + "ruler measuring stick", + "sneaker", + "safe", + "safety pin", + "salt shaker", + "sandal", + "sarong", + "saxophone", + "scabbard", + "weighing scale", + "school bus", + "schooner", + "scoreboard", + "CRT monitor", + "screw", + "screwdriver", + "seat belt", + "sewing machine", + "shield", + "shoe store", + "shoji screen / room divider", + "shopping basket", + "shopping cart", + "shovel", + "shower cap", + "shower curtain", + "ski", + "balaclava ski mask", + "sleeping bag", + "slide rule", + "sliding door", + "slot machine", + "snorkel", + "snowmobile", + "snowplow", + "soap dispenser", + "soccer ball", + "sock", + "solar thermal collector", + "sombrero", + "soup bowl", + "keyboard space bar", + "space heater", + "space shuttle", + "spatula", + "motorboat", + "spider web", + "spindle", + "sports car", + "spotlight", + "stage", + "steam locomotive", + "through arch bridge", + "steel drum", + "stethoscope", + "scarf", + "stone wall", + "stopwatch", + "stove", + "strainer", + "tram", + "stretcher", + "couch", + "stupa", + "submarine", + "suit", + "sundial", + "sunglasses", + "sunglasses", + "sunscreen", + "suspension bridge", + "mop", + "sweatshirt", + "swim trunks / shorts", + "swing", + "electrical switch", + "syringe", + "table lamp", + "tank", + "tape player", + "teapot", + "teddy bear", + "television", + "tennis ball", + "thatched roof", + "front curtain", + "thimble", + "threshing machine", + "throne", + "tile roof", + "toaster", + "tobacco shop", + "toilet seat", + "torch", + "totem pole", + "tow truck", + "toy store", + "tractor", + "semi-trailer truck", + "tray", + "trench coat", + "tricycle", + "trimaran", + "tripod", + "triumphal arch", + "trolleybus", + "trombone", + "hot tub", + "turnstile", + "typewriter keyboard", + "umbrella", + "unicycle", + "upright piano", + "vacuum cleaner", + "vase", + "vaulted or arched ceiling", + "velvet fabric", + "vending machine", + "vestment", + "viaduct", + "violin", + "volleyball", + "waffle iron", + "wall clock", + "wallet", + "wardrobe", + "military aircraft", + "sink", + "washing machine", + "water bottle", + "water jug", + "water tower", + "whiskey jug", + "whistle", + "hair wig", + "window screen", + "window shade", + "Windsor tie", + "wine bottle", + "airplane wing", + "wok", + "wooden spoon", + "wool", + "split-rail fence", + "shipwreck", + "sailboat", + "yurt", + "website", + "comic book", + "crossword", + "traffic or street sign", + "traffic light", + "dust jacket", + "menu", + "plate", + "guacamole", + "consomme", + "hot pot", + "trifle", + "ice cream", + "popsicle", + "baguette", + "bagel", + "pretzel", + "cheeseburger", + "hot dog", + "mashed potatoes", + "cabbage", + "broccoli", + "cauliflower", + "zucchini", + "spaghetti squash", + "acorn squash", + "butternut squash", + "cucumber", + "artichoke", + "bell pepper", + "cardoon", + "mushroom", + "Granny Smith apple", + "strawberry", + "orange", + "lemon", + "fig", + "pineapple", + "banana", + "jackfruit", + "cherimoya (custard apple)", + "pomegranate", + "hay", + "carbonara", + "chocolate syrup", + "dough", + "meatloaf", + "pizza", + "pot pie", + "burrito", + "red wine", + "espresso", + "tea cup", + "eggnog", + "mountain", + "bubble", + "cliff", + "coral reef", + "geyser", + "lakeshore", + "promontory", + "sandbar", + "beach", + "valley", + "volcano", + "baseball player", + "bridegroom", + "scuba diver", + "rapeseed", + "daisy", + "yellow lady's slipper", + "corn", + "acorn", + "rose hip", + "horse chestnut seed", + "coral fungus", + "agaric", + "gyromitra", + "stinkhorn mushroom", + "earth star fungus", + "hen of the woods mushroom", + "bolete", + "corn cob", + "toilet paper", +] +IMAGENET_1K_CLASS_ID_TO_LABEL = dict( + zip(range(len(IMAGENET_CLASSNAMES)), IMAGENET_CLASSNAMES) +) + +HM_CLASSNAMES = [ + "no", + "yes", + "true", + "false", +] +HM_CLASS_ID_TO_LABEL = {0: "no", 1: "yes", 2: "yes", 3: "no"} diff --git a/open_flamingo/open_flamingo/eval/coco_metric.py b/open_flamingo/open_flamingo/eval/coco_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..6f159c625963d126c5420e5362b897f954a0cef5 --- /dev/null +++ b/open_flamingo/open_flamingo/eval/coco_metric.py @@ -0,0 +1,22 @@ +from pycocoevalcap.eval import COCOEvalCap +from pycocotools.coco import COCO + + +def compute_cider( + result_path, + annotations_path, +): + # create coco object and coco_result object + coco = COCO(annotations_path) + coco_result = coco.loadRes(result_path) + + # create coco_eval object by taking coco and coco_result + coco_eval = COCOEvalCap(coco, coco_result) + coco_eval.params["image_id"] = coco_result.getImgIds() + coco_eval.evaluate() + + return coco_eval.eval + + +def postprocess_captioning_generation(predictions): + return predictions.split("Output", 1)[0] diff --git a/open_flamingo/open_flamingo/eval/eval_datasets.py b/open_flamingo/open_flamingo/eval/eval_datasets.py new file mode 100644 index 0000000000000000000000000000000000000000..fce2eb5bb2b6b4fa96834e9e9de33bc5e788c321 --- /dev/null +++ b/open_flamingo/open_flamingo/eval/eval_datasets.py @@ -0,0 +1,154 @@ +import json +import os + +from PIL import Image +from torch.utils.data import Dataset +from torchvision.datasets import ImageFolder + +from open_flamingo.eval.classification_utils import IMAGENET_1K_CLASS_ID_TO_LABEL + + +class CaptionDataset(Dataset): + def __init__( + self, + image_train_dir_path, + annotations_path, + is_train, + dataset_name, + image_val_dir_path=None, + ): + self.image_train_dir_path = image_train_dir_path + self.image_val_dir_path = image_val_dir_path + self.annotations = [] + self.is_train = is_train + self.dataset_name = dataset_name + + full_annotations = json.load(open(annotations_path))["images"] + + for i in range(len(full_annotations)): + if self.is_train and full_annotations[i]["split"] != "train": + continue + elif not self.is_train and full_annotations[i]["split"] != "test": + continue + + self.annotations.append(full_annotations[i]) + + def __len__(self): + return len(self.annotations) + + def __getitem__(self, idx): + if self.dataset_name == "coco": + image = Image.open( + os.path.join( + self.image_train_dir_path, self.annotations[idx]["filename"] + ) + if self.annotations[idx]["filepath"] == "train2014" + else os.path.join( + self.image_val_dir_path, self.annotations[idx]["filename"] + ) + ) + elif self.dataset_name == "flickr": + image = Image.open( + os.path.join( + self.image_train_dir_path, self.annotations[idx]["filename"] + ) + ) + image.load() + caption = self.annotations[idx]["sentences"][0]["raw"] + return { + "image": image, + "caption": caption, + "image_id": self.annotations[idx]["cocoid"] + if self.dataset_name == "coco" + else self.annotations[idx]["filename"].split(".")[0], + } + + +class VQADataset(Dataset): + def __init__( + self, image_dir_path, question_path, annotations_path, is_train, dataset_name + ): + self.questions = json.load(open(question_path, "r"))["questions"] + if annotations_path is not None: + self.answers = json.load(open(annotations_path, "r"))["annotations"] + else: + self.answers = None + self.image_dir_path = image_dir_path + self.is_train = is_train + self.dataset_name = dataset_name + if self.dataset_name in {"vqav2", "ok_vqa"}: + self.img_coco_split = self.image_dir_path.strip("/").split("/")[-1] + assert self.img_coco_split in {"train2014", "val2014", "test2015"} + + def __len__(self): + return len(self.questions) + + def get_img_path(self, question): + if self.dataset_name in {"vqav2", "ok_vqa"}: + return os.path.join( + self.image_dir_path, + f"COCO_{self.img_coco_split}_{question['image_id']:012d}.jpg" + if self.is_train + else f"COCO_{self.img_coco_split}_{question['image_id']:012d}.jpg", + ) + elif self.dataset_name == "vizwiz": + return os.path.join(self.image_dir_path, question["image_id"]) + elif self.dataset_name == "textvqa": + return os.path.join(self.image_dir_path, f"{question['image_id']}.jpg") + else: + raise Exception(f"Unknown VQA dataset {self.dataset_name}") + + def __getitem__(self, idx): + question = self.questions[idx] + img_path = self.get_img_path(question) + image = Image.open(img_path) + image.load() + results = { + "image": image, + "question": question["question"], + "question_id": question["question_id"], + } + if self.answers is not None: + answers = self.answers[idx] + results["answers"] = [a["answer"] for a in answers["answers"]] + return results + + +class ImageNetDataset(ImageFolder): + """Class to represent the ImageNet1k dataset.""" + + def __init__(self, root, **kwargs): + super().__init__(root=root, **kwargs) + + def __getitem__(self, idx): + sample, target = super().__getitem__(idx) + target_label = IMAGENET_1K_CLASS_ID_TO_LABEL[target] + return { + "id": idx, + "image": sample, + "class_id": target, # numeric ID of the ImageNet class + "class_name": target_label, # human-readable name of ImageNet class + } + + +class HatefulMemesDataset(Dataset): + def __init__(self, image_dir_path, annotations_path): + self.image_dir_path = image_dir_path + with open(annotations_path, "r") as f: + self.annotations = [json.loads(line) for line in f] + + def __len__(self): + return len(self.annotations) + + def __getitem__(self, idx): + annotation = self.annotations[idx] + img_path = os.path.join(self.image_dir_path, annotation["img"].split("/")[-1]) + image = Image.open(img_path) + image.load() + return { + "id": idx, + "image": image, + "ocr": annotation["text"], + "class_name": "yes" if annotation["label"] == 1 else "no", + "class_id": annotation["label"], + } diff --git a/open_flamingo/open_flamingo/eval/eval_model.py b/open_flamingo/open_flamingo/eval/eval_model.py new file mode 100644 index 0000000000000000000000000000000000000000..b35dfbbba55cd663a463092c871e54351c22ceaf --- /dev/null +++ b/open_flamingo/open_flamingo/eval/eval_model.py @@ -0,0 +1,73 @@ +import abc +import argparse +from typing import List +from torch.nn.parallel import DistributedDataParallel as DDP +from PIL import Image + + +class BaseEvalModel(abc.ABC): + """Base class encapsulating functionality needed to evaluate a model.""" + + def __init__(self, args: List[str]): + """Initialize model. + + Args: + args: arguments to model. These should be parsed, or if the model + has no applicable arguments, an error should be thrown if `args` + is non-empty. + """ + + def init_distributed(self): + """Wrap model as DDP.""" + self.model = DDP(self.model, device_ids=[self.device]) + + def set_device(self, device): + """Set device for model.""" + self.device = device + self.model = self.model.to(device) + + def get_outputs( + self, + batch_text: List[str], + batch_images: List[List[Image.Image]], + min_generation_length: int, + max_generation_length: int, + num_beams: int, + length_penalty: float, + ) -> List[str]: + """Get outputs for a batch of images and text. + + Args: + batch_text: list of text strings, with the text "" in place + of any images to be included. + batch_images: images to provide to model. Should be a list of lists, + where each list contains the images for a single example. + max_generation_length: maximum length of the generated caption. + Defaults to 10. + num_beams: number of beams to use for beam search. Defaults to 3. + length_penalty: length penalty for beam search. Defaults to -2.0. + + Returns: + List of decoded output strings. + """ + + def vqa_prompt(self, question, answer=None) -> str: + """Get the prompt to use for VQA evaluation. If the answer is not provided, it should be left blank to be generated by the model. + + Returns: + The prompt to use for VQA. + """ + + def caption_prompt(self, caption=None) -> str: + """Get the prompt to use for caption evaluation. If the caption is not provided, it should be left blank to be generated by the model. + + Returns: + The prompt to use for captioning. + """ + + def classification_prompt(self, class_str=None) -> str: + """Get the prompt to use for classification evaluation. If the class_str is not provided, it should be left blank to be generated by the model. + + Returns: + The prompt to use for classification. + """ diff --git a/open_flamingo/open_flamingo/eval/evaluate.py b/open_flamingo/open_flamingo/eval/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..36793293664d2e8208735616f4a707ef703ff8cb --- /dev/null +++ b/open_flamingo/open_flamingo/eval/evaluate.py @@ -0,0 +1,1247 @@ +import argparse +import importlib +import json +import os +import random +import uuid +from collections import defaultdict + +from einops import repeat +import more_itertools +import numpy as np +import torch +from sklearn.metrics import roc_auc_score + +from coco_metric import compute_cider, postprocess_captioning_generation +from eval_datasets import ( + CaptionDataset, + VQADataset, + ImageNetDataset, + HatefulMemesDataset, +) +from tqdm import tqdm + + +from eval_datasets import VQADataset, ImageNetDataset +from classification_utils import ( + IMAGENET_CLASSNAMES, + IMAGENET_1K_CLASS_ID_TO_LABEL, + HM_CLASSNAMES, + HM_CLASS_ID_TO_LABEL, +) + +from eval_model import BaseEvalModel + +from ok_vqa_utils import postprocess_ok_vqa_generation +from open_flamingo.src.flamingo import Flamingo +from vqa_metric import compute_vqa_accuracy, postprocess_vqa_generation + +from open_flamingo.train.distributed import init_distributed_device, world_info_from_env + +parser = argparse.ArgumentParser() + +parser.add_argument( + "--model", + type=str, + help="Model name. Currently only `OpenFlamingo` is supported.", + default="open_flamingo", +) +parser.add_argument( + "--results_file", type=str, default=None, help="JSON file to save results" +) + +# Trial arguments +parser.add_argument("--shots", nargs="+", default=[0, 4, 8, 16, 32], type=int) +parser.add_argument( + "--num_trials", + type=int, + default=1, + help="Number of trials to run for each shot using different demonstrations", +) +parser.add_argument( + "--trial_seeds", + nargs="+", + type=int, + default=[42], + help="Seeds to use for each trial for picking demonstrations and eval sets", +) +parser.add_argument( + "--num_samples", type=int, default=-1, help="Number of samples to evaluate on. -1 for all samples." +) +parser.add_argument( + "--query_set_size", type=int, default=2048, help="Size of demonstration query set" +) + +parser.add_argument("--batch_size", type=int, default=8) + +parser.add_argument("--use_kv_caching_for_classification", + action="store_true", + help="Use key-value caching for classification evals to speed it up. Currently this doesn't underperforms for MPT models." + ) + +# Per-dataset evaluation flags +parser.add_argument( + "--eval_coco", + action="store_true", + default=False, + help="Whether to evaluate on COCO.", +) +parser.add_argument( + "--eval_vqav2", + action="store_true", + default=False, + help="Whether to evaluate on VQAV2.", +) +parser.add_argument( + "--eval_ok_vqa", + action="store_true", + default=False, + help="Whether to evaluate on OK-VQA.", +) +parser.add_argument( + "--eval_vizwiz", + action="store_true", + default=False, + help="Whether to evaluate on VizWiz.", +) +parser.add_argument( + "--eval_textvqa", + action="store_true", + default=False, + help="Whether to evaluate on TextVQA.", +) +parser.add_argument( + "--eval_imagenet", + action="store_true", + default=False, + help="Whether to evaluate on ImageNet.", +) +parser.add_argument( + "--eval_flickr30", + action="store_true", + default=False, + help="Whether to evaluate on Flickr30.", +) +parser.add_argument( + "--eval_hateful_memes", + action="store_true", + default=False, + help="Whether to evaluate on Hateful Memes.", +) + +# Dataset arguments + +## Flickr30 Dataset +parser.add_argument( + "--flickr_image_dir_path", + type=str, + help="Path to the flickr30/flickr30k_images directory.", + default=None, +) +parser.add_argument( + "--flickr_karpathy_json_path", + type=str, + help="Path to the dataset_flickr30k.json file.", + default=None, +) +parser.add_argument( + "--flickr_annotations_json_path", + type=str, + help="Path to the dataset_flickr30k_coco_style.json file.", +) +## COCO Dataset +parser.add_argument( + "--coco_train_image_dir_path", + type=str, + default=None, +) +parser.add_argument( + "--coco_val_image_dir_path", + type=str, + default=None, +) +parser.add_argument( + "--coco_karpathy_json_path", + type=str, + default=None, +) +parser.add_argument( + "--coco_annotations_json_path", + type=str, + default=None, +) + +## VQAV2 Dataset +parser.add_argument( + "--vqav2_train_image_dir_path", + type=str, + default=None, +) +parser.add_argument( + "--vqav2_train_questions_json_path", + type=str, + default=None, +) +parser.add_argument( + "--vqav2_train_annotations_json_path", + type=str, + default=None, +) +parser.add_argument( + "--vqav2_test_image_dir_path", + type=str, + default=None, +) +parser.add_argument( + "--vqav2_test_questions_json_path", + type=str, + default=None, +) +parser.add_argument( + "--vqav2_test_annotations_json_path", + type=str, + default=None, +) + +## OK-VQA Dataset +parser.add_argument( + "--ok_vqa_train_image_dir_path", + type=str, + help="Path to the vqav2/train2014 directory.", + default=None, +) +parser.add_argument( + "--ok_vqa_train_questions_json_path", + type=str, + help="Path to the v2_OpenEnded_mscoco_train2014_questions.json file.", + default=None, +) +parser.add_argument( + "--ok_vqa_train_annotations_json_path", + type=str, + help="Path to the v2_mscoco_train2014_annotations.json file.", + default=None, +) +parser.add_argument( + "--ok_vqa_test_image_dir_path", + type=str, + help="Path to the vqav2/val2014 directory.", + default=None, +) +parser.add_argument( + "--ok_vqa_test_questions_json_path", + type=str, + help="Path to the v2_OpenEnded_mscoco_val2014_questions.json file.", + default=None, +) +parser.add_argument( + "--ok_vqa_test_annotations_json_path", + type=str, + help="Path to the v2_mscoco_val2014_annotations.json file.", + default=None, +) + +## VizWiz Dataset +parser.add_argument( + "--vizwiz_train_image_dir_path", + type=str, + help="Path to the vizwiz train images directory.", + default=None, +) +parser.add_argument( + "--vizwiz_test_image_dir_path", + type=str, + help="Path to the vizwiz test images directory.", + default=None, +) +parser.add_argument( + "--vizwiz_train_questions_json_path", + type=str, + help="Path to the vizwiz questions json file.", + default=None, +) +parser.add_argument( + "--vizwiz_train_annotations_json_path", + type=str, + help="Path to the vizwiz annotations json file.", + default=None, +) +parser.add_argument( + "--vizwiz_test_questions_json_path", + type=str, + help="Path to the vizwiz questions json file.", + default=None, +) +parser.add_argument( + "--vizwiz_test_annotations_json_path", + type=str, + help="Path to the vizwiz annotations json file.", + default=None, +) + +# TextVQA Dataset +parser.add_argument( + "--textvqa_image_dir_path", + type=str, + help="Path to the textvqa images directory.", + default=None, +) +parser.add_argument( + "--textvqa_train_questions_json_path", + type=str, + help="Path to the textvqa questions json file.", + default=None, +) +parser.add_argument( + "--textvqa_train_annotations_json_path", + type=str, + help="Path to the textvqa annotations json file.", + default=None, +) +parser.add_argument( + "--textvqa_test_questions_json_path", + type=str, + help="Path to the textvqa questions json file.", + default=None, +) +parser.add_argument( + "--textvqa_test_annotations_json_path", + type=str, + help="Path to the textvqa annotations json file.", + default=None, +) + +## Imagenet dataset +parser.add_argument("--imagenet_root", type=str, default="/tmp") + +## Hateful Memes dataset +parser.add_argument( + "--hateful_memes_image_dir_path", + type=str, + default=None, +) +parser.add_argument( + "--hateful_memes_train_annotations_json_path", + type=str, + default=None, +) +parser.add_argument( + "--hateful_memes_test_annotations_json_path", + type=str, + default=None, +) + +# Distributed evaluation +parser.add_argument( + "--dist-url", + default="env://", + type=str, + help="url used to set up distributed training", +) +parser.add_argument( + "--dist-backend", default="nccl", type=str, help="distributed backend" +) +parser.add_argument( + "--horovod", + default=False, + action="store_true", + help="Use horovod for distributed training.", +) +parser.add_argument( + "--no-set-device-rank", + default=False, + action="store_true", + help="Don't set device index from local rank (when CUDA_VISIBLE_DEVICES restricted to one per proc).", +) + + +def main(): + args, leftovers = parser.parse_known_args() + module = importlib.import_module(f"open_flamingo.eval.models.{args.model}") + + model_args = { + leftovers[i].lstrip("-"): leftovers[i + 1] for i in range(0, len(leftovers), 2) + } + eval_model = module.EvalModel(model_args) + + # set up distributed evaluation + args.local_rank, args.rank, args.world_size = world_info_from_env() + device_id = init_distributed_device(args) + eval_model.set_device(device_id) + eval_model.init_distributed() + + if args.model != "open_flamingo" and args.shots != [0]: + raise ValueError("Only 0 shot eval is supported for non-open_flamingo models") + + if len(args.trial_seeds) != args.num_trials: + raise ValueError("Number of trial seeds must be == number of trials.") + + results = defaultdict(list) + + if args.eval_flickr30: + print("Evaluating on Flickr30k...") + for shot in args.shots: + scores = [] + for seed, trial in zip(args.trial_seeds, range(args.num_trials)): + cider_score = evaluate_captioning( + args, + eval_model=eval_model, + num_shots=shot, + seed=seed, + dataset_name="flickr", + min_generation_length=12, + max_generation_length=30, + num_beams=5, + ) + if args.rank == 0: + print(f"Shots {shot} Trial {trial} CIDEr score: {cider_score}") + scores.append(cider_score) + + if args.rank == 0: + print(f"Shots {shot} Mean CIDEr score: {np.nanmean(scores)}") + results["flickr30"].append( + {"shots": shot, "trials": scores, "mean": np.nanmean(scores)} + ) + + if args.eval_coco: + print("Evaluating on COCO...") + for shot in args.shots: + scores = [] + for seed, trial in zip(args.trial_seeds, range(args.num_trials)): + cider_score = evaluate_captioning( + args, + eval_model=eval_model, + num_shots=shot, + seed=seed, + dataset_name="coco", + ) + if args.rank == 0: + print(f"Shots {shot} Trial {trial} CIDEr score: {cider_score}") + scores.append(cider_score) + + if args.rank == 0: + print(f"Shots {shot} Mean CIDEr score: {np.nanmean(scores)}") + results["coco"].append( + {"shots": shot, "trials": scores, "mean": np.nanmean(scores)} + ) + + if args.eval_ok_vqa: + print("Evaluating on OK-VQA...") + for shot in args.shots: + scores = [] + for seed, trial in zip(args.trial_seeds, range(args.num_trials)): + ok_vqa_score = evaluate_vqa( + args=args, + eval_model=eval_model, + num_shots=shot, + seed=seed, + dataset_name="ok_vqa", + ) + if args.rank == 0: + print(f"Shots {shot} Trial {trial} OK-VQA score: {ok_vqa_score}") + scores.append(ok_vqa_score) + + if args.rank == 0: + print(f"Shots {shot} Mean OK-VQA score: {np.nanmean(scores)}") + results["ok_vqa"].append( + {"shots": shot, "trials": scores, "mean": np.nanmean(scores)} + ) + + if args.eval_vqav2: + print("Evaluating on VQAv2...") + for shot in args.shots: + scores = [] + for seed, trial in zip(args.trial_seeds, range(args.num_trials)): + vqa_score = evaluate_vqa( + args=args, + eval_model=eval_model, + num_shots=shot, + seed=seed, + dataset_name="vqav2", + ) + if args.rank == 0: + print(f"Shots {shot} Trial {trial} VQA score: {vqa_score}") + scores.append(vqa_score) + + if args.rank == 0: + print(f"Shots {shot} Mean VQA score: {np.nanmean(scores)}") + results["vqav2"].append( + {"shots": shot, "trials": scores, "mean": np.nanmean(scores)} + ) + + if args.eval_vizwiz: + print("Evaluating on VizWiz...") + for shot in args.shots: + scores = [] + for seed, trial in zip(args.trial_seeds, range(args.num_trials)): + vizwiz_score = evaluate_vqa( + args=args, + eval_model=eval_model, + num_shots=shot, + seed=seed, + dataset_name="vizwiz", + ) + if args.rank == 0: + print(f"Shots {shot} Trial {trial} VizWiz score: {vizwiz_score}") + scores.append(vizwiz_score) + + if args.rank == 0: + print(f"Shots {shot} Mean VizWiz score: {np.nanmean(scores)}") + results["vizwiz"].append( + {"shots": shot, "trials": scores, "mean": np.nanmean(scores)} + ) + + if args.eval_textvqa: + print("Evaluating on TextVQA...") + for shot in args.shots: + scores = [] + for seed, trial in zip(args.trial_seeds, range(args.num_trials)): + textvqa_score = evaluate_vqa( + args=args, + eval_model=eval_model, + num_shots=shot, + seed=seed, + dataset_name="textvqa", + max_generation_length=10, + ) + if args.rank == 0: + print(f"Shots {shot} Trial {trial} TextVQA score: {textvqa_score}") + scores.append(textvqa_score) + + if args.rank == 0: + print(f"Shots {shot} Mean TextVQA score: {np.nanmean(scores)}") + results["textvqa"].append( + {"shots": shot, "trials": scores, "mean": np.nanmean(scores)} + ) + + if args.eval_imagenet: + print("Evaluating on ImageNet...") + for shot in args.shots: + scores = [] + for seed, trial in zip(args.trial_seeds, range(args.num_trials)): + imagenet_score = evaluate_classification( + args, + eval_model=eval_model, + num_shots=shot, + seed=seed, + use_kv_caching=args.use_kv_caching_for_classification, + dataset_name="imagenet", + ) + if args.rank == 0: + print( + f"Shots {shot} Trial {trial} " f"ImageNet score: {imagenet_score}" + ) + scores.append(imagenet_score) + + if args.rank == 0: + print(f"Shots {shot} Mean ImageNet score: {np.nanmean(scores)}") + results["imagenet"].append( + {"shots": shot, "trials": scores, "mean": np.nanmean(scores)} + ) + + if args.eval_hateful_memes: + print("Evaluating on Hateful Memes...") + for shot in args.shots: + scores = [] + for seed, trial in zip(args.trial_seeds, range(args.num_trials)): + hateful_memes_score = evaluate_classification( + args, + eval_model=eval_model, + num_shots=shot, + seed=seed, + use_kv_caching=args.use_kv_caching_for_classification, + dataset_name="hateful_memes", + ) + if args.rank == 0: + print( + f"Shots {shot} Trial {trial} " + f"Hateful Memes score: {hateful_memes_score}" + ) + scores.append(hateful_memes_score) + + if args.rank == 0: + print(f"Shots {shot} Mean Hateful Memes score: {np.nanmean(scores)}") + results["hateful_memes"].append( + {"shots": shot, "trials": scores, "mean": np.nanmean(scores)} + ) + + if args.rank == 0 and args.results_file is not None: + with open(args.results_file, "w") as f: + json.dump(results, f) + + +def get_random_indices(num_samples, query_set_size, full_dataset, seed): + if num_samples + query_set_size > len(full_dataset): + raise ValueError( + f"num_samples + query_set_size must be less than {len(full_dataset)}" + ) + + # get a random subset of the dataset + np.random.seed(seed) + random_indices = np.random.choice( + len(full_dataset), num_samples + query_set_size, replace=False + ) + return random_indices + + +def get_query_set(train_dataset, query_set_size, seed): + np.random.seed(seed) + query_set = np.random.choice(len(train_dataset), query_set_size, replace=False) + return [train_dataset[i] for i in query_set] + + +def prepare_eval_samples(test_dataset, num_samples, batch_size, seed): + np.random.seed(seed) + random_indices = np.random.choice(len(test_dataset), num_samples, replace=False) + dataset = torch.utils.data.Subset(test_dataset, random_indices) + sampler = torch.utils.data.distributed.DistributedSampler(dataset) + loader = torch.utils.data.DataLoader( + dataset, + batch_size=batch_size, + sampler=sampler, + collate_fn=custom_collate_fn, + ) + return loader + + +def sample_batch_demos_from_query_set(query_set, num_samples, batch_size): + return [random.sample(query_set, num_samples) for _ in range(batch_size)] + + +def compute_effective_num_shots(num_shots, model_type): + if model_type == "open_flamingo": + return num_shots if num_shots > 0 else 2 + return num_shots + + +def custom_collate_fn(batch): + collated_batch = {} + for key in batch[0].keys(): + collated_batch[key] = [item[key] for item in batch] + return collated_batch + + +def evaluate_captioning( + args: argparse.Namespace, + eval_model: BaseEvalModel, + seed: int = 42, + min_generation_length: int = 0, + max_generation_length: int = 20, + num_beams: int = 3, + length_penalty: float = 0.0, + num_shots: int = 8, + dataset_name: str = "coco", +): + """Evaluate a model on COCO dataset. + + Args: + args (argparse.Namespace): arguments + eval_model (BaseEvalModel): model to evaluate + seed (int, optional): seed for random number generator. Defaults to 42. + max_generation_length (int, optional): maximum length of the generated caption. Defaults to 20. + num_beams (int, optional): number of beams to use for beam search. Defaults to 3. + length_penalty (float, optional): length penalty for beam search. Defaults to -2.0. + num_shots (int, optional): number of in-context samples to use. Defaults to 8. + dataset_name (str, optional): dataset to evaluate on. Can be "coco" or "flickr". Defaults to "coco". + Returns: + float: CIDEr score + + """ + + if dataset_name == "coco": + image_train_dir_path = args.coco_train_image_dir_path + image_val_dir_path = args.coco_val_image_dir_path + annotations_path = args.coco_karpathy_json_path + elif dataset_name == "flickr": + image_train_dir_path = ( + args.flickr_image_dir_path + ) # Note: calling this "train" for consistency with COCO but Flickr only has one split for images + image_val_dir_path = None + annotations_path = args.flickr_karpathy_json_path + else: + raise ValueError(f"Unsupported dataset: {dataset_name}") + + train_dataset = CaptionDataset( + image_train_dir_path=image_train_dir_path, + image_val_dir_path=image_val_dir_path, + annotations_path=annotations_path, + is_train=True, + dataset_name=dataset_name if dataset_name != "nocaps" else "coco", + ) + + test_dataset = CaptionDataset( + image_train_dir_path=image_train_dir_path, + image_val_dir_path=image_val_dir_path, + annotations_path=annotations_path, + is_train=False, + dataset_name=dataset_name, + ) + + effective_num_shots = compute_effective_num_shots(num_shots, args.model) + + test_dataset = prepare_eval_samples( + test_dataset, + args.num_samples if args.num_samples > 0 else len(test_dataset), + args.batch_size, + seed, + ) + + in_context_samples = get_query_set(train_dataset, args.query_set_size, seed) + + predictions = defaultdict() + + for batch in tqdm(test_dataset, desc=f"Running inference {dataset_name.upper()}"): + batch_demo_samples = sample_batch_demos_from_query_set( + in_context_samples, effective_num_shots, len(batch["image"]) + ) + + batch_images = [] + batch_text = [] + for i in range(len(batch["image"])): + if num_shots > 0: + context_images = [x["image"] for x in batch_demo_samples[i]] + else: + context_images = [] + batch_images.append(context_images + [batch["image"][i]]) + + context_text = "".join( + [ + eval_model.get_caption_prompt(caption=x["caption"].strip()) + for x in batch_demo_samples[i] + ] + ) + + # Keep the text but remove the image tags for the zero-shot case + if num_shots == 0: + context_text = context_text.replace("", "") + + batch_text.append(context_text + eval_model.get_caption_prompt()) + + outputs = eval_model.get_outputs( + batch_images=batch_images, + batch_text=batch_text, + min_generation_length=min_generation_length, + max_generation_length=max_generation_length, + num_beams=num_beams, + length_penalty=length_penalty, + ) + + new_predictions = [ + postprocess_captioning_generation(out).replace('"', "") for out in outputs + ] + + for i, sample_id in enumerate(batch["image_id"]): + predictions[sample_id] = { + "caption": new_predictions[i], + } + + # all gather + all_predictions = [None] * args.world_size + torch.distributed.all_gather_object(all_predictions, predictions) # list of dicts + + if args.rank != 0: + return + + all_predictions = { + k: v for d in all_predictions for k, v in d.items() + } # merge dicts + + # save the predictions to a temporary file + results_path = f"{dataset_name}results_{uuid.uuid4()}.json" + + with open(results_path, "w") as f: + f.write( + json.dumps( + [ + {"image_id": k, "caption": all_predictions[k]["caption"]} + for k in all_predictions + ], + indent=4, + ) + ) + + metrics = compute_cider( + result_path=results_path, + annotations_path=args.coco_annotations_json_path + if dataset_name == "coco" + else args.flickr_annotations_json_path, + ) + + # delete the temporary file + os.remove(results_path) + + return metrics["CIDEr"] * 100.0 + + +def evaluate_vqa( + args: argparse.Namespace, + eval_model: BaseEvalModel, + seed: int = 42, + min_generation_length: int = 0, + max_generation_length: int = 5, + num_beams: int = 3, + length_penalty: float = -2.0, + num_shots: int = 8, + dataset_name: str = "vqav2", +): + """ + Evaluate a model on VQA datasets. Currently supports VQA v2.0, OK-VQA, VizWiz and TextVQA. + + Args: + args (argparse.Namespace): arguments + eval_model (BaseEvalModel): model to evaluate + seed (int, optional): random seed. Defaults to 42. + max_generation_length (int, optional): max generation length. Defaults to 5. + num_beams (int, optional): number of beams to use for beam search. Defaults to 3. + length_penalty (float, optional): length penalty for beam search. Defaults to -2.0. + num_shots (int, optional): number of shots to use. Defaults to 8. + dataset_name (string): type of vqa dataset: currently supports vqav2, ok_vqa. Defaults to vqav2. + Returns: + float: accuracy score + """ + + if dataset_name == "ok_vqa": + train_image_dir_path = args.ok_vqa_train_image_dir_path + train_questions_json_path = args.ok_vqa_train_questions_json_path + train_annotations_json_path = args.ok_vqa_train_annotations_json_path + test_image_dir_path = args.ok_vqa_test_image_dir_path + test_questions_json_path = args.ok_vqa_test_questions_json_path + test_annotations_json_path = args.ok_vqa_test_annotations_json_path + elif dataset_name == "vqav2": + train_image_dir_path = args.vqav2_train_image_dir_path + train_questions_json_path = args.vqav2_train_questions_json_path + train_annotations_json_path = args.vqav2_train_annotations_json_path + test_image_dir_path = args.vqav2_test_image_dir_path + test_questions_json_path = args.vqav2_test_questions_json_path + test_annotations_json_path = args.vqav2_test_annotations_json_path + elif dataset_name == "vizwiz": + train_image_dir_path = args.vizwiz_train_image_dir_path + train_questions_json_path = args.vizwiz_train_questions_json_path + train_annotations_json_path = args.vizwiz_train_annotations_json_path + test_image_dir_path = args.vizwiz_test_image_dir_path + test_questions_json_path = args.vizwiz_test_questions_json_path + test_annotations_json_path = args.vizwiz_test_annotations_json_path + elif dataset_name == "textvqa": + train_image_dir_path = args.textvqa_image_dir_path + train_questions_json_path = args.textvqa_train_questions_json_path + train_annotations_json_path = args.textvqa_train_annotations_json_path + test_image_dir_path = args.textvqa_image_dir_path + test_questions_json_path = args.textvqa_test_questions_json_path + test_annotations_json_path = args.textvqa_test_annotations_json_path + else: + raise ValueError(f"Unsupported dataset: {dataset_name}") + + train_dataset = VQADataset( + image_dir_path=train_image_dir_path, + question_path=train_questions_json_path, + annotations_path=train_annotations_json_path, + is_train=True, + dataset_name=dataset_name, + ) + + test_dataset = VQADataset( + image_dir_path=test_image_dir_path, + question_path=test_questions_json_path, + annotations_path=test_annotations_json_path, + is_train=False, + dataset_name=dataset_name, + ) + + effective_num_shots = compute_effective_num_shots(num_shots, args.model) + + test_dataset = prepare_eval_samples( + test_dataset, + args.num_samples if args.num_samples > 0 else len(test_dataset), + args.batch_size, + seed, + ) + + in_context_samples = get_query_set(train_dataset, args.query_set_size, seed) + predictions = [] + + for batch in tqdm(test_dataset, desc=f"Running inference {dataset_name.upper()}"): + batch_demo_samples = sample_batch_demos_from_query_set( + in_context_samples, effective_num_shots, len(batch["image"]) + ) + + batch_images = [] + batch_text = [] + for i in range(len(batch["image"])): + if num_shots > 0: + context_images = [x["image"] for x in batch_demo_samples[i]] + else: + context_images = [] + batch_images.append(context_images + [batch["image"][i]]) + + context_text = "".join( + [ + eval_model.get_vqa_prompt( + question=x["question"], answer=x["answers"][0] + ) + for x in batch_demo_samples[i] + ] + ) + + # Keep the text but remove the image tags for the zero-shot case + if num_shots == 0: + context_text = context_text.replace("", "") + + batch_text.append( + context_text + eval_model.get_vqa_prompt(question=batch["question"][i]) + ) + + outputs = eval_model.get_outputs( + batch_images=batch_images, + batch_text=batch_text, + min_generation_length=min_generation_length, + max_generation_length=max_generation_length, + num_beams=num_beams, + length_penalty=length_penalty, + ) + + process_function = ( + postprocess_ok_vqa_generation + if dataset_name == "ok_vqa" + else postprocess_vqa_generation + ) + + new_predictions = map(process_function, outputs) + + for new_prediction, sample_id in zip(new_predictions, batch["question_id"]): + predictions.append({"answer": new_prediction, "question_id": sample_id}) + + # all gather + all_predictions = [None] * args.world_size + torch.distributed.all_gather_object(all_predictions, predictions) # list of lists + if args.rank != 0: + return + + all_predictions = [ + item for sublist in all_predictions for item in sublist + ] # flatten + + # save the predictions to a temporary file + random_uuid = str(uuid.uuid4()) + with open(f"{dataset_name}results_{random_uuid}.json", "w") as f: + f.write(json.dumps(all_predictions, indent=4)) + + if test_annotations_json_path is not None: + acc = compute_vqa_accuracy( + f"{dataset_name}results_{random_uuid}.json", + test_questions_json_path, + test_annotations_json_path, + ) + # delete the temporary file + os.remove(f"{dataset_name}results_{random_uuid}.json") + + else: + print("No annotations provided, skipping accuracy computation.") + print("Temporary file saved to:", f"{dataset_name}results_{random_uuid}.json") + acc = None + + return acc + + +def evaluate_classification( + args: argparse.Namespace, + eval_model, + seed: int = 42, + num_shots: int = 8, + use_kv_caching=False, + dataset_name: str = "imagenet", +): + """ + Evaluate a model on classification dataset. + + Args: + eval_model (BaseEvalModel): model to evaluate + imagenet_root (str): path to imagenet root for the specified split. + seed (int, optional): random seed. Defaults to 42. + num_shots (int, optional): number of shots to use. Defaults to 8. + dataset_name (str, optional): dataset name. Defaults to "imagenet". + + Returns: + float: accuracy score + """ + if args.model != "open_flamingo": + raise NotImplementedError( + "evaluate_classification is currently only supported for OpenFlamingo " + "models" + ) + batch_size = args.batch_size + num_samples = args.num_samples + np.random.seed(seed) + model, tokenizer = eval_model.model, eval_model.tokenizer + + if dataset_name == "imagenet": + train_dataset = ImageNetDataset(os.path.join(args.imagenet_root, "train")) + test_dataset = ImageNetDataset(os.path.join(args.imagenet_root, "val")) + elif dataset_name == "hateful_memes": + train_dataset = HatefulMemesDataset( + args.hateful_memes_image_dir_path, + args.hateful_memes_train_annotations_json_path, + ) + test_dataset = HatefulMemesDataset( + args.hateful_memes_image_dir_path, + args.hateful_memes_test_annotations_json_path, + ) + else: + raise ValueError(f"Unsupported dataset {dataset_name}") + + effective_num_shots = compute_effective_num_shots(num_shots, args.model) + + test_dataloader = prepare_eval_samples( + test_dataset, + args.num_samples if args.num_samples > 0 else len(test_dataset), + batch_size, + seed, + ) + + acc1 = 0 + acc5 = 0 + + if dataset_name == "imagenet": + prompt_text = "Output:" + elif dataset_name == "hateful_memes": + prompt_text = "is an image with: '{meme_text}' written on it. Is it hateful? Answer: " + + predictions = [] + + for batch_idx, batch in tqdm( + enumerate(test_dataloader), desc=f"Running inference {dataset_name}", disable=args.rank != 0 + ): + batch_images = [] + batch_text = [] + + for idx in range(len(batch["image"])): + # Choose a different set of random context samples for each sample + # from the training set + context_indices = np.random.choice( + len(train_dataset), effective_num_shots, replace=False + ) + + in_context_samples = [train_dataset[i] for i in context_indices] + + if num_shots > 0: + vision_x = [ + eval_model.image_processor(data["image"]).unsqueeze(0) + for data in in_context_samples + ] + else: + vision_x = [] + + vision_x = vision_x + [eval_model.image_processor(batch["image"][idx]).unsqueeze(0)] + batch_images.append(torch.cat(vision_x, dim=0)) + + def sample_to_prompt(sample): + if dataset_name == "hateful_memes": + return prompt_text.replace("{meme_text}", sample["ocr"]) + else: + return prompt_text + + context_text = "".join( + f"{sample_to_prompt(in_context_samples[i])}{in_context_samples[i]['class_name']}<|endofchunk|>" + for i in range(effective_num_shots) + ) + + # Keep the text but remove the image tags for the zero-shot case + if num_shots == 0: + context_text = context_text.replace("", "") + + batch_text.append(context_text) + + # shape [B, T_img, C, h, w] + vision_x = torch.stack(batch_images, dim=0) + # shape [B, T_img, 1, C, h, w] where 1 is the frame dimension + vision_x = vision_x.unsqueeze(2) + + # Cache the context text: tokenize context and prompt, + # e.g. ' a picture of a ' + text_x = [ + context_text + + sample_to_prompt({k: batch[k][idx] for k in batch.keys()}) + for idx, context_text in enumerate(batch_text) + ] + + ctx_and_prompt_tokenized = tokenizer( + text_x, + return_tensors="pt", + padding="longest", + max_length=2000, + ) + + ctx_and_prompt_input_ids = ctx_and_prompt_tokenized["input_ids"].to(eval_model.device) + ctx_and_prompt_attention_mask = ctx_and_prompt_tokenized["attention_mask"].to(eval_model.device).bool() + + def _detach_pkvs(pkvs): + """Detach a set of past key values.""" + return list([tuple([x.detach() for x in inner]) for inner in pkvs]) + + if use_kv_caching: + eval_model.cache_media(input_ids=ctx_and_prompt_input_ids, vision_x=vision_x.to(eval_model.device)) + + with torch.no_grad(): + precomputed = eval_model.model( + vision_x=None, + lang_x=ctx_and_prompt_input_ids, + attention_mask=ctx_and_prompt_attention_mask, + clear_conditioned_layers=False, + use_cache=True, + ) + + precomputed_pkvs = _detach_pkvs(precomputed.past_key_values) + precomputed_logits = precomputed.logits.detach() + else: + precomputed_pkvs = None + precomputed_logits = None + + if dataset_name == "imagenet": + all_class_names = IMAGENET_CLASSNAMES + else: + all_class_names = HM_CLASSNAMES + + if dataset_name == "imagenet": + class_id_to_name = IMAGENET_1K_CLASS_ID_TO_LABEL + else: + class_id_to_name = HM_CLASS_ID_TO_LABEL + + overall_probs = [] + for class_name in all_class_names: + past_key_values = None + # Tokenize only the class name and iteratively decode the model's + # predictions for this class. + classname_tokens = tokenizer( + class_name, add_special_tokens=False, return_tensors="pt" + )["input_ids"].to(eval_model.device) + + if classname_tokens.ndim == 1: # Case: classname is only 1 token + classname_tokens = torch.unsqueeze(classname_tokens, 1) + + classname_tokens = repeat( + classname_tokens, "b s -> (repeat b) s", repeat=len(batch_text) + ) + + if use_kv_caching: + # Compute the outputs one token at a time, using cached + # activations. + + # Initialize the elementwise predictions with the last set of + # logits from precomputed; this will correspond to the predicted + # probability of the first position/token in the imagenet + # classname. We will append the logits for each token to this + # list (each element has shape [B, 1, vocab_size]). + elementwise_logits = [precomputed_logits[:, -2:-1, :]] + + for token_idx in range(classname_tokens.shape[1]): + _lang_x = classname_tokens[:, token_idx].reshape((-1, 1)) + outputs = eval_model.get_logits( + lang_x=_lang_x, + past_key_values=( + past_key_values if token_idx > 0 else precomputed_pkvs + ), + clear_conditioned_layers=False, + ) + past_key_values = _detach_pkvs(outputs.past_key_values) + elementwise_logits.append(outputs.logits.detach()) + + # logits/probs has shape [B, classname_tokens + 1, vocab_size] + logits = torch.concat(elementwise_logits, 1) + probs = torch.softmax(logits, dim=-1) + + # collect the probability of the generated token -- probability + # at index 0 corresponds to the token at index 1. + probs = probs[:, :-1, :] # shape [B, classname_tokens, vocab_size] + + gen_probs = torch.gather(probs, 2, classname_tokens[:, :, None]).squeeze(-1).cpu() + + class_prob = torch.prod(gen_probs, 1).numpy() + else: + # Compute the outputs without using cached + # activations. + + # contatenate the class name tokens to the end of the context + # tokens + _lang_x = torch.cat([ctx_and_prompt_input_ids, classname_tokens], dim=1) + _attention_mask = torch.cat( + [ + ctx_and_prompt_attention_mask, + torch.ones_like(classname_tokens).bool(), + ], + dim=1, + ) + + outputs = eval_model.get_logits( + vision_x=vision_x.to(eval_model.device), + lang_x=_lang_x.to(eval_model.device), + attention_mask=_attention_mask.to(eval_model.device), + clear_conditioned_layers=True, + ) + + logits = outputs.logits.detach().float() + probs = torch.softmax(logits, dim=-1) + + # get probability of the generated class name tokens + gen_probs = probs[:, ctx_and_prompt_input_ids.shape[1]-1:_lang_x.shape[1], :] + gen_probs = torch.gather(gen_probs, 2, classname_tokens[:, :, None]).squeeze(-1).cpu() + class_prob = torch.prod(gen_probs, 1).numpy() + + overall_probs.append(class_prob) + + overall_probs = np.row_stack(overall_probs).T # shape [B, num_classes] + + eval_model.uncache_media() + + def topk(probs_ary: np.ndarray, k: int) -> np.ndarray: + """Return the indices of the top k elements in probs_ary.""" + return np.argsort(probs_ary)[::-1][:k] + + for i in range(len(batch_text)): + highest_prob_idxs = topk(overall_probs[i], 5) + + top5 = [class_id_to_name[pred] for pred in highest_prob_idxs] + + y_i = batch["class_name"][i] + acc5 += int(y_i in set(top5)) + acc1 += int(y_i == top5[0]) + + if dataset_name == "hateful_memes": + # sum over the probabilities of the different classes + binary_probs = [overall_probs[i][0] + overall_probs[i][3], overall_probs[i][1] + overall_probs[i][2]] + + predictions.append({ + "id": batch["id"][i], + "gt_label": y_i, + "pred_label": top5[0], + "pred_score": binary_probs[highest_prob_idxs[0]] if dataset_name == "hateful_memes" else None, # only for hateful memes + }) + + # all gather + all_predictions = [None] * args.world_size + torch.distributed.all_gather_object(all_predictions, predictions) # list of lists + if args.rank != 0: + return + + all_predictions = [ + item for sublist in all_predictions for item in sublist + ] # flatten + + # Hack to remove samples with duplicate ids (only necessary for multi-GPU evaluation) + all_predictions = {pred["id"]: pred for pred in all_predictions}.values() + + assert len(all_predictions) == len(test_dataset) # sanity check + + if dataset_name == "hateful_memes": + # return ROC-AUC score + gts = [pred["gt_label"] for pred in all_predictions] + pred_scores = [pred["pred_score"] for pred in all_predictions] + return roc_auc_score(gts, pred_scores) + else: + # return top-1 accuracy + acc1 = sum( + int(pred["gt_label"] == pred["pred_label"]) + for pred in all_predictions + ) + return float(acc1) / len(all_predictions) + +if __name__ == "__main__": + main() diff --git a/open_flamingo/open_flamingo/eval/models/blip.py b/open_flamingo/open_flamingo/eval/models/blip.py new file mode 100644 index 0000000000000000000000000000000000000000..59f693ae7c9f536b0925ee76143bff74991ab7fa --- /dev/null +++ b/open_flamingo/open_flamingo/eval/models/blip.py @@ -0,0 +1,113 @@ +from typing import List + +from PIL import Image +import torch + +from transformers import Blip2Processor, Blip2ForConditionalGeneration +from open_flamingo.eval.eval_model import BaseEvalModel +from open_flamingo.eval.models.utils import unwrap_model + +class EvalModel(BaseEvalModel): + """BLIP-2 model evaluation. + + Attributes: + model (nn.Module): Underlying Torch model. + tokenizer (transformers.PreTrainedTokenizer): Tokenizer for model. + device: Index of GPU to use, or the string "cpu" + """ + + def __init__(self, model_args): + assert ( + "processor_path" in model_args + and "lm_path" in model_args + and "device" in model_args + ), "BLIP-2 requires processor_path, lm_path, and device arguments to be specified" + + self.device = ( + int(model_args["device"]) + if ("device" in model_args and model_args["device"] >= 0) + else "cpu" + ) + self.processor = Blip2Processor.from_pretrained(model_args["processor_path"]) + self.model = Blip2ForConditionalGeneration.from_pretrained( + model_args["lm_path"] + ) + self.model.to(self.device) + self.model.eval() + self.processor.tokenizer.padding_side = "left" + + def _prepare_images(self, batch: List[List[torch.Tensor]]) -> torch.Tensor: + """Preprocess images and stack them. + + Args: + batch: A list of lists of images. + + Returns: + A Tensor of shape + (batch_size, channels, height, width). + """ + batch_images = None + assert all( + len(example) == 1 for example in batch + ), "BLIP-2 only supports one image per example" + + for example in batch: + assert len(example) == 1, "BLIP-2 only supports one image per example" + batch_images = torch.cat( + [ + batch_images, + self.processor.image_processor(example, return_tensors="pt")[ + "pixel_values" + ], + ] + if batch_images is not None + else [ + self.processor.image_processor(example, return_tensors="pt")[ + "pixel_values" + ] + ], + dim=0, + ) + return batch_images + + def get_outputs( + self, + batch_text: List[str], + batch_images: List[List[Image.Image]], + max_generation_length: int, + num_beams: int, + length_penalty: float, + ) -> List[str]: + encodings = self.processor.tokenizer( + batch_text, + padding="longest", + truncation=True, + return_tensors="pt", + max_length=2000, + ) + input_ids = encodings["input_ids"] + attention_mask = encodings["attention_mask"] + + with torch.inference_mode(): + outputs = unwrap_model(self.model).generate( + self._prepare_images(batch_images).to(self.device), + input_ids.to(self.device), + attention_mask=attention_mask.to(self.device), + max_new_tokens=max_generation_length, + min_new_tokens=8, + num_beams=num_beams, + length_penalty=length_penalty, + ) + + return self.processor.tokenizer.batch_decode(outputs, skip_special_tokens=True) + + def get_vqa_prompt(self, question, answer=None) -> str: + return ( + f"Question:{question} Short answer:{answer if answer is not None else ''}" + ) + + def get_caption_prompt(self, caption=None) -> str: + return f"A photo of {caption if caption is not None else ''}" + + def get_classification_prompt(self, class_str=None) -> str: + raise NotImplementedError diff --git a/open_flamingo/open_flamingo/eval/models/open_flamingo.py b/open_flamingo/open_flamingo/eval/models/open_flamingo.py new file mode 100644 index 0000000000000000000000000000000000000000..c7328bece80b785d89c8ad37ee5a5faab3c3300f --- /dev/null +++ b/open_flamingo/open_flamingo/eval/models/open_flamingo.py @@ -0,0 +1,176 @@ +from typing import List + +from PIL import Image +import torch + +from open_flamingo.eval.eval_model import BaseEvalModel +from open_flamingo.src.factory import create_model_and_transforms +from contextlib import suppress +from open_flamingo.eval.models.utils import unwrap_model + +class EvalModel(BaseEvalModel): + """OpenFlamingo model evaluation. + + Attributes: + model (nn.Module): Underlying Torch model. + tokenizer (transformers.PreTrainedTokenizer): Tokenizer for model. + device: Index of GPU to use, or the string "CPU" + """ + + def __init__(self, model_args): + assert ( + "vision_encoder_path" in model_args + and "lm_path" in model_args + and "checkpoint_path" in model_args + and "lm_tokenizer_path" in model_args + and "cross_attn_every_n_layers" in model_args + and "vision_encoder_pretrained" in model_args + and "precision" in model_args + ), "OpenFlamingo requires vision_encoder_path, lm_path, device, checkpoint_path, lm_tokenizer_path, cross_attn_every_n_layers, vision_encoder_pretrained, and precision arguments to be specified" + + self.device = ( + model_args["device"] + if ("device" in model_args and model_args["device"] >= 0) + else "cpu" + ) + + ( + self.model, + self.image_processor, + self.tokenizer, + ) = create_model_and_transforms( + model_args["vision_encoder_path"], + model_args["vision_encoder_pretrained"], + model_args["lm_path"], + model_args["lm_tokenizer_path"], + cross_attn_every_n_layers=int(model_args["cross_attn_every_n_layers"]), + ) + checkpoint = torch.load(model_args["checkpoint_path"], map_location="cpu") + if "model_state_dict" in checkpoint: + checkpoint = checkpoint["model_state_dict"] + checkpoint = {k.replace("module.", ""): v for k, v in checkpoint.items()} + self.model.load_state_dict(checkpoint, strict=False) + self.model.to(self.device) + self.model.eval() + self.tokenizer.padding_side = "left" + + # autocast + self.autocast = get_autocast(model_args["precision"]) + self.cast_dtype = get_cast_dtype(model_args["precision"]) + + def _prepare_images(self, batch: List[List[torch.Tensor]]) -> torch.Tensor: + """Preprocess images and stack them. + + Args: + batch: A list of lists of images. + + Returns: + A Tensor of shape + (batch_size, images_per_example, frames, channels, height, width). + """ + images_per_example = max(len(x) for x in batch) + batch_images = None + for iexample, example in enumerate(batch): + for iimage, image in enumerate(example): + preprocessed = self.image_processor(image) + + if batch_images is None: + batch_images = torch.zeros( + (len(batch), images_per_example, 1) + preprocessed.shape, + dtype=preprocessed.dtype, + ) + batch_images[iexample, iimage, 0] = preprocessed + return batch_images + + def get_outputs( + self, + batch_text: List[str], + batch_images: List[List[Image.Image]], + min_generation_length: int, + max_generation_length: int, + num_beams: int, + length_penalty: float, + ) -> List[str]: + encodings = self.tokenizer( + batch_text, + padding="longest", + truncation=True, + return_tensors="pt", + max_length=2000, + ) + input_ids = encodings["input_ids"] + attention_mask = encodings["attention_mask"] + + with torch.inference_mode(): + with self.autocast(): + outputs = unwrap_model(self.model).generate( + self._prepare_images(batch_images).to( + self.device, dtype=self.cast_dtype, non_blocking=True + ), + input_ids.to(self.device, dtype=self.cast_dtype, non_blocking=True), + attention_mask=attention_mask.to( + self.device, dtype=self.cast_dtype, non_blocking=True + ), + min_new_tokens=min_generation_length, + max_new_tokens=max_generation_length, + num_beams=num_beams, + length_penalty=length_penalty, + ) + + outputs = outputs[:, len(input_ids[0]) :] + + return self.tokenizer.batch_decode(outputs, skip_special_tokens=True) + + def get_logits( + self, + lang_x: torch.Tensor, + vision_x: torch.Tensor = None, + attention_mask: torch.Tensor = None, + past_key_values: torch.Tensor = None, + clear_conditioned_layers: bool = False, + ): + with torch.inference_mode(): + with self.autocast(): + outputs = self.model( + vision_x=vision_x, + lang_x=lang_x, + attention_mask=attention_mask, + clear_conditioned_layers=clear_conditioned_layers, + past_key_values=past_key_values, + use_cache=(past_key_values is not None), + ) + return outputs + + def encode_vision_x(self, image_tensor: torch.Tensor): + unwrap_model(self.model)._encode_vision_x(image_tensor.to(self.device)) + + def uncache_media(self): + unwrap_model(self.model).uncache_media() + + def cache_media(self, input_ids, vision_x): + unwrap_model(self.model).cache_media(input_ids=input_ids, vision_x=vision_x) + + def get_vqa_prompt(self, question, answer=None) -> str: + return f"Question:{question} Short answer:{answer if answer is not None else ''}{'<|endofchunk|>' if answer is not None else ''}" + + def get_caption_prompt(self, caption=None) -> str: + return f"Output:{caption if caption is not None else ''}{'<|endofchunk|>' if caption is not None else ''}" + + +def get_cast_dtype(precision: str): + cast_dtype = None + if precision == "bf16": + cast_dtype = torch.bfloat16 + elif precision == "fp16": + cast_dtype = torch.float16 + return cast_dtype + + +def get_autocast(precision): + if precision == "amp": + return torch.cuda.amp.autocast + elif precision == "amp_bfloat16" or precision == "amp_bf16": + # amp_bfloat16 is more stable than amp float16 for clip training + return lambda: torch.cuda.amp.autocast(dtype=torch.bfloat16) + else: + return suppress diff --git a/open_flamingo/open_flamingo/eval/models/utils.py b/open_flamingo/open_flamingo/eval/models/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c65ca980f628fb063b614c619cf426c5be50073d --- /dev/null +++ b/open_flamingo/open_flamingo/eval/models/utils.py @@ -0,0 +1,10 @@ +import torch.nn as nn + +def unwrap_model(model): + """ + Unwrap a model from a DataParallel or DistributedDataParallel wrapper. + """ + if isinstance(model, (nn.DataParallel, nn.parallel.DistributedDataParallel)): + return model.module + else: + return model \ No newline at end of file diff --git a/open_flamingo/open_flamingo/eval/ok_vqa_utils.py b/open_flamingo/open_flamingo/eval/ok_vqa_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe6feeed4e3c3af190d770a625ea651a6efd639 --- /dev/null +++ b/open_flamingo/open_flamingo/eval/ok_vqa_utils.py @@ -0,0 +1,214 @@ +# Those are manual mapping that are not caught by our stemming rules or would +# would be done incorrectly by our automatic stemming rule. In details, +# the keys of the _MANUAL_MATCHES dict contains the original word and the value +# contains the transformation of the word expected by the OKVQA stemming rule. +# These manual rules were found by checking the `raw_answers` and the `answers` +# fields of the released OKVQA dataset and checking all things that were not +# properly mapped by our automatic rules. In particular some of the mapping +# are sometimes constant, e.g. christmas -> christmas which was incorrectly +# singularized by our inflection.singularize. +import re +import nltk +from nltk.corpus.reader import VERB +import inflection + +_MANUAL_MATCHES = { + "police": "police", + "las": "las", + "vegas": "vegas", + "yes": "yes", + "jeans": "jean", + "hell's": "hell", + "domino's": "domino", + "morning": "morn", + "clothes": "cloth", + "are": "are", + "riding": "ride", + "leaves": "leaf", + "dangerous": "danger", + "clothing": "cloth", + "texting": "text", + "kiting": "kite", + "firefighters": "firefight", + "ties": "tie", + "married": "married", + "teething": "teeth", + "gloves": "glove", + "tennis": "tennis", + "dining": "dine", + "directions": "direct", + "waves": "wave", + "christmas": "christmas", + "drives": "drive", + "pudding": "pud", + "coding": "code", + "plating": "plate", + "quantas": "quanta", + "hornes": "horn", + "graves": "grave", + "mating": "mate", + "paned": "pane", + "alertness": "alert", + "sunbathing": "sunbath", + "tenning": "ten", + "wetness": "wet", + "urinating": "urine", + "sickness": "sick", + "braves": "brave", + "firefighting": "firefight", + "lenses": "lens", + "reflections": "reflect", + "backpackers": "backpack", + "eatting": "eat", + "designers": "design", + "curiousity": "curious", + "playfulness": "play", + "blindness": "blind", + "hawke": "hawk", + "tomatoe": "tomato", + "rodeoing": "rodeo", + "brightness": "bright", + "circuses": "circus", + "skateboarders": "skateboard", + "staring": "stare", + "electronics": "electron", + "electicity": "elect", + "mountainous": "mountain", + "socializing": "social", + "hamburgers": "hamburg", + "caves": "cave", + "transitions": "transit", + "wading": "wade", + "creame": "cream", + "toileting": "toilet", + "sautee": "saute", + "buildings": "build", + "belongings": "belong", + "stockings": "stock", + "walle": "wall", + "cumulis": "cumuli", + "travelers": "travel", + "conducter": "conduct", + "browsing": "brows", + "pooping": "poop", + "haircutting": "haircut", + "toppings": "top", + "hearding": "heard", + "sunblocker": "sunblock", + "bases": "base", + "markings": "mark", + "mopeds": "mope", + "kindergartener": "kindergarten", + "pies": "pie", + "scrapbooking": "scrapbook", + "couponing": "coupon", + "meetings": "meet", + "elevators": "elev", + "lowes": "low", + "men's": "men", + "childrens": "children", + "shelves": "shelve", + "paintings": "paint", + "raines": "rain", + "paring": "pare", + "expressions": "express", + "routes": "rout", + "pease": "peas", + "vastness": "vast", + "awning": "awn", + "boy's": "boy", + "drunkenness": "drunken", + "teasing": "teas", + "conferences": "confer", + "ripeness": "ripe", + "suspenders": "suspend", + "earnings": "earn", + "reporters": "report", + "kid's": "kid", + "containers": "contain", + "corgie": "corgi", + "porche": "porch", + "microwaves": "microwave", + "batter's": "batter", + "sadness": "sad", + "apartments": "apart", + "oxygenize": "oxygen", + "striping": "stripe", + "purring": "pure", + "professionals": "profession", + "piping": "pipe", + "farmer's": "farmer", + "potatoe": "potato", + "emirates": "emir", + "womens": "women", + "veteran's": "veteran", + "wilderness": "wilder", + "propellers": "propel", + "alpes": "alp", + "charioteering": "chariot", + "swining": "swine", + "illness": "ill", + "crepte": "crept", + "adhesives": "adhesive", + "regent's": "regent", + "decorations": "decor", + "rabbies": "rabbi", + "overseas": "oversea", + "travellers": "travel", + "casings": "case", + "smugness": "smug", + "doves": "dove", + "nationals": "nation", + "mustange": "mustang", + "ringe": "ring", + "gondoliere": "gondolier", + "vacationing": "vacate", + "reminders": "remind", + "baldness": "bald", + "settings": "set", + "glaced": "glace", + "coniferous": "conifer", + "revelations": "revel", + "personals": "person", + "daughter's": "daughter", + "badness": "bad", + "projections": "project", + "polarizing": "polar", + "vandalizers": "vandal", + "minerals": "miner", + "protesters": "protest", + "controllers": "control", + "weddings": "wed", + "sometimes": "sometime", + "earing": "ear", +} + + +class OKVQAStemmer: + """Stemmer to match OKVQA v1.1 procedure.""" + + def __init__(self): + self._wordnet_lemmatizer = nltk.stem.WordNetLemmatizer() + + def stem(self, input_string): + """Apply stemming.""" + word_and_pos = nltk.pos_tag(nltk.tokenize.word_tokenize(input_string)) + stemmed_words = [] + for w, p in word_and_pos: + if w in _MANUAL_MATCHES: + w = _MANUAL_MATCHES[w] + elif w.endswith("ing"): + w = self._wordnet_lemmatizer.lemmatize(w, VERB) + elif p.startswith("NNS") or p.startswith("NNPS"): + w = inflection.singularize(w) + stemmed_words.append(w) + return " ".join(stemmed_words) + + +stemmer = OKVQAStemmer() + + +def postprocess_ok_vqa_generation(predictions) -> str: + prediction = re.split("Question|Answer|Short", predictions, 1)[0] + prediction_stem = stemmer.stem(prediction) + return prediction_stem diff --git a/open_flamingo/open_flamingo/eval/vqa_metric.py b/open_flamingo/open_flamingo/eval/vqa_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..72eb4d23a0c6270581e7c31bc4baee399985eed7 --- /dev/null +++ b/open_flamingo/open_flamingo/eval/vqa_metric.py @@ -0,0 +1,583 @@ +import copy +import datetime +import json +import os +import random +import re +import sys + +# Interface for accessing the VQA dataset. + +# This code is based on the code written by Tsung-Yi Lin for MSCOCO Python API available at the following link: +# (https://github.com/pdollar/coco/blob/master/PythonAPI/pycocotools/coco.py). + +# The following functions are defined: +# VQA - VQA class that loads VQA annotation file and prepares data structures. +# getQuesIds - Get question ids that satisfy given filter conditions. +# getImgIds - Get image ids that satisfy given filter conditions. +# loadQA - Load questions and answers with the specified question ids. +# showQA - Display the specified questions and answers. +# loadRes - Load result file and create result object. + +# Help on each function can be accessed by: "help(COCO.function)" + + +class VQA: + def __init__(self, annotation_file=None, question_file=None): + """ + Constructor of VQA helper class for reading and visualizing questions and answers. + :param annotation_file (str): location of VQA annotation file + :return: + """ + # load dataset + self.dataset = {} + self.questions = {} + self.qa = {} + self.qqa = {} + self.imgToQA = {} + if not annotation_file == None and not question_file == None: + print("loading VQA annotations and questions into memory...") + time_t = datetime.datetime.utcnow() + dataset = json.load(open(annotation_file, "r")) + questions = json.load(open(question_file, "r")) + print(datetime.datetime.utcnow() - time_t) + self.dataset = dataset + self.questions = questions + self.createIndex() + + def createIndex(self): + # create index + print("creating index...") + imgToQA = {ann["image_id"]: [] for ann in self.dataset["annotations"]} + qa = {ann["question_id"]: [] for ann in self.dataset["annotations"]} + qqa = {ann["question_id"]: [] for ann in self.dataset["annotations"]} + for ann in self.dataset["annotations"]: + imgToQA[ann["image_id"]] += [ann] + qa[ann["question_id"]] = ann + for ques in self.questions["questions"]: + qqa[ques["question_id"]] = ques + print("index created!") + + # create class members + self.qa = qa + self.qqa = qqa + self.imgToQA = imgToQA + + def info(self): + """ + Print information about the VQA annotation file. + :return: + """ + for key, value in self.dataset["info"].items(): + print("%s: %s" % (key, value)) + + def getQuesIds(self, imgIds=[], quesTypes=[], ansTypes=[]): + """ + Get question ids that satisfy given filter conditions. default skips that filter + :param imgIds (int array) : get question ids for given imgs + quesTypes (str array) : get question ids for given question types + ansTypes (str array) : get question ids for given answer types + :return: ids (int array) : integer array of question ids + """ + imgIds = imgIds if type(imgIds) == list else [imgIds] + quesTypes = quesTypes if type(quesTypes) == list else [quesTypes] + ansTypes = ansTypes if type(ansTypes) == list else [ansTypes] + + if len(imgIds) == len(quesTypes) == len(ansTypes) == 0: + anns = self.dataset["annotations"] + else: + if not len(imgIds) == 0: + anns = sum( + [self.imgToQA[imgId] for imgId in imgIds if imgId in self.imgToQA], + [], + ) + else: + anns = self.dataset["annotations"] + anns = ( + anns + if len(quesTypes) == 0 + else [ann for ann in anns if ann["question_type"] in quesTypes] + ) + anns = ( + anns + if len(ansTypes) == 0 + else [ann for ann in anns if ann["answer_type"] in ansTypes] + ) + ids = [ann["question_id"] for ann in anns] + return ids + + def getImgIds(self, quesIds=[], quesTypes=[], ansTypes=[]): + """ + Get image ids that satisfy given filter conditions. default skips that filter + :param quesIds (int array) : get image ids for given question ids + quesTypes (str array) : get image ids for given question types + ansTypes (str array) : get image ids for given answer types + :return: ids (int array) : integer array of image ids + """ + quesIds = quesIds if type(quesIds) == list else [quesIds] + quesTypes = quesTypes if type(quesTypes) == list else [quesTypes] + ansTypes = ansTypes if type(ansTypes) == list else [ansTypes] + + if len(quesIds) == len(quesTypes) == len(ansTypes) == 0: + anns = self.dataset["annotations"] + else: + if not len(quesIds) == 0: + anns = sum( + [self.qa[quesId] for quesId in quesIds if quesId in self.qa], [] + ) + else: + anns = self.dataset["annotations"] + anns = ( + anns + if len(quesTypes) == 0 + else [ann for ann in anns if ann["question_type"] in quesTypes] + ) + anns = ( + anns + if len(ansTypes) == 0 + else [ann for ann in anns if ann["answer_type"] in ansTypes] + ) + ids = [ann["image_id"] for ann in anns] + return ids + + def loadQA(self, ids=[]): + """ + Load questions and answers with the specified question ids. + :param ids (int array) : integer ids specifying question ids + :return: qa (object array) : loaded qa objects + """ + if type(ids) == list: + return [self.qa[id] for id in ids] + elif type(ids) == int: + return [self.qa[ids]] + + def showQA(self, anns): + """ + Display the specified annotations. + :param anns (array of object): annotations to display + :return: None + """ + if len(anns) == 0: + return 0 + for ann in anns: + quesId = ann["question_id"] + print("Question: %s" % (self.qqa[quesId]["question"])) + for ans in ann["answers"]: + print("Answer %d: %s" % (ans["answer_id"], ans["answer"])) + + def loadRes(self, resFile, quesFile): + """ + Load result file and return a result object. + :param resFile (str) : file name of result file + :return: res (obj) : result api object + """ + res = VQA() + res.questions = json.load(open(quesFile)) + res.dataset["info"] = copy.deepcopy(self.questions["info"]) + res.dataset["task_type"] = copy.deepcopy(self.questions["task_type"]) + res.dataset["data_type"] = copy.deepcopy(self.questions["data_type"]) + res.dataset["data_subtype"] = copy.deepcopy(self.questions["data_subtype"]) + res.dataset["license"] = copy.deepcopy(self.questions["license"]) + + print("Loading and preparing results... ") + time_t = datetime.datetime.utcnow() + anns = json.load(open(resFile)) + assert type(anns) == list, "results is not an array of objects" + annsQuesIds = [ann["question_id"] for ann in anns] + # print set of question ids that do not have corresponding annotations + + # assert set(annsQuesIds) == set(self.getQuesIds()), \ + # 'Results do not correspond to current VQA set. Either the results do not have predictions for all question ids in annotation file or there is atleast one question id that does not belong to the question ids in the annotation file.' + for ann in anns: + quesId = ann["question_id"] + if res.dataset["task_type"] == "Multiple Choice": + assert ( + ann["answer"] in self.qqa[quesId]["multiple_choices"] + ), "predicted answer is not one of the multiple choices" + qaAnn = self.qa[quesId] + ann["image_id"] = qaAnn["image_id"] + ann["question_type"] = qaAnn["question_type"] + if "answer_type" in ann: + ann["answer_type"] = qaAnn["answer_type"] + print( + "DONE (t=%0.2fs)" % ((datetime.datetime.utcnow() - time_t).total_seconds()) + ) + + res.dataset["annotations"] = anns + res.createIndex() + return res + + +class VQAEval: + def __init__(self, vqa, vqaRes, n=2): + self.n = n + self.accuracy = {} + self.evalQA = {} + self.evalQuesType = {} + self.evalAnsType = {} + self.vqa = vqa + self.vqaRes = vqaRes + if not vqa is None and not vqaRes is None: + self.params = {"question_id": vqaRes.getQuesIds()} + self.contractions = { + "aint": "ain't", + "arent": "aren't", + "cant": "can't", + "couldve": "could've", + "couldnt": "couldn't", + "couldn'tve": "couldn't've", + "couldnt've": "couldn't've", + "didnt": "didn't", + "doesnt": "doesn't", + "dont": "don't", + "hadnt": "hadn't", + "hadnt've": "hadn't've", + "hadn'tve": "hadn't've", + "hasnt": "hasn't", + "havent": "haven't", + "hed": "he'd", + "hed've": "he'd've", + "he'dve": "he'd've", + "hes": "he's", + "howd": "how'd", + "howll": "how'll", + "hows": "how's", + "Id've": "I'd've", + "I'dve": "I'd've", + "Im": "I'm", + "Ive": "I've", + "isnt": "isn't", + "itd": "it'd", + "itd've": "it'd've", + "it'dve": "it'd've", + "itll": "it'll", + "let's": "let's", + "maam": "ma'am", + "mightnt": "mightn't", + "mightnt've": "mightn't've", + "mightn'tve": "mightn't've", + "mightve": "might've", + "mustnt": "mustn't", + "mustve": "must've", + "neednt": "needn't", + "notve": "not've", + "oclock": "o'clock", + "oughtnt": "oughtn't", + "ow's'at": "'ow's'at", + "'ows'at": "'ow's'at", + "'ow'sat": "'ow's'at", + "shant": "shan't", + "shed've": "she'd've", + "she'dve": "she'd've", + "she's": "she's", + "shouldve": "should've", + "shouldnt": "shouldn't", + "shouldnt've": "shouldn't've", + "shouldn'tve": "shouldn't've", + "somebody'd": "somebodyd", + "somebodyd've": "somebody'd've", + "somebody'dve": "somebody'd've", + "somebodyll": "somebody'll", + "somebodys": "somebody's", + "someoned": "someone'd", + "someoned've": "someone'd've", + "someone'dve": "someone'd've", + "someonell": "someone'll", + "someones": "someone's", + "somethingd": "something'd", + "somethingd've": "something'd've", + "something'dve": "something'd've", + "somethingll": "something'll", + "thats": "that's", + "thered": "there'd", + "thered've": "there'd've", + "there'dve": "there'd've", + "therere": "there're", + "theres": "there's", + "theyd": "they'd", + "theyd've": "they'd've", + "they'dve": "they'd've", + "theyll": "they'll", + "theyre": "they're", + "theyve": "they've", + "twas": "'twas", + "wasnt": "wasn't", + "wed've": "we'd've", + "we'dve": "we'd've", + "weve": "we've", + "werent": "weren't", + "whatll": "what'll", + "whatre": "what're", + "whats": "what's", + "whatve": "what've", + "whens": "when's", + "whered": "where'd", + "wheres": "where's", + "whereve": "where've", + "whod": "who'd", + "whod've": "who'd've", + "who'dve": "who'd've", + "wholl": "who'll", + "whos": "who's", + "whove": "who've", + "whyll": "why'll", + "whyre": "why're", + "whys": "why's", + "wont": "won't", + "wouldve": "would've", + "wouldnt": "wouldn't", + "wouldnt've": "wouldn't've", + "wouldn'tve": "wouldn't've", + "yall": "y'all", + "yall'll": "y'all'll", + "y'allll": "y'all'll", + "yall'd've": "y'all'd've", + "y'alld've": "y'all'd've", + "y'all'dve": "y'all'd've", + "youd": "you'd", + "youd've": "you'd've", + "you'dve": "you'd've", + "youll": "you'll", + "youre": "you're", + "youve": "you've", + } + self.manualMap = { + "none": "0", + "zero": "0", + "one": "1", + "two": "2", + "three": "3", + "four": "4", + "five": "5", + "six": "6", + "seven": "7", + "eight": "8", + "nine": "9", + "ten": "10", + } + self.articles = ["a", "an", "the"] + + self.periodStrip = re.compile("(?!<=\d)(\.)(?!\d)") + self.commaStrip = re.compile("(\d)(\,)(\d)") + self.punct = [ + ";", + r"/", + "[", + "]", + '"', + "{", + "}", + "(", + ")", + "=", + "+", + "\\", + "_", + "-", + ">", + "<", + "@", + "`", + ",", + "?", + "!", + ] + + def evaluate(self, quesIds=None): + if quesIds == None: + quesIds = [quesId for quesId in self.params["question_id"]] + gts = {} + res = {} + for quesId in quesIds: + gts[quesId] = self.vqa.qa[quesId] + res[quesId] = self.vqaRes.qa[quesId] + + # ================================================= + # Compute accuracy + # ================================================= + accQA = [] + accQuesType = {} + accAnsType = {} + print("computing accuracy") + step = 0 + for quesId in quesIds: + for ansDic in gts[quesId]["answers"]: + ansDic["answer"] = ansDic["answer"].replace("\n", " ") + ansDic["answer"] = ansDic["answer"].replace("\t", " ") + ansDic["answer"] = ansDic["answer"].strip() + resAns = res[quesId]["answer"] + resAns = resAns.replace("\n", " ") + resAns = resAns.replace("\t", " ") + resAns = resAns.strip() + resAns = self.processPunctuation(resAns) + resAns = self.processDigitArticle(resAns) + gtAcc = [] + + for ansDic in gts[quesId]["answers"]: + ansDic["answer"] = self.processPunctuation(ansDic["answer"]) + ansDic["answer"] = self.processDigitArticle(ansDic["answer"]) + + for gtAnsDatum in gts[quesId]["answers"]: + otherGTAns = [ + item for item in gts[quesId]["answers"] if item != gtAnsDatum + ] + matchingAns = [item for item in otherGTAns if item["answer"] == resAns] + acc = min(1, float(len(matchingAns)) / 3) + gtAcc.append(acc) + quesType = gts[quesId]["question_type"] + ansType = ( + gts[quesId]["answer_type"] if "answer_type" in gts[quesId] else "other" + ) + avgGTAcc = float(sum(gtAcc)) / len(gtAcc) + accQA.append(avgGTAcc) + if quesType not in accQuesType: + accQuesType[quesType] = [] + accQuesType[quesType].append(avgGTAcc) + if ansType not in accAnsType: + accAnsType[ansType] = [] + accAnsType[ansType].append(avgGTAcc) + self.setEvalQA(quesId, avgGTAcc) + self.setEvalQuesType(quesId, quesType, avgGTAcc) + self.setEvalAnsType(quesId, ansType, avgGTAcc) + if step % 100 == 0: + self.updateProgress(step / float(len(quesIds))) + step = step + 1 + + self.setAccuracy(accQA, accQuesType, accAnsType) + print("Done computing accuracy") + + def processPunctuation(self, inText): + outText = inText + for p in self.punct: + if (p + " " in inText or " " + p in inText) or ( + re.search(self.commaStrip, inText) != None + ): + outText = outText.replace(p, "") + else: + outText = outText.replace(p, " ") + outText = self.periodStrip.sub("", outText, re.UNICODE) + return outText + + def processDigitArticle(self, inText): + outText = [] + tempText = inText.lower().split() + for word in tempText: + word = self.manualMap.setdefault(word, word) + if word not in self.articles: + outText.append(word) + else: + pass + for wordId, word in enumerate(outText): + if word in self.contractions: + outText[wordId] = self.contractions[word] + outText = " ".join(outText) + return outText + + def setAccuracy(self, accQA, accQuesType, accAnsType): + self.accuracy["overall"] = round(100 * float(sum(accQA)) / len(accQA), self.n) + self.accuracy["perQuestionType"] = { + quesType: round( + 100 * float(sum(accQuesType[quesType])) / len(accQuesType[quesType]), + self.n, + ) + for quesType in accQuesType + } + self.accuracy["perAnswerType"] = { + ansType: round( + 100 * float(sum(accAnsType[ansType])) / len(accAnsType[ansType]), self.n + ) + for ansType in accAnsType + } + + def setEvalQA(self, quesId, acc): + self.evalQA[quesId] = round(100 * acc, self.n) + + def setEvalQuesType(self, quesId, quesType, acc): + if quesType not in self.evalQuesType: + self.evalQuesType[quesType] = {} + self.evalQuesType[quesType][quesId] = round(100 * acc, self.n) + + def setEvalAnsType(self, quesId, ansType, acc): + if ansType not in self.evalAnsType: + self.evalAnsType[ansType] = {} + self.evalAnsType[ansType][quesId] = round(100 * acc, self.n) + + def updateProgress(self, progress): + barLength = 20 + status = "" + if isinstance(progress, int): + progress = float(progress) + if not isinstance(progress, float): + progress = 0 + status = "error: progress var must be float\r\n" + if progress < 0: + progress = 0 + status = "Halt...\r\n" + if progress >= 1: + progress = 1 + status = "Done...\r\n" + block = int(round(barLength * progress)) + text = "\rFinshed Percent: [{0}] {1}% {2}".format( + "#" * block + "-" * (barLength - block), int(progress * 100), status + ) + sys.stdout.write(text) + sys.stdout.flush() + + +def compute_vqa_accuracy(result_json_path, question_json_path, annotation_json_path): + """Compute the VQA accuracy metric. + + Args: + result_json_path (str): Path to the json file with model outputs + question_json_path (str): Path to the json file with questions + annotation_json_path (str): Path to the json file with annotations + + Returns: + float: VQA accuracy + """ + # coding: utf-8 + # dataDir = data_dir + + # set up file names and paths + # versionType = 'v2_' # this should be '' when using VQA v2.0 dataset + # 'OpenEnded' only for v2.0. 'OpenEnded' or 'MultipleChoice' for v1.0 + # taskType = 'OpenEnded' + # 'mscoco' only for v1.0. 'mscoco' for real and 'abstract_v002' for abstract for v1.0. + # dataType = 'mscoco' + # dataSubType = 'train2014' + # annFile = '%s/%s%s_%s_annotations.json' % ( + # dataDir, versionType, dataType, dataSubType) + # quesFile = '%s/%s%s_%s_%s_questions.json' % ( + # dataDir, versionType, taskType, dataType, dataSubType) + # imgDir = '%s/%s/%s/' % (dataDir, dataType, dataSubType) + # resultType = res_file_name + # fileTypes = ['results', 'accuracy', + # 'evalQA', 'evalQuesType', 'evalAnsType'] + + # An example result json file has been provided in './Results' folder. + + # [resFile, accuracyFile, evalQAFile, evalQuesTypeFile, evalAnsTypeFile] = ['%s/%s%s_%s_%s_%s_%s.json' % (dataDir, versionType, taskType, dataType, dataSubType, + # resultType, fileType) for fileType in fileTypes] + + # create vqa object and vqaRes object + vqa = VQA(annotation_json_path, question_json_path) + vqaRes = vqa.loadRes(result_json_path, question_json_path) + + # create vqaEval object by taking vqa and vqaRes + # n is precision of accuracy (number of places after decimal), default is 2 + vqaEval = VQAEval(vqa, vqaRes, n=2) + + # evaluate results + """ + If you have a list of question ids on which you would like to evaluate your results, pass it as a list to below function + By default it uses all the question ids in annotation file + """ + vqaEval.evaluate() + + return vqaEval.accuracy["overall"] + + +def postprocess_vqa_generation(predictions): + answer = re.split("Question|Answer|Short", predictions, 1)[0] + answer = re.split(", ", answer, 1)[0] + return answer diff --git a/open_flamingo/open_flamingo/scripts/convert_mmc4_to_wds.py b/open_flamingo/open_flamingo/scripts/convert_mmc4_to_wds.py new file mode 100644 index 0000000000000000000000000000000000000000..724721d0750cedbe1ba1f979409f569ccb04cf16 --- /dev/null +++ b/open_flamingo/open_flamingo/scripts/convert_mmc4_to_wds.py @@ -0,0 +1,76 @@ +import argparse +import json +import os +import uuid +import zipfile +from PIL import Image +import base64 +from io import BytesIO + +import braceexpand +import webdataset as wds + +arg_parser = argparse.ArgumentParser() +arg_parser.add_argument( + "--output_dir", + type=str, + help="Pass in the directory where the output shards (as tar files) will be written to.", +) +arg_parser.add_argument( + "--zip_files", + type=str, + help="Pass in a list of MMC4 shards in the format path_to_shard/shard_{0..23098}.zip", +) +arg_parser.add_argument( + "--image_dir", + type=str, + help="Pass in the directory where the images have been downloaded to.", +) +args = arg_parser.parse_args() + + +def main(): + os.makedirs(args.output_dir, exist_ok=True) + + doc_shards = list(braceexpand.braceexpand(args.zip_files)) + + with wds.ShardWriter(args.output_dir + "/%09d.tar") as sink: + for idx in range(len(doc_shards)): + # Open the ZIP archive and extract the JSON file + with zipfile.ZipFile(doc_shards[idx], "r") as zip_file: + # Assumes the JSON file is the first file in the archive + json_filename = zip_file.namelist()[0] + with zip_file.open(json_filename, "r") as json_file: + for sample_data in json_file: + # get image names from json + sample_data = json.loads(sample_data) + image_info = sample_data["image_info"] + image_names = [image["image_name"] for image in image_info] + + # Add each image to the tar file + for img_idx, image_name in enumerate(image_names): + try: + # load image + img = Image.open( + os.path.join(args.image_dir, str(idx), image_name) + ).convert("RGB") + buffered = BytesIO() + img.save(buffered, format="JPEG") + img_str = base64.b64encode(buffered.getvalue()) + # convert to base64 + sample_data["image_info"][img_idx][ + "image_base64" + ] = str(img_str) + except FileNotFoundError: + print( + f"Did not find {image_name} downloaded. This can happen if the url is now 404." + ) + except Exception as e: + print(f"Error processing {image_name}: {e}") + + key_str = uuid.uuid4().hex + sink.write({"__key__": key_str, "json": sample_data}) + + +if __name__ == "__main__": + main() diff --git a/open_flamingo/open_flamingo/scripts/run_eval.sh b/open_flamingo/open_flamingo/scripts/run_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..d347d0a4adabe92f9414bd0663bb0b15770c585d --- /dev/null +++ b/open_flamingo/open_flamingo/scripts/run_eval.sh @@ -0,0 +1,74 @@ +#!/bin/bash +#SBATCH --nodes=1 +#SBATCH --ntasks-per-node=2 +#SBATCH --gpus-per-task=1 + +<", ""]} + ) + if text_tokenizer.pad_token is None: + # Issue: GPT models don't have a pad token, which we use to + # modify labels for the loss. + text_tokenizer.add_special_tokens({"pad_token": ""}) + + lang_encoder = AutoModelForCausalLM.from_pretrained( + lang_encoder_path, + local_files_only=use_local_files, + trust_remote_code=True, + ) + + # hacks for MPT-1B, which doesn't have a get_input_embeddings method + if "mpt-1b-redpajama-200b" in lang_encoder_path: + + class EmbeddingFnMixin: + def get_input_embeddings(self): + return self.transformer.wte + + def set_input_embeddings(self, new_embeddings): + self.transformer.wte = new_embeddings + + extend_instance(lang_encoder, EmbeddingFnMixin) + + # convert LM to FlamingoLM + extend_instance(lang_encoder, FlamingoLMMixin) + + if decoder_layers_attr_name is None: + decoder_layers_attr_name = _infer_decoder_layers_attr_name(lang_encoder) + lang_encoder.set_decoder_layers_attr_name(decoder_layers_attr_name) + lang_encoder.resize_token_embeddings(len(text_tokenizer)) + + model = Flamingo( + vision_encoder, + lang_encoder, + text_tokenizer.encode("<|endofchunk|>")[-1], + text_tokenizer.encode("")[-1], + vis_dim=open_clip.get_model_config(clip_vision_encoder_path)["vision_cfg"][ + "width" + ], + cross_attn_every_n_layers=cross_attn_every_n_layers, + **flamingo_kwargs, + ) + + # Freeze all parameters + model.requires_grad_(False) + assert sum(p.numel() for p in model.parameters() if p.requires_grad) == 0 + + # Unfreeze perceiver, gated_cross_attn_layers, and LM input embeddings + model.perceiver.requires_grad_(True) + model.lang_encoder.gated_cross_attn_layers.requires_grad_(True) + if not freeze_lm_embeddings: + model.lang_encoder.get_input_embeddings().requires_grad_(True) + # TODO: investigate also training the output embeddings when untied + + print( + f"Flamingo model initialized with {sum(p.numel() for p in model.parameters() if p.requires_grad)} trainable parameters" + ) + + return model, image_processor, text_tokenizer + + +def _infer_decoder_layers_attr_name(model): + for k in __KNOWN_DECODER_LAYERS_ATTR_NAMES: + if k.lower() in model.__class__.__name__.lower(): + return __KNOWN_DECODER_LAYERS_ATTR_NAMES[k] + + raise ValueError( + f"We require the attribute name for the nn.ModuleList in the decoder storing the transformer block layers. Please supply this string manually." + ) + + +__KNOWN_DECODER_LAYERS_ATTR_NAMES = { + "opt": "model.decoder.layers", + "gptj": "transformer.h", + "gpt-j": "transformer.h", + "pythia": "gpt_neox.layers", + "llama": "model.layers", + "gptneoxforcausallm": "gpt_neox.layers", + "mpt": "transformer.blocks", + "mosaicgpt": "transformer.blocks", +} diff --git a/open_flamingo/open_flamingo/src/flamingo.py b/open_flamingo/open_flamingo/src/flamingo.py new file mode 100644 index 0000000000000000000000000000000000000000..4e6adcc6e85555d8e015beecf9cef91c8474abef --- /dev/null +++ b/open_flamingo/open_flamingo/src/flamingo.py @@ -0,0 +1,356 @@ +import torch +from einops import rearrange +from torch import nn +from .helpers import PerceiverResampler +from torch.distributed.fsdp.wrap import ( + enable_wrap, + wrap, +) +from transformers.modeling_outputs import CausalLMOutputWithPast +from torch.distributed.fsdp import ( + FullyShardedDataParallel as FSDP, +) + +from .utils import apply_with_stopping_condition + + +class Flamingo(nn.Module): + def __init__( + self, + vision_encoder: nn.Module, + lang_encoder: nn.Module, + eoc_token_id: int, + media_token_id: int, + vis_dim: int, + cross_attn_every_n_layers: int = 1, + gradient_checkpointing: bool = False, + ): + """ + Args: + vision_encoder (nn.Module): HF CLIPModel + lang_encoder (nn.Module): HF causal language model + eoc_token_id (int): Token id for <|endofchunk|> + media_token_id (int): Token id for + vis_dim (int): Dimension of the visual features. + Visual features are projected to match this shape along the last dimension. + cross_attn_every_n_layers (int, optional): How often to apply cross attention after transformer layer. Defaults to 1. + """ + super().__init__() + self.eoc_token_id = eoc_token_id + self.media_token_id = media_token_id + self.vis_dim = vis_dim + if hasattr(lang_encoder.config, "d_model"): + self.lang_dim = lang_encoder.config.d_model # mpt uses d_model + else: + self.lang_dim = lang_encoder.config.hidden_size + + self.vision_encoder = vision_encoder.visual + self.perceiver = PerceiverResampler(dim=self.vis_dim) + self.lang_encoder = lang_encoder + self.lang_encoder.init_flamingo( + media_token_id=media_token_id, + lang_hidden_size=self.lang_dim, + vis_hidden_size=self.vis_dim, + cross_attn_every_n_layers=cross_attn_every_n_layers, + gradient_checkpointing=gradient_checkpointing, + ) + self._use_gradient_checkpointing = gradient_checkpointing + self.perceiver._use_gradient_checkpointing = gradient_checkpointing + + def forward( + self, + vision_x: torch.Tensor, + lang_x: torch.Tensor, + attention_mask: torch.Tensor = None, + labels: torch.Tensor = None, + clear_conditioned_layers: bool = True, + past_key_values=None, + use_cache: bool = False, + ): + """ + Forward pass of Flamingo. + + Args: + vision_x (torch.Tensor): Vision input + shape (B, T_img, F, C, H, W) with F=1 + lang_x (torch.Tensor): Language input ids + shape (B, T_txt) + attention_mask (torch.Tensor, optional): Attention mask. Defaults to None. + labels (torch.Tensor, optional): Labels. Defaults to None. + clear_conditioned_layers: if True, clear the conditioned layers + once the foward pass is completed. Set this to false if the + same set of images will be reused in another subsequent + forward pass. + past_key_values: pre-computed values to pass to language model. + See past_key_values documentation in Hugging Face + CausalLM models. + use_cache: whether to use cached key values. See use_cache + documentation in Hugging Face CausalLM models. + """ + assert ( + self.lang_encoder.initialized_flamingo + ), "Flamingo layers are not initialized. Please call `init_flamingo` first." + + assert ( + self.lang_encoder._use_cached_vision_x or vision_x is not None + ), "Must provide either vision_x or have precached media using cache_media()." + + if self.lang_encoder._use_cached_vision_x: + # Case: use cached; vision_x should be cached and other + # vision-related inputs should not be provided. + assert ( + vision_x is None + ), "Expect vision_x to be None when media has been cached using cache_media(). Try uncache_media() first." + assert self.lang_encoder.is_conditioned() + + else: + # Case: do not use caching (i.e. this is a standard forward pass); + self._encode_vision_x(vision_x=vision_x) + self._condition_media_locations(input_ids=lang_x) + + output = self.lang_encoder( + input_ids=lang_x, + attention_mask=attention_mask, + labels=labels, + past_key_values=past_key_values, + use_cache=use_cache, + ) + + if clear_conditioned_layers: + self.lang_encoder.clear_conditioned_layers() + + return output + + def generate( + self, + vision_x: torch.Tensor, + lang_x: torch.Tensor, + attention_mask: torch.Tensor = None, + num_beams=1, + min_new_tokens=None, + max_new_tokens=None, + temperature=1.0, + top_k=0, + top_p=1.0, + no_repeat_ngram_size=0, + prefix_allowed_tokens_fn=None, + length_penalty=1.0, + num_return_sequences=1, + do_sample=False, + early_stopping=False, + ): + """ + Generate text conditioned on vision and language inputs. + + Args: + vision_x (torch.Tensor): Vision input + shape (B, T_img, F, C, H, W) + images in the same chunk are collated along T_img, and frames are collated along F + currently only F=1 is supported (single-frame videos) + lang_x (torch.Tensor): Language input + shape (B, T_txt) + max_length (int, optional): Maximum length of the output. Defaults to None. + attention_mask (torch.Tensor, optional): Attention mask. Defaults to None. + num_beams (int, optional): Number of beams. Defaults to 1. + max_new_tokens (int, optional): Maximum new tokens. Defaults to None. + temperature (float, optional): Temperature. Defaults to 1.0. + top_k (int, optional): Top k. Defaults to 0. + top_p (float, optional): Top p. Defaults to 1.0. + no_repeat_ngram_size (int, optional): No repeat ngram size. Defaults to 0. + length_penalty (float, optional): Length penalty. Defaults to 1.0. + num_return_sequences (int, optional): Number of return sequences. Defaults to 1. + do_sample (bool, optional): Do sample. Defaults to False. + early_stopping (bool, optional): Early stopping. Defaults to False. + Returns: + torch.Tensor: lang_x with generated tokens appended to it + """ + if num_beams > 1: + vision_x = vision_x.repeat_interleave(num_beams, dim=0) + + self.lang_encoder._use_cached_vision_x = True + self._encode_vision_x(vision_x=vision_x) + + output = self.lang_encoder.generate( + input_ids=lang_x, + attention_mask=attention_mask, + eos_token_id=self.eoc_token_id, + num_beams=num_beams, + min_new_tokens=min_new_tokens, + max_new_tokens=max_new_tokens, + temperature=temperature, + top_k=top_k, + top_p=top_p, + prefix_allowed_tokens_fn=prefix_allowed_tokens_fn, + no_repeat_ngram_size=no_repeat_ngram_size, + length_penalty=length_penalty, + num_return_sequences=num_return_sequences, + do_sample=do_sample, + early_stopping=early_stopping, + ) + + self.lang_encoder.clear_conditioned_layers() + self.lang_encoder._use_cached_vision_x = False + return output + + def _encode_vision_x(self, vision_x: torch.Tensor): + """ + Compute media tokens from vision input by passing it through vision encoder and conditioning language model. + Args: + vision_x (torch.Tensor): Vision input + shape (B, T_img, F, C, H, W) + Images in the same chunk are collated along T_img, and frames are collated along F + Currently only F=1 is supported (single-frame videos) + + rearrange code based on https://github.com/dhansmair/flamingo-mini + """ + + assert vision_x.ndim == 6, "vision_x should be of shape (b, T_img, F, C, H, W)" + b, T, F = vision_x.shape[:3] + assert F == 1, "Only single frame supported" + + vision_x = rearrange(vision_x, "b T F c h w -> (b T F) c h w") + with torch.no_grad(): + vision_x = self.vision_encoder(vision_x)[1] + vision_x = rearrange(vision_x, "(b T F) v d -> b T F v d", b=b, T=T, F=F) + vision_x = self.perceiver(vision_x) + + for layer in self.lang_encoder._get_decoder_layers(): + layer.condition_vis_x(vision_x) + + def wrap_fsdp(self, wrapper_kwargs, device_id): + """ + Manually wraps submodules for FSDP and move other parameters to device_id. + + Why manually wrap? + - all parameters within the FSDP wrapper must have the same requires_grad. + We have a mix of frozen and unfrozen parameters. + - model.vision_encoder.visual needs to be individually wrapped or encode_vision_x errors + See: https://github.com/pytorch/pytorch/issues/82461#issuecomment-1269136344 + + The rough wrapping structure is: + - FlamingoModel + - FSDP(FSDP(vision_encoder)) + - FSDP(FSDP(perceiver)) + - lang_encoder + - FSDP(FSDP(input_embeddings)) + - FlamingoLayers + - FSDP(FSDP(gated_cross_attn_layer)) + - FSDP(FSDP(decoder_layer)) + - FSDP(FSDP(output_embeddings)) + - other parameters + + Known issues: + - Our FSDP strategy is not compatible with tied embeddings. If the LM embeddings are tied, + train with DDP or set the --freeze_lm_embeddings flag to true. + - With FSDP + gradient ckpting, one can increase the batch size with seemingly no upper bound. + Although the training curves look okay, we found that downstream performance dramatically + degrades if the batch size is unreasonably large (e.g., 100 MMC4 batch size for OPT-125M). + + FAQs about our FSDP wrapping strategy: + Why double wrap? + As of torch==2.0.1, FSDP's _post_forward_hook and _post_backward_hook + only free gathered parameters if the module is NOT FSDP root. + + Why unfreeze the decoder_layers? + See https://github.com/pytorch/pytorch/issues/95805 + As of torch==2.0.1, FSDP's _post_backward_hook is only registed if the flat param + requires_grad=True. We need the postback to fire to avoid OOM. + To effectively freeze the decoder layers, we exclude them from the optimizer. + + What is assumed to be frozen v. unfrozen? + We assume that the model is being trained under normal Flamingo settings + with these lines being called in factory.py: + ``` + # Freeze all parameters + model.requires_grad_(False) + assert sum(p.numel() for p in model.parameters() if p.requires_grad) == 0 + + # Unfreeze perceiver, gated_cross_attn_layers, and LM input embeddings + model.perceiver.requires_grad_(True) + model.lang_encoder.gated_cross_attn_layers.requires_grad_(True) + [optional] model.lang_encoder.get_input_embeddings().requires_grad_(True) + ``` + """ + # unfreeze the decoder layers + for block in self.lang_encoder.old_decoder_blocks: + block.requires_grad_(True) + + # wrap in FSDP + with enable_wrap(wrapper_cls=FSDP, **wrapper_kwargs): + self.perceiver = wrap(wrap(self.perceiver)) + self.lang_encoder.old_decoder_blocks = nn.ModuleList( + wrap(wrap(block)) for block in self.lang_encoder.old_decoder_blocks + ) + self.lang_encoder.gated_cross_attn_layers = nn.ModuleList( + wrap(wrap(layer)) if layer is not None else None + for layer in self.lang_encoder.gated_cross_attn_layers + ) + self.lang_encoder.init_flamingo_layers(self._use_gradient_checkpointing) + self.lang_encoder.set_input_embeddings( + wrap(wrap(self.lang_encoder.get_input_embeddings())) + ) + self.lang_encoder.set_output_embeddings( + wrap(wrap(self.lang_encoder.get_output_embeddings())) + ) + self.vision_encoder = wrap(wrap(self.vision_encoder)) # frozen + + # manually move non-FSDP managed parameters to device_id + # these are all in lang_encoder + apply_with_stopping_condition( + module=self.lang_encoder, + apply_fn=lambda m: m.to(device_id), + apply_condition=lambda m: len(list(m.children())) == 0, + stopping_condition=lambda m: isinstance(m, FSDP), + ) + + # exclude the original decoder layers from the optimizer + for block in self.lang_encoder.old_decoder_blocks: + for p in block.parameters(): + p.exclude_from_optimizer = True + + # set up clip_grad_norm_ function + def clip_grad_norm_(max_norm): + self.perceiver.clip_grad_norm_(max_norm) + for layer in self.lang_encoder.gated_cross_attn_layers: + if layer is not None: + layer.clip_grad_norm_(max_norm) + self.lang_encoder.get_input_embeddings().clip_grad_norm_(max_norm) + + self.clip_grad_norm_ = clip_grad_norm_ + + def _condition_media_locations(self, input_ids: torch.Tensor): + """ + Compute the media token locations from lang_x and condition the language model on these. + Args: + input_ids (torch.Tensor): Language input + shape (B, T_txt) + """ + media_locations = input_ids == self.media_token_id + + for layer in self.lang_encoder._get_decoder_layers(): + layer.condition_media_locations(media_locations) + + def cache_media(self, input_ids: torch.Tensor, vision_x: torch.Tensor): + """ + Pre-cache a prompt/sequence of images / text for log-likelihood evaluations. + All subsequent calls to forward() will generate attending to the LAST + image in vision_x. + This is not meant to be used to cache things for generate(). + Args: + input_ids (torch.Tensor): Language input + shape (B, T_txt) + vision_x (torch.Tensor): Vision input + shape (B, T_img, F, C, H, W) + Images in the same chunk are collated along T_img, and frames are collated along F + Currently only F=1 is supported (single-frame videos) + """ + self._encode_vision_x(vision_x=vision_x) + self._condition_media_locations(input_ids=input_ids) + self.lang_encoder._use_cached_vision_x = True + + def uncache_media(self): + """ + Clear all conditioning. + """ + self.lang_encoder.clear_conditioned_layers() + self.lang_encoder._use_cached_vision_x = False diff --git a/open_flamingo/open_flamingo/src/flamingo_lm.py b/open_flamingo/open_flamingo/src/flamingo_lm.py new file mode 100644 index 0000000000000000000000000000000000000000..e424cdfab3ea36eccd96cfa9eee5388075ec20fc --- /dev/null +++ b/open_flamingo/open_flamingo/src/flamingo_lm.py @@ -0,0 +1,169 @@ +import torch.nn as nn +from .helpers import GatedCrossAttentionBlock +from .utils import getattr_recursive, setattr_recursive + + +class FlamingoLayer(nn.Module): + """ + FlamingoLayer is a wrapper around the GatedCrossAttentionBlock and DecoderLayer. + """ + + def __init__( + self, gated_cross_attn_layer, decoder_layer, gradient_checkpointing=False + ): + super().__init__() + self.gated_cross_attn_layer = gated_cross_attn_layer + self.decoder_layer = decoder_layer + self.vis_x = None + self.media_locations = None + if self.gated_cross_attn_layer is not None: + self.gated_cross_attn_layer._use_gradient_checkpointing = ( + gradient_checkpointing + ) + self.decoder_layer._use_gradient_checkpointing = gradient_checkpointing + + def is_conditioned(self) -> bool: + """Check whether the layer is conditioned.""" + return self.vis_x is not None and self.media_locations is not None + + # Used this great idea from this implementation of Flamingo (https://github.com/dhansmair/flamingo-mini/) + def condition_vis_x(self, vis_x): + self.vis_x = vis_x + + def condition_media_locations(self, media_locations): + self.media_locations = media_locations + + def condition_use_cached_media(self, use_cached_media): + self.use_cached_media = use_cached_media + + def forward( + self, + lang_x, + attention_mask=None, + **decoder_layer_kwargs, + ): + # Cross attention + if self.gated_cross_attn_layer is not None: + if self.vis_x is None: + raise ValueError("vis_x must be conditioned before forward pass") + + if self.media_locations is None: + raise ValueError( + "media_locations must be conditioned before forward pass" + ) + + lang_x = self.gated_cross_attn_layer( + lang_x, + self.vis_x, + media_locations=self.media_locations, + use_cached_media=self.use_cached_media, + ) + + # Normal decoder layer + lang_x = self.decoder_layer( + lang_x, attention_mask=attention_mask, **decoder_layer_kwargs + ) + return lang_x + + +class FlamingoLMMixin(nn.Module): + """ + Mixin to add cross-attention layers to a language model. + """ + + def set_decoder_layers_attr_name(self, decoder_layers_attr_name): + self.decoder_layers_attr_name = decoder_layers_attr_name + + def _get_decoder_layers(self): + return getattr_recursive(self, self.decoder_layers_attr_name) + + def _set_decoder_layers(self, value): + setattr_recursive(self, self.decoder_layers_attr_name, value) + + def init_flamingo( + self, + media_token_id, + lang_hidden_size, + vis_hidden_size, + cross_attn_every_n_layers, + gradient_checkpointing, + ): + """ + Initialize Flamingo by adding a new gated cross attn to the decoder. Store the media token id for computing the media locations. + """ + self.old_decoder_blocks = self._get_decoder_layers() + self.gated_cross_attn_layers = nn.ModuleList( + [ + GatedCrossAttentionBlock( + dim=lang_hidden_size, dim_visual=vis_hidden_size + ) + if (layer_idx + 1) % cross_attn_every_n_layers == 0 + else None + for layer_idx, _ in enumerate(self._get_decoder_layers()) + ] + ) + self.init_flamingo_layers(gradient_checkpointing) + self.media_token_id = media_token_id + self.initialized_flamingo = True + self._use_cached_vision_x = False + + def init_flamingo_layers(self, gradient_checkpointing): + """ + Re initializes the FlamingoLayers. + Propagates any changes made to self.gated_corss_attn_layers or self.old_decoder_blocks + """ + self._set_decoder_layers( + nn.ModuleList( + [ + FlamingoLayer( + gated_cross_attn_layer, decoder_layer, gradient_checkpointing + ) + for gated_cross_attn_layer, decoder_layer in zip( + self.gated_cross_attn_layers, self.old_decoder_blocks + ) + ] + ) + ) + + def forward(self, input_ids, attention_mask, **kwargs): + """Condition the Flamingo layers on the media locations before forward()""" + if not self.initialized_flamingo: + raise ValueError( + "Flamingo layers are not initialized. Please call `init_flamingo` first." + ) + + media_locations = input_ids == self.media_token_id + + # if there are media already cached and we're generating and there are no media tokens in the input, + # we'll assume that ALL input tokens should attend to the last previous media that is cached. + # this is especially important for HF generate() compatibility, since generate() calls forward() + # repeatedly one token at a time (with no media tokens). + # without this check, the model would not attend to any images when generating (after the first token) + use_cached_media_locations = ( + self._use_cached_vision_x + and self.is_conditioned() + and not media_locations.any() + ) + + for layer in self._get_decoder_layers(): + if not use_cached_media_locations: + layer.condition_media_locations(media_locations) + layer.condition_use_cached_media(use_cached_media_locations) + + # package arguments for the other parent's forward. since we don't know the order of the arguments, + # make them all kwargs + kwargs["input_ids"] = input_ids + kwargs["attention_mask"] = attention_mask + return super().forward( + **kwargs + ) # Call the other parent's forward method + + def is_conditioned(self) -> bool: + """Check whether all decoder layers are already conditioned.""" + return all(l.is_conditioned() for l in self._get_decoder_layers()) + + def clear_conditioned_layers(self): + for layer in self._get_decoder_layers(): + layer.condition_vis_x(None) + layer.condition_media_locations(None) + layer.condition_use_cached_media(None) diff --git a/open_flamingo/open_flamingo/src/helpers.py b/open_flamingo/open_flamingo/src/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..239503f8693c1c94d1441e496c1a6b90e0c25cdb --- /dev/null +++ b/open_flamingo/open_flamingo/src/helpers.py @@ -0,0 +1,279 @@ +""" +Based on: https://github.com/lucidrains/flamingo-pytorch +""" + +import torch +from einops import rearrange, repeat +from einops_exts import rearrange_many +from torch import einsum, nn + + +def exists(val): + return val is not None + + +def FeedForward(dim, mult=4): + inner_dim = int(dim * mult) + return nn.Sequential( + nn.LayerNorm(dim), + nn.Linear(dim, inner_dim, bias=False), + nn.GELU(), + nn.Linear(inner_dim, dim, bias=False), + ) + + +class PerceiverAttention(nn.Module): + def __init__(self, *, dim, dim_head=64, heads=8): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + inner_dim = dim_head * heads + + self.norm_media = nn.LayerNorm(dim) + self.norm_latents = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + def forward(self, x, latents): + """ + Args: + x (torch.Tensor): image features + shape (b, T, n1, D) + latent (torch.Tensor): latent features + shape (b, T, n2, D) + """ + x = self.norm_media(x) + latents = self.norm_latents(latents) + + h = self.heads + + q = self.to_q(latents) + kv_input = torch.cat((x, latents), dim=-2) + k, v = self.to_kv(kv_input).chunk(2, dim=-1) + q, k, v = rearrange_many((q, k, v), "b t n (h d) -> b h t n d", h=h) + q = q * self.scale + + # attention + sim = einsum("... i d, ... j d -> ... i j", q, k) + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + attn = sim.softmax(dim=-1) + + out = einsum("... i j, ... j d -> ... i d", attn, v) + out = rearrange(out, "b h t n d -> b t n (h d)", h=h) + return self.to_out(out) + + +class PerceiverResampler(nn.Module): + def __init__( + self, + *, + dim, + depth=6, + dim_head=64, + heads=8, + num_latents=64, + max_num_media=None, + max_num_frames=None, + ff_mult=4, + ): + super().__init__() + self.latents = nn.Parameter(torch.randn(num_latents, dim)) + self.frame_embs = ( + nn.Parameter(torch.randn(max_num_frames, dim)) + if exists(max_num_frames) + else None + ) + self.media_time_embs = ( + nn.Parameter(torch.randn(max_num_media, 1, dim)) + if exists(max_num_media) + else None + ) + + self.layers = nn.ModuleList([]) + for _ in range(depth): + self.layers.append( + nn.ModuleList( + [ + PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads), + FeedForward(dim=dim, mult=ff_mult), + ] + ) + ) + + self.norm = nn.LayerNorm(dim) + + def forward(self, x): + """ + Args: + x (torch.Tensor): image features + shape (b, T, F, v, D) + Returns: + shape (b, T, n, D) where n is self.num_latents + """ + b, T, F, v = x.shape[:4] + + # frame and media time embeddings + if exists(self.frame_embs): + frame_embs = repeat(self.frame_embs[:F], "F d -> b T F v d", b=b, T=T, v=v) + x = x + frame_embs + x = rearrange( + x, "b T F v d -> b T (F v) d" + ) # flatten the frame and spatial dimensions + if exists(self.media_time_embs): + x = x + self.media_time_embs[:T] + + # blocks + latents = repeat(self.latents, "n d -> b T n d", b=b, T=T) + for attn, ff in self.layers: + latents = attn(x, latents) + latents + latents = ff(latents) + latents + return self.norm(latents) + + +# gated cross attention +class MaskedCrossAttention(nn.Module): + def __init__( + self, + *, + dim, + dim_visual, + dim_head=64, + heads=8, + only_attend_immediate_media=True, + ): + super().__init__() + self.scale = dim_head**-0.5 + self.heads = heads + inner_dim = dim_head * heads + + self.norm = nn.LayerNorm(dim) + + self.to_q = nn.Linear(dim, inner_dim, bias=False) + self.to_kv = nn.Linear(dim_visual, inner_dim * 2, bias=False) + self.to_out = nn.Linear(inner_dim, dim, bias=False) + + # whether for text to only attend to immediate preceding image, or all previous images + self.only_attend_immediate_media = only_attend_immediate_media + + def forward(self, x, media, media_locations=None, use_cached_media=False): + """ + Args: + x (torch.Tensor): text features + shape (B, T_txt, D_txt) + media (torch.Tensor): image features + shape (B, T_img, n, D_img) where n is the dim of the latents + media_locations: boolean mask identifying the media tokens in x + shape (B, T_txt) + use_cached_media: bool + If true, treat all of x as if they occur after the last media + registered in media_locations. T_txt does not need to exactly + equal media_locations.shape[1] in this case + """ + + if not use_cached_media: + assert ( + media_locations.shape[1] == x.shape[1] + ), f"media_location.shape is {media_locations.shape} but x.shape is {x.shape}" + + T_txt = x.shape[1] + _, T_img, n = media.shape[:3] + h = self.heads + + x = self.norm(x) + + q = self.to_q(x) + media = rearrange(media, "b t n d -> b (t n) d") + + k, v = self.to_kv(media).chunk(2, dim=-1) + q, k, v = rearrange_many((q, k, v), "b n (h d) -> b h n d", h=h) + + q = q * self.scale + + sim = einsum("... i d, ... j d -> ... i j", q, k) + + if exists(media_locations): + media_time = torch.arange(T_img, device=x.device) + 1 + + if use_cached_media: + # text time is set to the last cached media location + text_time = repeat( + torch.count_nonzero(media_locations, dim=1), + "b -> b i", + i=T_txt, + ) + else: + # at each boolean of True, increment the time counter (relative to media time) + text_time = media_locations.cumsum(dim=-1) + + # text time must equal media time if only attending to most immediate image + # otherwise, as long as text time is greater than media time (if attending to all previous images / media) + mask_op = torch.eq if self.only_attend_immediate_media else torch.ge + + text_to_media_mask = mask_op( + rearrange(text_time, "b i -> b 1 i 1"), + repeat(media_time, "j -> 1 1 1 (j n)", n=n), + ) + sim = sim.masked_fill(~text_to_media_mask, -torch.finfo(sim.dtype).max) + + sim = sim - sim.amax(dim=-1, keepdim=True).detach() + attn = sim.softmax(dim=-1) + + if exists(media_locations) and self.only_attend_immediate_media: + # any text without a preceding media needs to have attention zeroed out + text_without_media_mask = text_time == 0 + text_without_media_mask = rearrange( + text_without_media_mask, "b i -> b 1 i 1" + ) + attn = attn.masked_fill(text_without_media_mask, 0.0) + + out = einsum("... i j, ... j d -> ... i d", attn, v) + out = rearrange(out, "b h n d -> b n (h d)") + return self.to_out(out) + + +class GatedCrossAttentionBlock(nn.Module): + def __init__( + self, + *, + dim, + dim_visual, + dim_head=64, + heads=8, + ff_mult=4, + only_attend_immediate_media=True, + ): + super().__init__() + self.attn = MaskedCrossAttention( + dim=dim, + dim_visual=dim_visual, + dim_head=dim_head, + heads=heads, + only_attend_immediate_media=only_attend_immediate_media, + ) + self.attn_gate = nn.Parameter(torch.tensor([0.0])) + + self.ff = FeedForward(dim, mult=ff_mult) + self.ff_gate = nn.Parameter(torch.tensor([0.0])) + + def forward( + self, + x, + media, + media_locations=None, + use_cached_media=False, + ): + x = ( + self.attn( + x, + media, + media_locations=media_locations, + use_cached_media=use_cached_media, + ) + * self.attn_gate.tanh() + + x + ) + x = self.ff(x) * self.ff_gate.tanh() + x + + return x diff --git a/open_flamingo/open_flamingo/src/utils.py b/open_flamingo/open_flamingo/src/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7895264638c7f52660e01436de00cc2bc0e52a89 --- /dev/null +++ b/open_flamingo/open_flamingo/src/utils.py @@ -0,0 +1,48 @@ +def extend_instance(obj, mixin): + """Apply mixins to a class instance after creation""" + base_cls = obj.__class__ + base_cls_name = obj.__class__.__name__ + obj.__class__ = type( + base_cls_name, (mixin, base_cls), {} + ) # mixin needs to go first for our forward() logic to work + + +def getattr_recursive(obj, att): + """ + Return nested attribute of obj + Example: getattr_recursive(obj, 'a.b.c') is equivalent to obj.a.b.c + """ + if att == "": + return obj + i = att.find(".") + if i < 0: + return getattr(obj, att) + else: + return getattr_recursive(getattr(obj, att[:i]), att[i + 1 :]) + + +def setattr_recursive(obj, att, val): + """ + Set nested attribute of obj + Example: setattr_recursive(obj, 'a.b.c', val) is equivalent to obj.a.b.c = val + """ + if "." in att: + obj = getattr_recursive(obj, ".".join(att.split(".")[:-1])) + setattr(obj, att.split(".")[-1], val) + + +def apply_with_stopping_condition( + module, apply_fn, apply_condition=None, stopping_condition=None, **other_args +): + if stopping_condition(module): + return + if apply_condition(module): + apply_fn(module, **other_args) + for child in module.children(): + apply_with_stopping_condition( + child, + apply_fn, + apply_condition=apply_condition, + stopping_condition=stopping_condition, + **other_args + ) diff --git a/open_flamingo/open_flamingo/train/README.md b/open_flamingo/open_flamingo/train/README.md new file mode 100644 index 0000000000000000000000000000000000000000..672ac47e217e6f06f4f8c295a890a84d1e021910 --- /dev/null +++ b/open_flamingo/open_flamingo/train/README.md @@ -0,0 +1,63 @@ +# OpenFlamingo Training +To train OpenFlamingo, please ensure your environment matches that of `environment.yml`. + +## Data +Our codebase uses [WebDataset](https://github.com/webdataset/webdataset) to efficiently load `.tar` files containing image and text sequences. We recommend resampling shards with replacement during training using the `--dataset_resampled` flag. + +### LAION-2B Dataset +[LAION-2B](https://arxiv.org/abs/2210.08402) contains 2B web-scraped (image, text) pairs. +We use [img2dataset](https://github.com/rom1504/img2dataset) to download this dataset into tar files. + +### Multimodal C4 Dataset +We train on the full version of [Multimodal C4 (MMC4)](https://github.com/allenai/mmc4), which includes 103M documents of web-scraped, interleaved image-text sequences. During training, we truncate sequences to 256 text tokens and six images per sequence. + +Our codebase expects `.tar` files containing `.json` files, which include raw images encoded in base64. +We provide scripts to convert MMC4 to this format: + +1. Download the MMC4 shards into `.zip` files using [the MMC4-provided scripts](https://github.com/allenai/mmc4/tree/main/scripts) (e.g., `fewer_facesv2.sh`). +2. Download the MMC4 raw images into an image directory using [the MMC4-provided scripts](https://github.com/allenai/mmc4/tree/main/scripts) (e.g., `download_images.py`). +2. Run `scripts/convert_mmc4_to_wds.py` to convert the downloaded items into the expected tar files. + +### ChatGPT-generated sequences +A subset of our models (listed below) were also trained on experimental ChatGPT-generated (image, text) sequences, where images are pulled from LAION. We are working to release these sequences soon. + +* OpenFlamingo-4B-vitl-rpj3b +* OpenFlamingo-4B-vitl-rpj3b-langinstruct + +## Example training command +We provide a sample Slurm training script in `scripts/`. You can also modify the following command: + +``` +torchrun --nnodes=1 --nproc_per_node=4 train.py \ + --lm_path anas-awadalla/mpt-1b-redpajama-200b \ + --tokenizer_path anas-awadalla/mpt-1b-redpajama-200b \ + --cross_attn_every_n_layers 1 \ + --dataset_resampled \ + --batch_size_mmc4 32 \ + --batch_size_laion 64 \ + --train_num_samples_mmc4 125000\ + --train_num_samples_laion 250000 \ + --loss_multiplier_laion 0.2 \ + --workers=4 \ + --run_name OpenFlamingo-3B-vitl-mpt1b \ + --num_epochs 480 \ + --warmup_steps 1875 \ + --mmc4_textsim_threshold 0.24 \ + --laion_shards "/path/to/shards/shard-{0000..0999}.tar" \ + --mmc4_shards "/path/to/shards/shard-{0000..0999}.tar" \ + --report_to_wandb +``` +*Note: The MPT-1B [base](https://huggingface.co/mosaicml/mpt-1b-redpajama-200b) and [instruct](https://huggingface.co/mosaicml/mpt-1b-redpajama-200b-dolly) modeling code does not accept the `labels` kwarg or compute cross-entropy loss directly within `forward()`, as expected by our codebase. We suggest using a modified version of the MPT-1B models found [here](https://huggingface.co/anas-awadalla/mpt-1b-redpajama-200b) and [here](https://huggingface.co/anas-awadalla/mpt-1b-redpajama-200b-dolly).* + +## Distributed training + +By default, `train.py` uses Pytorch's [DistributedDataParallel](https://pytorch.org/docs/stable/torch.nn.parallel.DistributedDataParallel.html) for training. +To use [FullyShardedDataParallel](https://pytorch.org/docs/stable/fsdp.html), use the `--fsdp` flag. + +Some notes on FSDP: + +* We recommend using the `--fsdp_use_orig_params` flag. If `--fsdp` is on without this flag, all language model embeddings will be unfrozen during training. (In contrast, the default behavior is to only train the newly added `` and `<|endofchunk|>` tokens.) + * Note: we've encountered issues using OPT with this flag. Other language models should be compatible. +* Our current FSDP wrapping strategy does not permit training language model embeddings that use tied weights (i.e., tied input / output embeddings). To train such models with FSDP, the language model embeddings must be frozen with the `--freeze_lm_embeddings` flag. + +We also implement gradient checkpointing and mixed precision training. Use the `--gradient_checkpointing` and `--precision` arguments respectively. \ No newline at end of file diff --git a/open_flamingo/open_flamingo/train/__init__.py b/open_flamingo/open_flamingo/train/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/open_flamingo/open_flamingo/train/__init__.py @@ -0,0 +1 @@ + diff --git a/open_flamingo/open_flamingo/train/data.py b/open_flamingo/open_flamingo/train/data.py new file mode 100644 index 0000000000000000000000000000000000000000..8cbe619f52dcc29b344796250e42f458ed757c1f --- /dev/null +++ b/open_flamingo/open_flamingo/train/data.py @@ -0,0 +1,476 @@ +""" +Preprocess and load datasets for training. +""" + +import functools +import io +import json +import math +import re +import random +import numpy as np +import torch +import torchvision +import webdataset as wds +from PIL import Image +import base64 + +from data_utils import * + +Image.MAX_IMAGE_PIXELS = 1000000000 +MAX_NUM_TOKENS = 256 +N_CHANNELS = 3 +MIN_KB = 10 +_SHARD_SHUFFLE_SIZE = 2000 +_SHARD_SHUFFLE_INITIAL = 500 +_SAMPLE_SHUFFLE_SIZE = 5000 +_SAMPLE_SHUFFLE_INITIAL = 1000 + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + + +def preprocess_image(sample, image_processor): + """ + Convert images to tensors for training. + Augmentations: random horizontal flip. + Normalization handled by wds. + """ + image = [image_processor(s).unsqueeze(0) for s in sample] + image = torch.cat(image, dim=0) + image = torchvision.transforms.RandomHorizontalFlip(p=0.5)(image) + return image + + +def filter_no_caption_or_no_image(sample): + """ + Filter out LAION samples with no caption or no image. + """ + return ("txt" in sample) and ( + "png" in sample or "jpg" in sample or "jpeg" in sample + ) + + +def preprocess_laion_text(sample, tokenizer, max_tokens=32): + """ + Preprocess text for LAION. + Captions are truncated to 32 tokens by default. + """ + tokenizer.padding_side = "right" + sample = [ + (f"{s.strip()}<|endofchunk|>{tokenizer.eos_token}") for s in sample + ] + text = tokenizer( + sample, + max_length=max_tokens, + padding="longest", + truncation="only_first", + return_tensors="pt", + ) + return text["input_ids"], text["attention_mask"] + + +def preprocess_gpt_interleaved( + info, tokenizer, clip_processor, min_num_images, max_num_images, max_tokens=256 +): + """ + Preprocess a ChatGPT-generated image-text sequence. + """ + text = info["example"] + text = re.sub(r"_!_IMAGE\d+_!_", "<|endofchunk|>", text) + + # convert images from base64 to PIL + images = [] + for image_key in range(1, len(info["image_map"]) + 1): + image_base64 = info["image_map"][f"_!_IMAGE{image_key}_!_"]["base64_image"] + rawbytes = base64.b64decode(image_base64) + images.append(Image.open(io.BytesIO(rawbytes)).convert("RGB")) + + # preprocess and pad images + images_tensors = preprocess_image(images, clip_processor) + keep_ixs = range(min(len(images_tensors), max_num_images)) + images_tensors = images_tensors[keep_ixs] + if len(images_tensors) < max_num_images: + zero_padding = torch.zeros( + (max_num_images - len(images_tensors), 3, 224, 224), dtype=torch.float + ) + images_tensors = torch.cat((images_tensors, zero_padding), dim=0) + + # preprocess and tokenize text + text = text.replace("<|endofchunk|>", "", 1) # but remove first eoc + # whitespace cleanup + text = ( + text.replace(" <|endofchunk|>", "<|endofchunk|>") + .replace(" ", "") + .replace(" ", "") + ) + + indices = [m.start() for m in re.finditer("", text)] + if len(indices) > max_num_images: + start_index = indices[max_num_images - 1] + text = text[:start_index] + + text = f"{text}<|endofchunk|>{tokenizer.eos_token}" + tokenizer.padding_side = "right" + text_tensor = tokenizer( + text, + max_length=max_tokens, + truncation=True, + padding="max_length", + return_tensors="pt", + ) + + # reject sequences with too few images after truncation + num_images = torch.count_nonzero( + text_tensor["input_ids"] + == tokenizer.additional_special_tokens_ids[ + tokenizer.additional_special_tokens.index("") + ] + ) + if num_images < min_num_images: + raise ValueError(f"Fewer than {min_num_images} images in sample") + + return (images_tensors, (text_tensor["input_ids"], text_tensor["attention_mask"])) + + +def preprocess_interleaved( + sample, + tokenizer, + clip_processor, + sim_threshold, + min_num_images, + max_num_images, + max_tokens=256, +): + """ + Preprocess an interleaved image-text sequence, either by calling preprocess_gpt_interleaved (if the sequence + is ChatGPT-generated) or by preprocessing in this function (if the sequences is from MMC4). + """ + info = json.loads(sample[0]) + if "is_gpt" in info: + return preprocess_gpt_interleaved( + info, tokenizer, clip_processor, min_num_images, max_num_images, max_tokens + ) + + sentences = info["text_list"] + sim_matrix = info["similarity_matrix"] + + # convert images from base64 to PIL and filter based on image-text similarity + images, sentence_ixs = [], [] + for sample_image, sim_vec in zip(info["image_info"], sim_matrix): + if "image_base64" not in sample_image: + continue + image_base64 = sample_image["image_base64"] + rawbytes = base64.b64decode(image_base64) + + sim_ix = np.argmax(sim_vec) + sim_score = sim_vec[sim_ix] + + # filter to images >= 10KB + if len(rawbytes) // 1000 <= MIN_KB: + continue + if sim_score < sim_threshold: + continue + image = Image.open(io.BytesIO(rawbytes)).convert("RGB") + + images.append(image) + sentence_ixs.append(sim_ix) + + if len(images) == 0: + raise ValueError("No images in sample") + + # preprocess and pad images + images_tensors = preprocess_image(images, clip_processor) + keep_ixs = range(min(len(images_tensors), max_num_images)) + images_tensors = images_tensors[keep_ixs] + sentence_ixs = [sentence_ixs[ix] for ix in keep_ixs] + if len(images_tensors) < max_num_images: + zero_padding = torch.zeros( + ( + max_num_images - len(images_tensors), + N_CHANNELS, + images_tensors[0].shape[1], + images_tensors[0].shape[2] + ), + dtype=torch.float, + ) + images_tensors = torch.cat((images_tensors, zero_padding), dim=0) + + # preprocess and tokenize text + # add in and tokens + for ix in sentence_ixs: + sentences[ix] = f"<|endofchunk|>{sentences[ix]}" + text = " ".join(sentences) + text = text.replace("<|endofchunk|>", "", 1) # but remove first eoc + # whitespace cleanup + text = ( + text.replace(" <|endofchunk|>", "<|endofchunk|>") + .replace(" ", "") + .replace(" ", "") + ) + text = f"{text}<|endofchunk|>{tokenizer.eos_token}" + tokenizer.padding_side = "right" + text_tensor = tokenizer( + text, + max_length=max_tokens, + truncation=True, + padding="max_length", + return_tensors="pt", + ) + + # reject sequences with too few images (after truncation) + num_images = torch.count_nonzero( + text_tensor["input_ids"] + == tokenizer.additional_special_tokens_ids[ + tokenizer.additional_special_tokens.index("") + ] + ) + if num_images < min_num_images: + raise ValueError(f"Fewer than {min_num_images} images in sample") + elif ( + num_images == 1 and random.random() <= 0.5 + ): # 50% chance of keeping single image samples + raise ValueError("Only one image in sample") + + # avoid the situation where there's one token and it's at the end + if ( + num_images == 1 + and text_tensor["input_ids"][:, -1] + == tokenizer.additional_special_tokens_ids[ + tokenizer.additional_special_tokens.index("") + ] + ): + raise ValueError( + "Only one image at the end of sample, so labels will all be -100" + ) + + return ( + images_tensors, + (text_tensor["input_ids"], text_tensor["attention_mask"]), + ) + + +def get_mmc4_dataset(args, image_processor, tokenizer, epoch=0, floor=False): + """ + Initialize webdataset for MMC4 / ChatGPT sequences + """ + input_shards = args.mmc4_shards + assert input_shards is not None + resampled = getattr(args, "dataset_resampled", False) + + num_samples, num_shards = get_dataset_size(input_shards) + num_samples = None + if not num_samples: + num_samples = args.train_num_samples_mmc4 + if not num_samples: + raise RuntimeError( + "Currently, number of dataset samples must be specified for training dataset. " + "Please specify via `--train-num-samples` if no dataset length info present." + ) + + # create a shared epoch store to sync epoch to dataloader worker proc + shared_epoch = SharedEpoch(epoch=epoch) + if resampled: + pipeline = [ + ResampledShards2(input_shards, deterministic=True, epoch=shared_epoch) + ] + else: + pipeline = [wds.SimpleShardList(input_shards)] + + preprocess_fn = functools.partial( + preprocess_interleaved, + clip_processor=image_processor, + tokenizer=tokenizer, + sim_threshold=args.mmc4_textsim_threshold, + min_num_images=args.mmc4_min_num_images, + max_num_images=args.mmc4_max_num_images, + ) + + # at this point we have an iterator over all the shards + if not resampled: + pipeline.extend( + [ + detshuffle2( + bufsize=_SHARD_SHUFFLE_SIZE, + initial=_SHARD_SHUFFLE_INITIAL, + seed=args.seed, + epoch=shared_epoch, + ), + wds.split_by_node, + wds.split_by_worker, + ] + ) + pipeline.extend( + [ + # at this point, we have an iterator over the shards assigned to each worker at each node + # wds.tarfile_to_samples(handler=log_and_continue), + tarfile_to_samples_nothrow, + wds.shuffle( + bufsize=_SAMPLE_SHUFFLE_SIZE, + initial=_SAMPLE_SHUFFLE_INITIAL, + ), + ] + ) + + pipeline.extend( + [ + wds.to_tuple("json", handler=log_and_continue), + wds.map(preprocess_fn, handler=log_and_continue), + wds.batched(args.batch_size_mmc4, partial=False), + ] + ) + + dataset = wds.DataPipeline(*pipeline) + if not resampled: + assert ( + num_shards >= args.workers * args.world_size + ), "number of shards must be >= total workers" + # roll over and repeat a few samples to get same number of full batches on each node + round_fn = math.floor if floor else math.ceil + global_batch_size = args.batch_size_mmc4 * args.world_size + num_batches = round_fn(num_samples / global_batch_size) + num_workers = max(1, args.workers) + num_worker_batches = round_fn(num_batches / num_workers) # per dataloader worker + num_batches = num_worker_batches * num_workers + num_samples = num_batches * global_batch_size + # each worker is iterating over this + dataset = dataset.with_epoch(num_worker_batches) + + dataloader = wds.WebLoader( + dataset, + batch_size=None, + shuffle=False, + num_workers=args.workers, + persistent_workers=True, + ) + + # add meta-data to dataloader instance for convenience + dataloader.num_batches = num_batches + dataloader.num_samples = num_samples + + return DataInfo(dataloader=dataloader, shared_epoch=shared_epoch) + + +def get_laion_dataset(args, image_processor, tokenizer, epoch=0, floor=False): + """ + Initialize webdataset for LAION data + """ + input_shards = args.laion_shards + assert input_shards is not None + resampled = getattr(args, "dataset_resampled", False) + + num_samples, num_shards = get_dataset_size(input_shards) + num_samples = None + if not num_samples: + num_samples = args.train_num_samples_laion + if not num_samples: + raise RuntimeError( + "Currently, number of dataset samples must be specified for training dataset. " + "Please specify via `--train-num-samples` if no dataset length info present." + ) + + # create a shared epoch store to sync epoch to dataloader worker proc + shared_epoch = SharedEpoch(epoch=epoch) + if resampled: + pipeline = [ + ResampledShards2(input_shards, deterministic=True, epoch=shared_epoch) + ] + else: + pipeline = [wds.SimpleShardList(input_shards)] + + # create two preprocess functions that take in the passed in image_processor and tokenizer + preprocess_image_fn = functools.partial( + preprocess_image, image_processor=image_processor + ) + preprocess_text_fn = functools.partial(preprocess_laion_text, tokenizer=tokenizer) + + # at this point we have an iterator over all the shards + if not resampled: + pipeline.extend( + [ + detshuffle2( + bufsize=_SHARD_SHUFFLE_SIZE, + initial=_SHARD_SHUFFLE_INITIAL, + seed=args.seed, + epoch=shared_epoch, + ), + wds.split_by_node, + wds.split_by_worker, + ] + ) + pipeline.extend( + [ + # at this point, we have an iterator over the shards assigned to each worker at each node + # wds.tarfile_to_samples(handler=log_and_continue), + tarfile_to_samples_nothrow, + wds.shuffle( + bufsize=_SAMPLE_SHUFFLE_SIZE, + initial=_SAMPLE_SHUFFLE_INITIAL, + ), + ] + ) + + pipeline.extend( + [ + wds.select(filter_no_caption_or_no_image), + wds.decode("pilrgb", handler=log_and_continue), + wds.to_tuple("jpg;png;jpeg", "txt", handler=log_and_continue), + wds.batched(args.batch_size_laion, partial=False), + wds.map_tuple( + preprocess_image_fn, preprocess_text_fn, handler=log_and_continue + ), + ] + ) + + dataset = wds.DataPipeline(*pipeline) + if not resampled: + assert ( + num_shards >= args.workers * args.world_size + ), "number of shards must be >= total workers" + # roll over and repeat a few samples to get same number of full batches on each node + round_fn = math.floor if floor else math.ceil + global_batch_size = args.batch_size_laion * args.world_size + num_batches = round_fn(num_samples / global_batch_size) + num_workers = max(1, args.workers) + num_worker_batches = round_fn(num_batches / num_workers) # per dataloader worker + num_batches = num_worker_batches * num_workers + num_samples = num_batches * global_batch_size + # each worker is iterating over this + dataset = dataset.with_epoch(num_worker_batches) + + dataloader = wds.WebLoader( + dataset, + batch_size=None, + shuffle=False, + num_workers=args.workers, + persistent_workers=True, + ) + + # add meta-data to dataloader instance for convenience + dataloader.num_batches = num_batches + dataloader.num_samples = num_samples + + return DataInfo(dataloader=dataloader, shared_epoch=shared_epoch) + + +def get_dataset_fn(dataset_type): + """ + Helper function to get the dataset function based on the dataset type + """ + if dataset_type == "image_text": + return get_laion_dataset + elif dataset_type == "mmc4": + return get_mmc4_dataset + else: + raise ValueError(f"Unsupported dataset type: {dataset_type}") + + +def get_data(args, image_processor, tokenizer, dataset_type, epoch=0): + """ + Interface for getting the webdatasets + """ + return get_dataset_fn(dataset_type)( + args, image_processor=image_processor, epoch=epoch, tokenizer=tokenizer + ) diff --git a/open_flamingo/open_flamingo/train/data_utils.py b/open_flamingo/open_flamingo/train/data_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2cf269e843d0c52182908c1798c0ef88fe1ffce5 --- /dev/null +++ b/open_flamingo/open_flamingo/train/data_utils.py @@ -0,0 +1,235 @@ +""" +Util functions for initializing webdataset objects +""" + +import ast +import json +import logging +import os +import random +import sys +from dataclasses import dataclass +from multiprocessing import Value + +import braceexpand +import numpy as np +import webdataset as wds +from PIL import Image +from torch.utils.data import DataLoader, IterableDataset, get_worker_info +from torch.utils.data.distributed import DistributedSampler +from webdataset.filters import _shuffle +from webdataset.tariterators import ( + base_plus_ext, + tar_file_expander, + url_opener, + valid_sample, +) + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + + +class SharedEpoch: + def __init__(self, epoch: int = 0): + self.shared_epoch = Value("i", epoch) + + def set_value(self, epoch): + self.shared_epoch.value = epoch + + def get_value(self): + return self.shared_epoch.value + + +@dataclass +class DataInfo: + dataloader: DataLoader + sampler: DistributedSampler = None + shared_epoch: SharedEpoch = None + + def set_epoch(self, epoch): + if self.shared_epoch is not None: + self.shared_epoch.set_value(epoch) + if self.sampler is not None and isinstance(self.sampler, DistributedSampler): + self.sampler.set_epoch(epoch) + + +def get_dataset_size(shards): + shards_list = list(braceexpand.braceexpand(shards)) + shards_list = shards + dir_path = os.path.dirname(shards[0]) + sizes_filename = os.path.join(dir_path, "sizes.json") + len_filename = os.path.join(dir_path, "__len__") + if os.path.exists(sizes_filename): + sizes = json.load(open(sizes_filename, "r")) + total_size = sum( + [ + int(sizes[os.path.basename(shard)]) + if os.path.basename(shard) in sizes + else 0 + for shard in shards_list + ] + ) + elif os.path.exists(len_filename): + # FIXME this used to be eval(open(...)) but that seemed rather unsafe + total_size = ast.literal_eval(open(len_filename, "r").read()) + else: + total_size = None # num samples undefined + # some common dataset sizes (at time of authors last download) + # CC3M (train): 2905954 + # CC12M: 10968539 + # LAION-400M: 407332084 + # LAION-2B (english): 2170337258 + num_shards = len(shards_list) + return total_size, num_shards + + +def count_samples(dataloader): + os.environ["WDS_EPOCH"] = "0" + n_elements, n_batches = 0, 0 + for images, texts in dataloader: + n_batches += 1 + n_elements += len(images) + assert len(images) == len(texts) + return n_elements, n_batches + + +def log_and_continue(exn): + """Call in an exception handler to ignore any exception, issue a warning, and continue.""" + logging.warning(f"Handling webdataset error ({repr(exn)}). Ignoring.") + return True + + +def group_by_keys_nothrow( + data, keys=base_plus_ext, lcase=True, suffixes=None, handler=None +): + """Return function over iterator that groups key, value pairs into samples. + + :param keys: function that splits the key into key and extension (base_plus_ext) + :param lcase: convert suffixes to lower case (Default value = True) + """ + current_sample = None + for filesample in data: + assert isinstance(filesample, dict) + fname, value = filesample["fname"], filesample["data"] + prefix, suffix = keys(fname) + if prefix is None: + continue + if lcase: + suffix = suffix.lower() + # FIXME webdataset version throws if suffix in current_sample, but we have a potential for + # this happening in the current LAION400m dataset if a tar ends with same prefix as the next + # begins, rare, but can happen since prefix aren't unique across tar files in that dataset + if ( + current_sample is None + or prefix != current_sample["__key__"] + or suffix in current_sample + ): + if valid_sample(current_sample): + yield current_sample + current_sample = dict(__key__=prefix, __url__=filesample["__url__"]) + if suffixes is None or suffix in suffixes: + current_sample[suffix] = value + if valid_sample(current_sample): + yield current_sample + + +def tarfile_to_samples_nothrow(src, handler=log_and_continue): + # NOTE this is a re-impl of the webdataset impl with group_by_keys that doesn't throw + streams = url_opener(src, handler=handler) + files = tar_file_expander(streams, handler=handler) + samples = group_by_keys_nothrow(files, handler=handler) + return samples + + +def pytorch_worker_seed(increment=0): + """get dataloader worker seed from pytorch""" + worker_info = get_worker_info() + if worker_info is not None: + # favour using the seed already created for pytorch dataloader workers if it exists + seed = worker_info.seed + if increment: + # space out seed increments so they can't overlap across workers in different iterations + seed += increment * max(1, worker_info.num_workers) + return seed + # fallback to wds rank based seed + return wds.utils.pytorch_worker_seed() + + +class detshuffle2(wds.PipelineStage): + def __init__( + self, + bufsize=1000, + initial=100, + seed=0, + epoch=-1, + ): + self.bufsize = bufsize + self.initial = initial + self.seed = seed + self.epoch = epoch + + def run(self, src): + if isinstance(self.epoch, SharedEpoch): + epoch = self.epoch.get_value() + else: + # NOTE: this is epoch tracking is problematic in a multiprocess (dataloader workers or train) + # situation as different workers may wrap at different times (or not at all). + self.epoch += 1 + epoch = self.epoch + rng = random.Random() + if self.seed < 0: + # If seed is negative, we use the worker's seed, this will be different across all nodes/workers + seed = pytorch_worker_seed(epoch) + else: + # This seed to be deterministic AND the same across all nodes/workers in each epoch + seed = self.seed + epoch + rng.seed(seed) + return _shuffle(src, self.bufsize, self.initial, rng) + + +class ResampledShards2(IterableDataset): + """An iterable dataset yielding a list of urls.""" + + def __init__( + self, + urls, + nshards=sys.maxsize, + worker_seed=None, + deterministic=False, + epoch=-1, + ): + """Sample shards from the shard list with replacement. + :param urls: a list of URLs as a Python list or brace notation string + """ + super().__init__() + urls = wds.shardlists.expand_urls(urls) + self.urls = urls + assert isinstance(self.urls[0], str) + self.nshards = nshards + self.rng = random.Random() + self.worker_seed = worker_seed + self.deterministic = deterministic + self.epoch = epoch + + def __iter__(self): + """Return an iterator over the shards.""" + if isinstance(self.epoch, SharedEpoch): + epoch = self.epoch.get_value() + else: + # NOTE: this is epoch tracking is problematic in a multiprocess (dataloader workers or train) + # situation as different workers may wrap at different times (or not at all). + self.epoch += 1 + epoch = self.epoch + + if self.deterministic: + # reset seed w/ epoch if deterministic + if self.worker_seed is None: + # pytorch worker seed should be deterministic due to being init by arg.seed + rank + worker id + seed = pytorch_worker_seed(epoch) + else: + seed = self.worker_seed() + epoch + self.rng.seed(seed) + for _ in range(self.nshards): + yield dict(url=self.rng.choice(self.urls)) diff --git a/open_flamingo/open_flamingo/train/distributed.py b/open_flamingo/open_flamingo/train/distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..2e1a3fe11754a6652ff70e4534c018ab4f3f15b2 --- /dev/null +++ b/open_flamingo/open_flamingo/train/distributed.py @@ -0,0 +1,132 @@ +""" +Util functions for setting up distributed training. +Credit: https://github.com/mlfoundations/open_clip/blob/main/src/training/distributed.py +""" + +import os +import torch + +try: + import horovod.torch as hvd +except ImportError: + hvd = None + + +def is_global_master(args): + return args.rank == 0 + + +def is_local_master(args): + return args.local_rank == 0 + + +def is_master(args, local=False): + return is_local_master(args) if local else is_global_master(args) + + +def is_using_horovod(): + # NOTE w/ horovod run, OMPI vars should be set, but w/ SLURM PMI vars will be set + # Differentiating between horovod and DDP use via SLURM may not be possible, so horovod arg still required... + ompi_vars = ["OMPI_COMM_WORLD_RANK", "OMPI_COMM_WORLD_SIZE"] + pmi_vars = ["PMI_RANK", "PMI_SIZE"] + if all([var in os.environ for var in ompi_vars]) or all( + [var in os.environ for var in pmi_vars] + ): + return True + else: + return False + + +def is_using_distributed(): + if "WORLD_SIZE" in os.environ: + return int(os.environ["WORLD_SIZE"]) > 1 + if "SLURM_NTASKS" in os.environ: + return int(os.environ["SLURM_NTASKS"]) > 1 + return False + + +def world_info_from_env(): + local_rank = 0 + for v in ( + "LOCAL_RANK", + "MPI_LOCALRANKID", + "SLURM_LOCALID", + "OMPI_COMM_WORLD_LOCAL_RANK", + ): + if v in os.environ: + local_rank = int(os.environ[v]) + break + global_rank = 0 + for v in ("RANK", "PMI_RANK", "SLURM_PROCID", "OMPI_COMM_WORLD_RANK"): + if v in os.environ: + global_rank = int(os.environ[v]) + break + world_size = 1 + for v in ("WORLD_SIZE", "PMI_SIZE", "SLURM_NTASKS", "OMPI_COMM_WORLD_SIZE"): + if v in os.environ: + world_size = int(os.environ[v]) + break + + return local_rank, global_rank, world_size + + +def init_distributed_device(args): + # Distributed training = training on more than one GPU. + # Works in both single and multi-node scenarios. + args.distributed = False + args.world_size = 1 + args.rank = 0 # global rank + args.local_rank = 0 + if args.horovod: + assert hvd is not None, "Horovod is not installed" + hvd.init() + args.local_rank = int(hvd.local_rank()) + args.rank = hvd.rank() + args.world_size = hvd.size() + args.distributed = True + os.environ["LOCAL_RANK"] = str(args.local_rank) + os.environ["RANK"] = str(args.rank) + os.environ["WORLD_SIZE"] = str(args.world_size) + elif is_using_distributed(): + if "SLURM_PROCID" in os.environ: + # DDP via SLURM + args.local_rank, args.rank, args.world_size = world_info_from_env() + # SLURM var -> torch.distributed vars in case needed + os.environ["LOCAL_RANK"] = str(args.local_rank) + os.environ["RANK"] = str(args.rank) + os.environ["WORLD_SIZE"] = str(args.world_size) + torch.distributed.init_process_group( + backend=args.dist_backend, + init_method=args.dist_url, + world_size=args.world_size, + rank=args.rank, + ) + else: + # DDP via torchrun, torch.distributed.launch + args.local_rank, _, _ = world_info_from_env() + torch.distributed.init_process_group( + backend=args.dist_backend, init_method=args.dist_url + ) + args.world_size = torch.distributed.get_world_size() + args.rank = torch.distributed.get_rank() + args.distributed = True + else: + # needed to run on single gpu + torch.distributed.init_process_group( + backend=args.dist_backend, + init_method=args.dist_url, + world_size=1, + rank=0, + ) + + if torch.cuda.is_available(): + if args.distributed and not args.no_set_device_rank: + device = "cuda:%d" % args.local_rank + else: + device = "cuda:0" + torch.cuda.set_device(device) + else: + device = "cpu" + args.device = device + device = torch.device(device) + return device diff --git a/open_flamingo/open_flamingo/train/train.py b/open_flamingo/open_flamingo/train/train.py new file mode 100644 index 0000000000000000000000000000000000000000..3a110901df2105ab0b0f54d3d5e5ca1a62006ac8 --- /dev/null +++ b/open_flamingo/open_flamingo/train/train.py @@ -0,0 +1,484 @@ +""" Main training script """ + +import argparse +import glob +import os +import random + +import numpy as np +import torch +import wandb +from data import get_data +from distributed import init_distributed_device, world_info_from_env +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from train_utils import ( + train_one_epoch, + get_mp_policy_dtype, + save_checkpoint, +) +from transformers import ( + get_constant_schedule_with_warmup, + get_cosine_schedule_with_warmup, + get_linear_schedule_with_warmup, +) + +from torch.distributed.fsdp import ( + CPUOffload, + MixedPrecision, + ShardingStrategy, + BackwardPrefetch, +) +from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + checkpoint_wrapper, + CheckpointWrapper, + CheckpointImpl, + apply_activation_checkpointing, +) +from torch.distributed.fsdp._init_utils import _init_intra_and_inter_node_groups +from torch.distributed.distributed_c10d import _get_default_group +import functools + +from open_flamingo import create_model_and_transforms + + +def random_seed(seed=42, rank=0): + torch.manual_seed(seed + rank) + np.random.seed(seed + rank) + random.seed(seed + rank) + + +def main(): + parser = argparse.ArgumentParser() + # model configuration args + parser.add_argument("--vision_encoder_path", default="ViT-L-14", type=str) + parser.add_argument("--vision_encoder_pretrained", default="openai", type=str) + parser.add_argument("--lm_path", default="facebook/opt-1.3b", type=str) + parser.add_argument( + "--tokenizer_path", + default="facebook/opt-30b", + type=str, + help="path to tokenizer", + ) + parser.add_argument( + "--cross_attn_every_n_layers", + type=int, + default=1, + help="how often to add a cross-attention layer after each transformer layer", + ) + + # training args + parser.add_argument( + "--run_name", + type=str, + default="openflamingo3B", + help="used to name saving directory and wandb run", + ) + parser.add_argument( + "--resume_from_checkpoint", + type=str, + help="path to checkpoint to resume from, this should contain model, optimizer, and lr_scheduler states. if there exists a checkpoint in the dir named run_name, we will resume from that checkpoint by default", + default=None, + ) + parser.add_argument( + "--delete_previous_checkpoint", + action="store_true", + help="delete previous checkpoint when saving new checkpoint", + ) + parser.add_argument("--batch_size_mmc4", type=int, default=128) + parser.add_argument("--batch_size_laion", type=int, default=128) + parser.add_argument("--gradient_accumulation_steps", type=int, default=1) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--learning_rate", default=1e-4, type=float) + parser.add_argument( + "--lr_scheduler", + default="constant", + type=str, + help="constant, linear, or cosine", + ) + parser.add_argument("--loss_multiplier_mmc4", type=float, default=1.0) + parser.add_argument("--loss_multiplier_laion", type=float, default=1.0) + parser.add_argument("--warmup_steps", default=5000, type=int) + parser.add_argument("--weight_decay", default=0.1, type=float) + parser.add_argument( + "--precision", + choices=["amp_bf16", "amp_bfloat16", "bf16", "fp16", "fp32"], + default="fp32", + help="Floating point precision.", + ) + parser.add_argument( + "--gradient_checkpointing", + action="store_true", + help="whether to train with gradient/activation checkpointing", + ) + parser.add_argument( + "--num_epochs", + type=int, + default=1, + help="we define an 'epoch' as a fixed number of examples (train_num_samples_mmc4, train_num_samples_laion), not a pass through the entire dataset", + ) + parser.add_argument("--offline", action="store_true") + parser.add_argument( + "--freeze_lm_embeddings", + action="store_true", + help="if True, we freeze the LM embeddings during training. Otherwise, we train the and <|endofchunk|> embeddings.", + ) + parser.add_argument( + "--logging_steps", type=int, default=100, help="log loss every n steps" + ) + + # data args + parser.add_argument( + "--laion_shards", + type=str, + help="path to laion shards, this should be a glob pattern such as /path/to/shards/shard-{0000..0999}.tar", + ) + parser.add_argument( + "--mmc4_shards", + type=str, + help="path to c4 shards, this should be a glob pattern such as /path/to/shards/shard-{0000..0999}.tar", + ) + parser.add_argument("--workers", type=int, default=1) + parser.add_argument("--train_num_samples_mmc4", type=int, default=10000) + parser.add_argument("--train_num_samples_laion", type=int, default=10000) + parser.add_argument("--dataset_resampled", action="store_true") + parser.add_argument( + "--mmc4_textsim_threshold", + default=30, + type=float, + help="threshold for filtering images in mmc4 based on image-text similarity", + ) + parser.add_argument( + "--mmc4_max_num_images", + default=6, + type=int, + help="max number of images per sequence in mmc4 / chatgpt", + ) + parser.add_argument( + "--mmc4_min_num_images", + default=1, + type=int, + help="min number of images per sequence in mmc4 / chatgpt", + ) + + # distributed training args + parser.add_argument( + "--dist-url", + default="env://", + type=str, + help="url used to set up distributed training", + ) + parser.add_argument( + "--dist-backend", default="nccl", type=str, help="distributed backend" + ) + parser.add_argument( + "--horovod", + default=False, + action="store_true", + help="Use horovod for distributed training.", + ) + parser.add_argument( + "--no-set-device-rank", + default=False, + action="store_true", + help="Don't set device index from local rank (when CUDA_VISIBLE_DEVICES restricted to one per proc).", + ) + parser.add_argument( + "--fsdp", + default=False, + action="store_true", + help="Use FullyShardedDataParallel for distributed training.", + ) + parser.add_argument( + "--fsdp_use_orig_params", + default=False, + action="store_true", + help="Passed into the FSDP constructor. Enables param_groups and gradient masking for weight_decay. Does not work with OPT.", + ) + parser.add_argument( + "--fsdp_sharding_strategy", default="full", type=str, choices=["full", "hybrid"] + ) + + # wandb args + parser.add_argument("--report_to_wandb", default=False, action="store_true") + parser.add_argument( + "--wandb_project", + type=str, + ) + parser.add_argument( + "--wandb_entity", + type=str, + ) + parser.add_argument( + "--save_checkpoints_to_wandb", + default=False, + action="store_true", + help="save checkpoints to wandb", + ) + + args = parser.parse_args() + + # Validate args + if args.laion_shards.startswith("s3"): + args.laion_shards = f"pipe:aws s3 cp {args.laion_shards} -" + + if args.mmc4_shards.startswith("s3"): + args.mmc4_shards = f"pipe:aws s3 cp {args.mmc4_shards} -" + + if args.save_checkpoints_to_wandb and not args.report_to_wandb: + raise ValueError("save_checkpoints_to_wandb requires report_to_wandb") + + if args.fsdp and not args.fsdp_use_orig_params: + print( + "Warning: FSDP is running without fsdp_use_orig_params flag. " + + "This is not recommended because it means we will use uniform weight decay" + + " and train all embeddings, not just the newly added ones. " + + "Note: OPT models are not compatible with fsdp_use_orig_params flag." + ) + + if args.fsdp and args.fsdp_sharding_strategy == "hybrid": + print( + "Warning: As of torch=2.0.1, the FSDP logic for optim_state_dict() is broken for hybrid sharding." + + "To make this method work, we need to modify torch.distributed.fsdp._optim_utils.py" + + "Copy and paste the code from the _optim_utils.py in this repo into the torch file." + + "The main issue was the missing group kwarg on line 1596 in _all_gather_optim_state." + ) + + assert (args.train_num_samples_laion // args.batch_size_laion) == ( + args.train_num_samples_mmc4 // args.batch_size_mmc4 + ), "number of samples per epoch must be equal for mmc4 and laion" + + # Set up distributed training + if args.offline: + os.environ["WANDB_MODE"] = "offline" + os.environ["TRANSFORMERS_OFFLINE"] = "1" + args.local_rank, args.rank, args.world_size = world_info_from_env() + device_id = init_distributed_device(args) + random_seed(args.seed) + + # Initialize model + model, image_processor, tokenizer = create_model_and_transforms( + args.vision_encoder_path, + args.vision_encoder_pretrained, + args.lm_path, + args.tokenizer_path if args.tokenizer_path else args.lm_path, + cross_attn_every_n_layers=args.cross_attn_every_n_layers, + use_local_files=args.offline, + gradient_checkpointing=args.gradient_checkpointing, + freeze_lm_embeddings=args.freeze_lm_embeddings, + ) + random_seed(args.seed, args.rank) + + # Initialize logging + print(f"Start running training on rank {args.rank}.") + if args.rank == 0 and args.report_to_wandb: + wandb.init( + project=args.wandb_project, + entity=args.wandb_entity, + name=args.run_name, + config=vars(args), + ) + + # Load model checkpoint on CPU + if os.path.exists(f"{args.run_name}") and args.resume_from_checkpoint is None: + # if args do not specify a checkpoint to resume from, check if checkpoints exist for this run + # and automatically resume from the latest checkpoint + checkpoint_list = glob.glob(f"{args.run_name}/checkpoint_*.pt") + if len(checkpoint_list) == 0: + print(f"Found no checkpoints for run {args.run_name}.") + else: + args.resume_from_checkpoint = sorted( + checkpoint_list, key=lambda x: int(x.split("_")[-1].split(".")[0]) + )[-1] + print( + f"Found checkpoint {args.resume_from_checkpoint} for run {args.run_name}." + ) + + resume_from_epoch = 0 + if args.resume_from_checkpoint is not None: + if args.rank == 0: + print(f"Loading checkpoint from {args.resume_from_checkpoint}") + checkpoint = torch.load(args.resume_from_checkpoint, map_location="cpu") + msd = checkpoint["model_state_dict"] + msd = {k.replace("module.", ""): v for k, v in msd.items()} + resume_from_epoch = checkpoint["epoch"] + 1 + + # for fsdp, only one rank needs to load the state dict + if not args.fsdp or args.rank == 0: + model.load_state_dict(msd, False) + + # Initialize FSDP / DDP, and ensure the model is on GPU + print(f"Initializing distributed training with {args.world_size} GPUs.") + if args.fsdp: + print( + f"Before FSDP parameter num: {sum(p.numel() for p in model.parameters())} on rank {args.rank}" + ) + + # init MixedPrecision + if args.precision != "fp32": + cast_dtype = get_mp_policy_dtype(args.precision) + mp_policy = MixedPrecision( + param_dtype=torch.float32, + reduce_dtype=cast_dtype, # gradient communication + buffer_dtype=cast_dtype, + ) + else: + mp_policy = None + + # init process groups + if args.fsdp_sharding_strategy == "hybrid": + intra_node_group, inter_node_group = _init_intra_and_inter_node_groups( + _get_default_group() + ) + args.my_group = intra_node_group # for optimizer saving + process_group = (intra_node_group, inter_node_group) # for FSDP init + else: + args.my_group = None # for optimizer saving + process_group = None # for FSDP init + + # init FSDP + wrapper_kwargs = dict( + process_group=process_group, + cpu_offload=CPUOffload(offload_params=False), + device_id=device_id, + sync_module_states=True, # broadcast loaded ckpt from rank 0 -> all ranks + sharding_strategy=ShardingStrategy.FULL_SHARD + if args.fsdp_sharding_strategy == "full" + else ShardingStrategy.HYBRID_SHARD, + use_orig_params=args.fsdp_use_orig_params, + mixed_precision=mp_policy, + forward_prefetch=True, + backward_prefetch=BackwardPrefetch.BACKWARD_PRE, + limit_all_gathers=True, + ) + model.wrap_fsdp(wrapper_kwargs, device_id) + ddp_model = model + + print( + f"After FSDP parameter num: {sum(p.numel() for p in model.parameters())} on rank {args.rank}" + ) + print( + f"After FSDP {torch.cuda.memory_allocated()/1024**3:.3} GB on rank {args.rank}" + ) + + else: + model = model.to(device_id) + ddp_model = DDP(model, device_ids=[device_id]) + + # Initialize gradient checkpointing + if args.gradient_checkpointing: + non_reentrant_wrapper = functools.partial( + checkpoint_wrapper, + offload_to_cpu=True, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + ) + apply_activation_checkpointing( + ddp_model, + checkpoint_wrapper_fn=non_reentrant_wrapper, + check_fn=lambda m: getattr(m, "_use_gradient_checkpointing", False) + and not isinstance(m, FSDP) + and not isinstance(m, CheckpointWrapper), + ) + + # Initialize optimizer + params_to_optimize = ddp_model.named_parameters() + params_to_optimize = list( + filter( + lambda x: x[1].requires_grad + and not getattr(x[1], "exclude_from_optimizer", False), + params_to_optimize, + ) + ) + if not args.fsdp or args.fsdp_use_orig_params: + # apply weight decay only to params in the xattn layers + def get_grouped_params(model): + params_with_wd, params_without_wd = [], [] + for n, p in params_to_optimize: + if "gated_cross_attn" in n: + params_with_wd.append(p) + else: + params_without_wd.append(p) + return [ + {"params": params_with_wd, "weight_decay": args.weight_decay}, + {"params": params_without_wd, "weight_decay": 0.0}, + ] + + optimizer = torch.optim.AdamW( + get_grouped_params(params_to_optimize), lr=args.learning_rate + ) + else: + # unclear if we should be using no weight decay or small weight decay for all parameters + optimizer = torch.optim.AdamW( + (p for _, p in params_to_optimize), + lr=args.learning_rate, + weight_decay=args.weight_decay, + ) + + # load optimizer checkpoint + if args.resume_from_checkpoint is not None: + osd = checkpoint["optimizer_state_dict"] + if args.fsdp: + osd = FSDP.optim_state_dict_to_load(osd, ddp_model, optimizer) + optimizer.load_state_dict(osd) + + # Initialize data loaders + laion_dataset = get_data(args, image_processor, tokenizer, "image_text") + mmc4_dataset = get_data(args, image_processor, tokenizer, "mmc4") + total_training_steps = ( + (args.train_num_samples_mmc4) // (args.batch_size_mmc4 * args.world_size) + ) * args.num_epochs + + if args.rank == 0: + print(f"Total training steps: {total_training_steps}") + + # Initialize lr scheduler + if args.lr_scheduler == "linear": + lr_scheduler = get_linear_schedule_with_warmup( + optimizer, + num_warmup_steps=args.warmup_steps, + num_training_steps=total_training_steps, + ) + elif args.lr_scheduler == "cosine": + lr_scheduler = get_cosine_schedule_with_warmup( + optimizer, + num_warmup_steps=args.warmup_steps, + num_training_steps=total_training_steps, + ) + else: + lr_scheduler = get_constant_schedule_with_warmup( + optimizer, num_warmup_steps=args.warmup_steps + ) + + # load lr scheduler checkpoint + if args.resume_from_checkpoint is not None: + lr_scheduler.load_state_dict(checkpoint["lr_scheduler_state_dict"]) + + # Start training! + ddp_model.train() + + for epoch in range(resume_from_epoch, args.num_epochs): + laion_dataset.set_epoch(epoch) + laion_loader = laion_dataset.dataloader + mmc4_dataset.set_epoch(epoch) + mmc4_loader = mmc4_dataset.dataloader + + train_one_epoch( + args=args, + model=ddp_model, + epoch=epoch, + tokenizer=tokenizer, + optimizer=optimizer, + lr_scheduler=lr_scheduler, + laion_loader=laion_loader, + mmc4_loader=mmc4_loader, + device_id=device_id, + wandb=wandb, + ) + save_checkpoint(ddp_model, optimizer, lr_scheduler, epoch, args) + + # save final checkpoint + save_checkpoint(ddp_model, optimizer, lr_scheduler, epoch, args) + + +if __name__ == "__main__": + main() diff --git a/open_flamingo/open_flamingo/train/train_utils.py b/open_flamingo/open_flamingo/train/train_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..08c3fcc244909b489ee953bca7d889264ac39ce7 --- /dev/null +++ b/open_flamingo/open_flamingo/train/train_utils.py @@ -0,0 +1,377 @@ +import time +from contextlib import suppress +import torch +from tqdm import tqdm +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.distributed.fsdp import ( + FullStateDictConfig, + StateDictType, +) +from torch.distributed.fsdp.api import FullOptimStateDictConfig +import os +import wandb +from einops import rearrange + + +def get_cast_dtype(precision: str): + cast_dtype = None + if precision == "bf16": + cast_dtype = torch.bfloat16 + elif precision == "fp16": + cast_dtype = torch.float16 + return cast_dtype + + +def get_mp_policy_dtype(precision: str): + if "bfloat16" in precision or "bf16" in precision: + return torch.bfloat16 + elif precision == "fp16": + return torch.float16 + else: + return torch.float32 + + +def get_autocast(precision, cache_enabled=True): + if precision == "amp": + return torch.cuda.amp.autocast(cache_enabled=cache_enabled) + elif precision == "amp_bfloat16" or precision == "amp_bf16": + # amp_bfloat16 is more stable than amp float16 for clip training + return lambda: torch.cuda.amp.autocast( + dtype=torch.bfloat16, cache_enabled=cache_enabled + ) + else: + return suppress + + +def train_one_epoch( + args, + model, + epoch, + laion_loader, + mmc4_loader, + tokenizer, + optimizer, + lr_scheduler, + device_id, + wandb, +): + # setup loaders + num_batches_per_epoch_laion = laion_loader.num_batches + num_batches_per_epoch_mmc4 = mmc4_loader.num_batches + assert ( + num_batches_per_epoch_laion == num_batches_per_epoch_mmc4 + ), "Number of batches in laion and mmc4 datasets must be the same" + num_batches_per_epoch = num_batches_per_epoch_mmc4 + total_training_steps = num_batches_per_epoch * args.num_epochs + + autocast = get_autocast( + args.precision, cache_enabled=(not args.fsdp) + ) # if fsdp, disable cache to save memory + cast_dtype = get_cast_dtype(args.precision) + + # setup model + media_token_id = tokenizer("", add_special_tokens=False)["input_ids"][-1] + endofchunk_token_id = tokenizer("<|endofchunk|>", add_special_tokens=False)[ + "input_ids" + ][-1] + model.train() + + # setup logging + step_time_m = AverageMeter() + data_time_m = AverageMeter() + end = time.time() + + # loop through dataloader + for num_steps, (batch_laion, batch_mmc4) in tqdm( + enumerate(zip(laion_loader, mmc4_loader)), + disable=args.rank != 0, + total=total_training_steps, + initial=(epoch * num_batches_per_epoch), + ): + data_time_m.update(time.time() - end) + global_step = num_steps + epoch * num_batches_per_epoch + + #### LAION FORWARD PASS #### + images = batch_laion[0].to(device_id, dtype=cast_dtype, non_blocking=True) + images = rearrange(images, "(b t f) c h w -> b t f c h w", t=1, f=1) + input_ids = batch_laion[1][0].to(device_id, dtype=cast_dtype, non_blocking=True) + attention_mask = batch_laion[1][1].to( + device_id, dtype=cast_dtype, non_blocking=True + ) + + # set up labels; language model is expected to handle shifting + labels = input_ids.clone() + labels[labels == tokenizer.pad_token_id] = -100 + labels[:, 0] = -100 + labels[labels == media_token_id] = -100 + labels = labels.to(device_id) + + # gradient accumulation w/ fsdp cpu offloading requires a no_sync context manager + with autocast(): + loss_laion = model( + vision_x=images, + lang_x=input_ids, + attention_mask=attention_mask, + labels=labels, + )[0] + + divided_loss_laion = loss_laion / args.gradient_accumulation_steps + (divided_loss_laion * args.loss_multiplier_laion).backward() + + #### MMC4 FORWARD PASS #### + images = batch_mmc4[0].to(device_id, dtype=cast_dtype, non_blocking=True) + images = rearrange(images, "b (t f) c h w -> b t f c h w", f=1) + input_ids = torch.stack([x[0] for x in batch_mmc4[1]]).squeeze(1) + attention_mask = torch.stack([x[1] for x in batch_mmc4[1]]).squeeze(1) + + # set up labels; language model is expected to handle shifting + labels = input_ids.clone() + labels[labels == tokenizer.pad_token_id] = -100 + labels[:, 0] = -100 + for i in range(labels.shape[0]): + # remove loss for any token before the first token + label_idx = 0 + while ( + label_idx < labels.shape[1] and labels[i][label_idx] != media_token_id + ): + labels[i][label_idx] = -100 + label_idx += 1 + + # get index of all endofchunk tokens in the sequence + endofchunk_idxs = torch.where(labels[i] == endofchunk_token_id)[0] + for endofchunk_idx in endofchunk_idxs: + token_idx = endofchunk_idx + 1 + while ( + token_idx < labels.shape[1] + and labels[i][token_idx] != media_token_id + ): + labels[i][token_idx] = -100 + token_idx += 1 + + labels[labels == media_token_id] = -100 + labels = labels.to(device_id) + + # gradient accumulation w/ fsdp cpu offloading requires a no_sync context manager + with autocast(): + loss_mmc4 = model( + vision_x=images, + lang_x=input_ids, + attention_mask=attention_mask, + labels=labels, + )[0] + + # if loss is nan, skip this batch + # this hack of skipping the batch is not FSDP-compatible + if torch.isnan(loss_mmc4): + print("loss is nan, skipping this batch") + print("input_ids: ", tokenizer.batch_decode(input_ids)) + print("labels: ", labels) + print("images: ", images) + optimizer.zero_grad(set_to_none=True) + continue + + divided_loss_mmc4 = loss_mmc4 / args.gradient_accumulation_steps + (divided_loss_mmc4 * args.loss_multiplier_mmc4).backward() + + if (not args.freeze_lm_embeddings) and ( + not args.fsdp or args.fsdp_use_orig_params + ): + # Mask gradients for input embeddings s.t. we only update the added tokens and <|endofchunk|> + if args.fsdp: + embed_grad = model.lang_encoder.get_input_embeddings().weight.grad + else: + embed_grad = ( + model.module.lang_encoder.get_input_embeddings().weight.grad + ) + zero_mask = torch.zeros_like(embed_grad) + zero_mask[media_token_id] = torch.ones_like(zero_mask[media_token_id]) + zero_mask[endofchunk_token_id] = torch.ones_like( + zero_mask[endofchunk_token_id] + ) + if args.fsdp: + model.lang_encoder.get_input_embeddings().weight.grad = ( + embed_grad * zero_mask + ) + else: + model.module.lang_encoder.get_input_embeddings().weight.grad = ( + embed_grad * zero_mask + ) + + # clip gradient norm + if args.fsdp: + """ + The way we clip gradients with FSDP is different than the non-FSDP case, + because during FSDP, gradient norms are computed over certain submodules, + rather than the entire model. + At least for OPT-125M, this didn't seem to make a difference in performance. + """ + model.clip_grad_norm_(1.0) + else: + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + + # step optimizer and log + if (((num_steps + 1) % args.gradient_accumulation_steps) == 0) or ( + num_steps == num_batches_per_epoch - 1 + ): + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad(set_to_none=True) + + # step time and reset end outside of rank 0 + step_time_m.update(time.time() - end) + end = time.time() + + # rank 0 logging + if args.rank == 0 and args.report_to_wandb: + laion_samples_per_second = ( + args.gradient_accumulation_steps + * args.batch_size_laion + * args.world_size + / step_time_m.val + ) + laion_samples_per_second_per_gpu = ( + args.gradient_accumulation_steps + * args.batch_size_laion + / step_time_m.val + ) + c4_samples_per_second = ( + args.gradient_accumulation_steps + * args.batch_size_mmc4 + * args.world_size + / step_time_m.val + ) + c4_samples_per_second_per_gpu = ( + args.gradient_accumulation_steps + * args.batch_size_mmc4 + / step_time_m.val + ) + wandb.log( + { + "data_time": data_time_m.avg, + "step_time": step_time_m.avg, + "laion_samples_per_second": laion_samples_per_second, + "laion_samples_per_second_per_gpu": laion_samples_per_second_per_gpu, + "c4_samples_per_second": c4_samples_per_second, + "c4_samples_per_second_per_gpu": c4_samples_per_second_per_gpu, + "lr": optimizer.param_groups[0]["lr"], + }, + commit=False, + ) + step_time_m.reset() + data_time_m.reset() + + wandb.log( + { + "loss_laion": loss_laion.item(), + "global_step": global_step, + }, + commit=False, + ) + wandb.log( + {"loss_mmc4": loss_mmc4.item(), "global_step": global_step}, + commit=True, + ) + + # Log loss to console + if ((num_steps + 1) % args.logging_steps == 0) and args.rank == 0: + print( + f"Step {num_steps+1}/{num_batches_per_epoch} of epoch {epoch+1}/{args.num_epochs} complete. Loss LAION: {loss_laion.item():.3f} // Loss MMC4: {loss_mmc4.item():.3f}" + ) + + +class AverageMeter(object): + """Computes and stores the average and current value""" + + def __init__(self): + self.reset() + + def reset(self): + self.val = 0 + self.avg = 0 + self.sum = 0 + self.count = 0 + + def update(self, val, n=1): + self.val = val + self.sum += val * n + self.count += n + self.avg = self.sum / self.count + + +def filter_state_dict_to_trainable(model, state_dict): + """ + Remove non-trainable parameters from model state dict. + Exception: Embeddings will not be removed, even if frozen. + This is because we need the new <|endofchunk|> tokens to + be consistent across initializations. + """ + for ( + name, + p, + ) in model.named_parameters(): # won't work for fsdp + use_orig_params=False + if "fsdp" in name: + continue + if "embed" in name or isinstance(p, torch.nn.Embedding): + continue + if not p.requires_grad: + name = name.replace("._checkpoint_wrapped_module", "") + if name in state_dict: + del state_dict[name] + else: + print(f"WARNING: filtering but {name} not in state_dict") + + # also remove the keys in state_dict generated from + # lang_encoder.old_decoder_blocks and lang_encoder.gated_cross_attn_layers + # because these are already saved in lang_encoder.model... + to_delete = [ + n + for n in state_dict.keys() + if ("lang_encoder.old_decoder_blocks" in n) + or ("lang_encoder.gated_cross_attn_layers" in n) + or ("vision_encoder" in n) + ] + for name in to_delete: + del state_dict[name] + return state_dict + + +def save_checkpoint(model, optimizer, lr_scheduler, epoch, args): + """ + Save training checkpoint with model, optimizer, and lr_scheduler state. + """ + if args.fsdp: + FSDP.set_state_dict_type( + model, + StateDictType.FULL_STATE_DICT, + FullStateDictConfig(rank0_only=True, offload_to_cpu=True), + FullOptimStateDictConfig(rank0_only=True), + ) + model_state = model.state_dict() + optim_state = FSDP.optim_state_dict(model, optimizer, group=args.my_group) + + else: + model_state = model.state_dict() + optim_state = optimizer.state_dict() + + if args.rank == 0: + if not (args.fsdp and not args.fsdp_use_orig_params): + model_state = filter_state_dict_to_trainable(model, model_state) + + if not os.path.exists(args.run_name): + os.makedirs(args.run_name) + + checkpoint_dict = { + "epoch": epoch, + "model_state_dict": model_state, + "optimizer_state_dict": optim_state, + "lr_scheduler_state_dict": lr_scheduler.state_dict(), + } + + print(f"Saving checkpoint to {args.run_name}/checkpoint_{epoch}.pt") + torch.save(checkpoint_dict, f"{args.run_name}/checkpoint_{epoch}.pt") + if args.report_to_wandb and args.save_checkpoints_to_wandb: + wandb.save(f"{args.run_name}/checkpoint_{epoch}.pt") + + if args.delete_previous_checkpoint: + if epoch > 0: + os.remove(f"{args.run_name}/checkpoint_{epoch-1}.pt") diff --git a/open_flamingo/requirements-dev.txt b/open_flamingo/requirements-dev.txt new file mode 100644 index 0000000000000000000000000000000000000000..429f646f468bad4cc842cff203810b985d55d41d --- /dev/null +++ b/open_flamingo/requirements-dev.txt @@ -0,0 +1,5 @@ +black +mypy +pylint +pytest +requests \ No newline at end of file diff --git a/open_flamingo/requirements.txt b/open_flamingo/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..0dca08220993d964e500db543aaec3b21f20d4eb --- /dev/null +++ b/open_flamingo/requirements.txt @@ -0,0 +1,16 @@ +einops +einops-exts +transformers==4.28 +torch==2.0.1 +torchvision +pillow +more-itertools +datasets +braceexpand +webdataset +wandb +nltk +scipy +inflection +sentencepiece +open_clip_torch diff --git a/open_flamingo/setup.py b/open_flamingo/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..8510a49f8dd9a4f0379304aa835277a7addfd9b6 --- /dev/null +++ b/open_flamingo/setup.py @@ -0,0 +1,57 @@ +from pathlib import Path + +from setuptools import find_packages, setup + +if __name__ == "__main__": + with Path(Path(__file__).parent, "README.md").open(encoding="utf-8") as file: + long_description = file.read() + + # TODO: This is a hack to get around the fact that we can't read the requirements.txt file, we should fix this. + # def _read_reqs(relpath): + # fullpath = os.path.join(Path(__file__).parent, relpath) + # with open(fullpath) as f: + # return [ + # s.strip() + # for s in f.readlines() + # if (s.strip() and not s.startswith("#")) + # ] + + REQUIREMENTS = [ + "einops", + "einops-exts", + "transformers", + "torch", + "torchvision", + "pillow", + "more-itertools", + "datasets", + "braceexpand", + "webdataset", + "wandb", + "nltk", + "scipy", + "inflection", + "sentencepiece", + "open_clip_torch", + ] + + setup( + name="open_flamingo", + packages=find_packages(), + include_package_data=True, + version="0.0.2", + license="MIT", + description="An open-source framework for training large multimodal models", + long_description=long_description, + long_description_content_type="text/markdown", + data_files=[(".", ["README.md"])], + keywords=["machine learning"], + install_requires=REQUIREMENTS, + classifiers=[ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3.9", + ], + ) diff --git a/pandas.jpg b/pandas.jpg new file mode 100644 index 0000000000000000000000000000000000000000..0c6551ae85f719a4df12aff75846ad3fef0b8afe Binary files /dev/null and b/pandas.jpg differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..7168c7477d0d4e91bddb70ba20a0901042d6b7bd --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +gradio +torch +pillow \ No newline at end of file diff --git a/shiba-inu-dog-in-the-snow.jpg b/shiba-inu-dog-in-the-snow.jpg new file mode 100644 index 0000000000000000000000000000000000000000..08652ab1e88383d47f5e9b5ee043fc85fe22570c Binary files /dev/null and b/shiba-inu-dog-in-the-snow.jpg differ