From 0d8aa6e6efcc9bebc4b161c36648ae4cd1e0c915 Mon Sep 17 00:00:00 2001 From: hiyouga Date: Tue, 29 Oct 2024 09:07:46 +0000 Subject: [PATCH] use pre-commit Former-commit-id: 21db8ed2f4a0eba203754a92ce0741538e8ee709 --- .github/workflows/publish.yml | 6 +- assets/benchmark.svg | 1630 ++++++++--------- data/alpaca_en_demo.json | 2 +- data/alpaca_zh_demo.json | 2 +- data/belle_multiturn/belle_multiturn.py | 6 +- data/c4_demo.json | 2 +- data/dataset_info.json | 2 +- data/dpo_en_demo.json | 2 +- data/dpo_zh_demo.json | 2 +- data/glaive_toolcall_en_demo.json | 2 +- data/glaive_toolcall_zh_demo.json | 2 +- data/hh_rlhf_en/hh_rlhf_en.py | 6 +- data/identity.json | 2 +- data/kto_en_demo.json | 2 +- data/mllm_demo.json | 2 +- data/mllm_video_demo.json | 2 +- data/ultra_chat/ultra_chat.py | 6 +- data/wiki_demo.txt | 2 +- evaluation/ceval/mapping.json | 2 +- evaluation/cmmlu/mapping.json | 2 +- evaluation/mmlu/mapping.json | 2 +- evaluation/mmlu/mmlu.py | 3 +- examples/deepspeed/ds_z0_config.json | 2 +- examples/deepspeed/ds_z2_config.json | 2 +- examples/deepspeed/ds_z2_offload_config.json | 2 +- examples/deepspeed/ds_z3_config.json | 2 +- examples/deepspeed/ds_z3_offload_config.json | 2 +- scripts/cal_flops.py | 1 - scripts/cal_lr.py | 3 +- scripts/cal_mfu.py | 9 +- scripts/cal_ppl.py | 7 +- scripts/length_cdf.py | 3 +- scripts/llama_pro.py | 21 +- scripts/llamafy_baichuan2.py | 9 +- scripts/llamafy_qwen.py | 11 +- scripts/loftq_init.py | 11 +- scripts/pissa_init.py | 11 +- scripts/test_toolcall.py | 1 - setup.py | 8 +- src/api.py | 2 +- src/llamafactory/api/app.py | 2 +- src/llamafactory/api/chat.py | 10 +- src/llamafactory/chat/chat_model.py | 2 +- src/llamafactory/chat/vllm_engine.py | 4 +- src/llamafactory/cli.py | 6 +- src/llamafactory/data/aligner.py | 6 +- src/llamafactory/data/collator.py | 6 +- src/llamafactory/data/data_utils.py | 2 +- src/llamafactory/data/formatter.py | 10 +- src/llamafactory/data/loader.py | 14 +- src/llamafactory/data/mm_plugin.py | 26 +- src/llamafactory/data/parser.py | 6 +- src/llamafactory/data/processors/pairwise.py | 4 +- .../data/processors/supervised.py | 4 +- src/llamafactory/data/template.py | 12 +- src/llamafactory/data/tool_utils.py | 2 +- src/llamafactory/eval/evaluator.py | 4 +- src/llamafactory/eval/template.py | 2 +- src/llamafactory/extras/env.py | 2 +- src/llamafactory/extras/logging.py | 2 +- src/llamafactory/extras/ploting.py | 4 +- src/llamafactory/hparams/parser.py | 6 +- src/llamafactory/model/adapter.py | 8 +- src/llamafactory/model/loader.py | 6 +- .../model/model_utils/attention.py | 2 +- .../model/model_utils/checkpointing.py | 2 +- .../model/model_utils/embedding.py | 2 +- src/llamafactory/model/model_utils/misc.py | 4 +- .../model/model_utils/quantization.py | 10 +- src/llamafactory/model/model_utils/rope.py | 8 +- .../model/model_utils/valuehead.py | 2 +- src/llamafactory/model/model_utils/visual.py | 2 +- src/llamafactory/train/callbacks.py | 10 +- src/llamafactory/train/dpo/trainer.py | 22 +- src/llamafactory/train/kto/trainer.py | 10 +- src/llamafactory/train/ppo/ppo_utils.py | 4 +- src/llamafactory/train/ppo/trainer.py | 16 +- src/llamafactory/train/trainer_utils.py | 12 +- src/llamafactory/train/tuner.py | 14 +- src/llamafactory/webui/common.py | 8 +- src/llamafactory/webui/components/data.py | 6 +- src/llamafactory/webui/engine.py | 6 +- src/llamafactory/webui/manager.py | 2 +- src/llamafactory/webui/runner.py | 4 +- src/llamafactory/webui/utils.py | 18 +- tests/e2e/test_train.py | 2 +- 86 files changed, 1048 insertions(+), 1064 deletions(-) diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 15c7153e..7c5d317f 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -26,15 +26,15 @@ jobs: uses: actions/setup-python@v5 with: python-version: "3.8" - + - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install build - + - name: Build package run: | python -m build - + - name: Publish package uses: pypa/gh-action-pypi-publish@release/v1 diff --git a/assets/benchmark.svg b/assets/benchmark.svg index 60f0aa4d..e2b1db48 100644 --- a/assets/benchmark.svg +++ b/assets/benchmark.svg @@ -21,19 +21,19 @@ - - @@ -41,8 +41,8 @@ z - @@ -53,243 +53,243 @@ L 0 3.5 - - - - - - - - - - @@ -320,97 +320,97 @@ z - - - - @@ -438,190 +438,190 @@ z - - - - - - - - - @@ -645,145 +645,145 @@ z - - - - - - - - - - - @@ -797,57 +797,57 @@ z - - - @@ -870,34 +870,34 @@ z - @@ -912,36 +912,36 @@ z - @@ -955,23 +955,23 @@ z - @@ -985,115 +985,115 @@ z - - - - - - - @@ -1122,24 +1122,24 @@ z - - @@ -1165,10 +1165,10 @@ z - @@ -1176,17 +1176,17 @@ z - diff --git a/data/alpaca_en_demo.json b/data/alpaca_en_demo.json index ec76a491..744fd0e8 100644 --- a/data/alpaca_en_demo.json +++ b/data/alpaca_en_demo.json @@ -4999,4 +4999,4 @@ "input": "Time waits for no one.", "output": "No one can stop time from moving forward." } -] \ No newline at end of file +] diff --git a/data/alpaca_zh_demo.json b/data/alpaca_zh_demo.json index 0f1d9c38..4501a26f 100644 --- a/data/alpaca_zh_demo.json +++ b/data/alpaca_zh_demo.json @@ -4999,4 +4999,4 @@ "input": "", "output": "安第斯山脉位于南美洲,横跨七个国家,包括委内瑞拉,哥伦比亚,厄瓜多尔,秘鲁,玻利维亚,智利和阿根廷。安第斯山脉是世界上最长的山脉之一,全长约7,000千米(4,350英里),其山脉沿着南美洲西海岸蜿蜒延伸,平均海拔约为4,000米(13,000英尺)。在其南部,安第斯山脉宽度达到700千米(430英里),在其北部宽度约为500千米(310英里)。" } -] \ No newline at end of file +] diff --git a/data/belle_multiturn/belle_multiturn.py b/data/belle_multiturn/belle_multiturn.py index 5c3fce26..7b2f5449 100644 --- a/data/belle_multiturn/belle_multiturn.py +++ b/data/belle_multiturn/belle_multiturn.py @@ -17,9 +17,9 @@ _CITATION = """\ } """ -_HOMEPAGE = "{}/datasets/BelleGroup/multiturn_chat_0.8M".format(_HF_ENDPOINT) +_HOMEPAGE = f"{_HF_ENDPOINT}/datasets/BelleGroup/multiturn_chat_0.8M" _LICENSE = "gpl-3.0" -_URL = "{}/datasets/BelleGroup/multiturn_chat_0.8M/resolve/main/multiturn_chat_0.8M.json".format(_HF_ENDPOINT) +_URL = f"{_HF_ENDPOINT}/datasets/BelleGroup/multiturn_chat_0.8M/resolve/main/multiturn_chat_0.8M.json" class BelleMultiturn(datasets.GeneratorBasedBuilder): @@ -38,7 +38,7 @@ class BelleMultiturn(datasets.GeneratorBasedBuilder): return [datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"filepath": file_path})] def _generate_examples(self, filepath: str): - with open(filepath, "r", encoding="utf-8") as f: + with open(filepath, encoding="utf-8") as f: for key, row in enumerate(f): data = json.loads(row) conversations = [] diff --git a/data/c4_demo.json b/data/c4_demo.json index 9e364d10..0c286252 100644 --- a/data/c4_demo.json +++ b/data/c4_demo.json @@ -899,4 +899,4 @@ { "text": "Having a DisplayPort with you at your house will always keep you entertained if you love gaming and live to stream. The cables fit perfectly in a monitor, projector, laptop or tablet. There are many products in the market you can choose from, but you have to do proper research to avoid purchasing a wrong product.\nThis is the perfect cable for your laptop or desktop that is equipped with a display port. You can also use it to enjoy your movies where you can also expand your laptop for better view or when you are presenting at school. It provides you with quality and high-definition audio and videos from your laptop.\nThis cable is gold plated, and this helps to resist corrosion or resist any damage and enhance durability. This kind of plating also ensures a perfect signal transmission. This display port connector provides a secure connection where it has a release button that is always lowered before unplugging. The display port is also portable where you can carry it anywhere with you.\nThis mini display port cable can give you quality transmission of videos and audios. You can connect it to your computer or tablet to get HD videos. Has gold plated connectors, copper conductors, and foil-and-braid shielding where all these provide enough energy and convenient connection.\nThis cable measures a maximum of 10 feet and gives an easy time when connecting it to your laptop. The cable has a sleek design that gives you an easy time to carry and store the cable. It is secure and reliable where it will provide you with a good connection when you need it.\nIf you are looking for a perfect cable for video streaming and gaming, this is the perfect fit. It has a construction design that prevents the cable from cracking or any damage. It contains gold-plated connectors and multiple shielding where this prevents any damage and enhance the durability of the cable.\nThe cable provides you with free non-interfered data transmission from any time and position. Provides a secure and reliable connection where you only plug and play without struggling. You can directly connect the display port that is equipped to your desktop for high definition videos and clear audios.\nThis is a convenient cable that connects a display port cable directly to a projector or HD monitor with display port unit. This cable is portable and mobile where you can use it anywhere. It features gold-plated connectors that with copper connectors and braid shielding where they all combine to provide powerful cable performance reliable connections.\nIt transmits high definition videos and clear music from your computer to a monitor for gaming or video streaming. It provides a secure connection where it has a button that is always lowered before unplugging. This cable is 10 foot long, and this gives you an easy time when using it from any position.\nThis cable has gold-plated connectors that resist corrosion and any form of damage. The gold connectors also enhance reliable and increased connectivity. It features inner braided foil that reduces interference and increases video and audio quality. The 6 feet cable connects a display port enabled computer to an HD monitor or projector with DP port unit for audio and video streaming.\nThe cable gives you the best and quality video resolution you need. The DP has a latch that provides a secure and reliable connection with the port where the latch must be pressed down before unplugging the connector. This is perfect for extended display or mirrored displays.\nThe cable supports resolutions of up to 3840 by 2160 and high-definition videos. This display port provides you with a secure and reliable connection any time you need it. It has pure copper conductors and triple metal shielding that enhance a perfect performance.\nThis cable transmits both high definition video from your computer or tablet to an HD display. It has gold-plated and copper conductors that protect the cable from damage and improve its performance.\nHas foil and braid shielding that helps in reducing electromagnetic interference.\nIt has an ergonomic design where it has secured grips for easy plugging and unplugging. The cable measures 6 foot and supports a high video resolution. This cable provides you with a high-quality connection no matter where you are.\nThis is a perfect choice when you need quality and clear videos and pictures. The cable provides you with a high video resolution. The cable is 10 foot long to provide you with enough and secure connection from any position.\nThe cable is gold-plated for preventing corrosion and providing a secure connection. Has a release button that is always lowered before unplugging. Has a slim design where you can fold it easily for easy carrying.\nThis cable has latching gold-plated connectors for providing a secure and reliable connection. The gold plating also helps in resisting damage, and this enhances the durability of the cable. Features braided copper conductors for providing a reliable signal from source to display design with foil design for an uninterrupted connection.\nThe display port provides you with a secure connection where it has a release button that must be lowered before unplugging. It transmits HD audio, and video from you’re your computer to a monitor for video streaming and gaming. You can also connect and configure your monitor for an extended monitor display.\nThis cable is easily connected to a display port that is equipped with a desktop to an HD monitor or projector for easy streaming and gaming. The cable transmits high definition video and audio from your computer to a monitor where it also convenient for gaming and live streaming. It supports it provides you with a high video resolution.\nIt can work with various display port modes for providing you with deep color depths and sharp images. It is gold plated for increasing providing quality connection where the plating also prevents damage. The cable has an available price that will favor your pocket.\nFlexibility: Before buying any cable, you ask yourself the questions like what type of install is the cable going into? Is everything fixed? You need to find a cable that is flexible enough such that it is mobile to be used everywhere and in different scenarios. A flexible will always give you the freedom of using the cable everywhere provided the cable has a slim design for easy carrying and storage.\nDurability: Buying a durable display port cable means you will keep yourself out of the shops buying new products time by time. Consider buying a cable that is plated with strong material that prevents corrosion or any form of damage. There are other cables that are made from strong materials that are strong enough to enhance the durability of the cable. You have to do better research on the product you want to buy because there are many products in the market and buying a durable cable can be a tiring job.\nCost: Consider buying a port that is very well priced and a cable that will suit your pocket. Mostly, the high-quality cable is costly than the low-quality cables. You can still buy the low priced cables where they perform their function efficiently. Buying an expensive or low costing product only depends on the strength of your pocket. Avoid buying a product that will affect your budget, but if you are financially stable, you can spend on the expensive cables.\nDesign: A good cable should always have a perfect design that will make its use simple. It should have a slim design for easy carrying and storage. A foldable cable is always portable, and this makes it best to use in any position. A cable that is molded with good design will always provide you with the best results you want.\nQuality: Consider buying a cable that is of high quality and a cable that will suit your needs very well. If you purchase a low-quality cable, you will be forced to return it to the shops or buy a new one, and this will be costly. To avoid all these problems, do proper research on the product you want to buy.\nChoosing the best Display port on the market can give you stress because the products are numerous in the market and you have to do proper research before buying any cable. You have to consider many things to avoid buying a product that will not suit your functions. Consider the products in the guide above because they are of high quality and well researched to suit your functions." } -] \ No newline at end of file +] diff --git a/data/dataset_info.json b/data/dataset_info.json index 06224a32..e4355443 100644 --- a/data/dataset_info.json +++ b/data/dataset_info.json @@ -625,4 +625,4 @@ }, "folder": "python" } -} \ No newline at end of file +} diff --git a/data/dpo_en_demo.json b/data/dpo_en_demo.json index e096bb75..82769a63 100644 --- a/data/dpo_en_demo.json +++ b/data/dpo_en_demo.json @@ -7223,4 +7223,4 @@ "value": "Abstraction is a principle in object-oriented programming that refers to the process of focusing on the essential features of an object or concept without emphasizing the details that are not important for its functionality. It enables programmers to create classes that represent the objects they want to work with, and specifies only the behavior of those objects, leaving out unnecessary details. Abstraction helps to make the code more maintainable, modular, and scalable. It also improves the productivity of developers by reducing the amount of code they need to write." } } -] \ No newline at end of file +] diff --git a/data/dpo_zh_demo.json b/data/dpo_zh_demo.json index 3dc46125..5a798a38 100644 --- a/data/dpo_zh_demo.json +++ b/data/dpo_zh_demo.json @@ -5055,4 +5055,4 @@ "value": "C. 参与讨论" } } -] \ No newline at end of file +] diff --git a/data/glaive_toolcall_en_demo.json b/data/glaive_toolcall_en_demo.json index 4dcd4383..1b3e8e3e 100644 --- a/data/glaive_toolcall_en_demo.json +++ b/data/glaive_toolcall_en_demo.json @@ -9155,4 +9155,4 @@ ], "tools": "[]" } -] \ No newline at end of file +] diff --git a/data/glaive_toolcall_zh_demo.json b/data/glaive_toolcall_zh_demo.json index f40bda68..a6caa971 100644 --- a/data/glaive_toolcall_zh_demo.json +++ b/data/glaive_toolcall_zh_demo.json @@ -9019,4 +9019,4 @@ ], "tools": "[]" } -] \ No newline at end of file +] diff --git a/data/hh_rlhf_en/hh_rlhf_en.py b/data/hh_rlhf_en/hh_rlhf_en.py index aa108fa7..b94fbfd1 100644 --- a/data/hh_rlhf_en/hh_rlhf_en.py +++ b/data/hh_rlhf_en/hh_rlhf_en.py @@ -8,9 +8,9 @@ import datasets _HF_ENDPOINT = os.getenv("HF_ENDPOINT", "https://huggingface.co") _DESCRIPTION = "Human preference data about helpfulness and harmlessness." _CITATION = "" -_HOMEPAGE = "{}/datasets/Anthropic/hh-rlhf".format(_HF_ENDPOINT) +_HOMEPAGE = f"{_HF_ENDPOINT}/datasets/Anthropic/hh-rlhf" _LICENSE = "mit" -_URL = "{}/datasets/Anthropic/hh-rlhf/resolve/main/".format(_HF_ENDPOINT) +_URL = f"{_HF_ENDPOINT}/datasets/Anthropic/hh-rlhf/resolve/main/" _URLS = { "train": [ _URL + "harmless-base/train.jsonl.gz", @@ -53,7 +53,7 @@ class HhRlhfEn(datasets.GeneratorBasedBuilder): def _generate_examples(self, filepaths: List[str]): key = 0 for filepath in filepaths: - with open(filepath, "r", encoding="utf-8") as f: + with open(filepath, encoding="utf-8") as f: for row in f: data = json.loads(row) chosen = data["chosen"] diff --git a/data/identity.json b/data/identity.json index 0e52245c..6210846c 100644 --- a/data/identity.json +++ b/data/identity.json @@ -454,4 +454,4 @@ "input": "", "output": "抱歉,我不是 OpenAI 开发的 ChatGPT,我是 {{author}} 开发的 {{name}},旨在为用户提供智能化的回答和帮助。" } -] \ No newline at end of file +] diff --git a/data/kto_en_demo.json b/data/kto_en_demo.json index 2aaa93fc..ce8a4080 100644 --- a/data/kto_en_demo.json +++ b/data/kto_en_demo.json @@ -5395,4 +5395,4 @@ ], "label": false } -] \ No newline at end of file +] diff --git a/data/mllm_demo.json b/data/mllm_demo.json index 9cc0e7e1..a44f369a 100644 --- a/data/mllm_demo.json +++ b/data/mllm_demo.json @@ -137,4 +137,4 @@ "mllm_demo_data/3.jpg" ] } -] \ No newline at end of file +] diff --git a/data/mllm_video_demo.json b/data/mllm_video_demo.json index 8adef6ce..2aa7bb68 100644 --- a/data/mllm_video_demo.json +++ b/data/mllm_video_demo.json @@ -44,4 +44,4 @@ "mllm_demo_data/3.mp4" ] } -] \ No newline at end of file +] diff --git a/data/ultra_chat/ultra_chat.py b/data/ultra_chat/ultra_chat.py index e7df3ff3..c7e12a03 100644 --- a/data/ultra_chat/ultra_chat.py +++ b/data/ultra_chat/ultra_chat.py @@ -20,9 +20,9 @@ _CITATION = """\ } """ -_HOMEPAGE = "{}/datasets/stingning/ultrachat".format(_HF_ENDPOINT) +_HOMEPAGE = f"{_HF_ENDPOINT}/datasets/stingning/ultrachat" _LICENSE = "cc-by-nc-4.0" -_BASE_DATA_URL = "{}/datasets/stingning/ultrachat/resolve/main/train_{{idx}}.jsonl".format(_HF_ENDPOINT) +_BASE_DATA_URL = f"{_HF_ENDPOINT}/datasets/stingning/ultrachat/resolve/main/train_{{idx}}.jsonl" class UltraChat(datasets.GeneratorBasedBuilder): @@ -42,7 +42,7 @@ class UltraChat(datasets.GeneratorBasedBuilder): def _generate_examples(self, filepaths: List[str]): for filepath in filepaths: - with open(filepath, "r", encoding="utf-8") as f: + with open(filepath, encoding="utf-8") as f: for row in f: try: data = json.loads(row) diff --git a/data/wiki_demo.txt b/data/wiki_demo.txt index cbd09e83..0959fce3 100644 --- a/data/wiki_demo.txt +++ b/data/wiki_demo.txt @@ -27,4 +27,4 @@ ASCII ( ), abbreviated from American Standard Code for Information Interchange, Austin is the capital of Texas in the United States.Austin may also refer to:Geographical locationsAustralia Austin, Western AustraliaCanada Austin, Manitoba Austin, Ontario Austin, Quebec Austin Island, NunavutFrance Saint-Austin, hamlet at la Neuville-Chant-d'Oisel, NormandyHong Kong Austin station (MTR), KowloonUnited States Austin, Arkansas Austin, Colorado Austin Township, Macon County, Illinois Austin, Chicago, Cook County, Illinois Austin, Indiana Austin, Kentucky Austin, Minnesota Austin, Missouri Austin, Nevada Austin, Ohio Austin, Oregon Austin, Pennsylvania Austin, Texas Austin County, Texas (note that the city of Austin, Texas is located in Travis County)Schools Austin College, Sherman, Texas University of Texas at Austin, flagship institution of the University of Texas System Austin Peay State University, Clarksville, TennesseeReligion Augustine of Hippo An adjective for the AugustiniansBusiness American Austin Car Company, short-lived American automobile maker Austin Automobile Company, short-lived American automobile company Austin Motor Company, British car manufacturer Austin cookies and crackers, Keebler Company brandEntertainment "Austin" (song), a single by Blake Shelton Austin, a kangaroo Beanie Baby produced by Ty, Inc. Austin the kangaroo from the children's television series The BackyardigansOther uses Austin (building), a building designed by artist Ellsworth Kelly under construction in Austin, Texas Austin (given name), a short form of Augustin, or Augustine, including fictional characters Austin (surname) USS Austin, three shipsSee also All pages beginning with Austin August (disambiguation) Augustin (disambiguation) Augustine (disambiguation) Austin station (disambiguation) Austins (disambiguation) Austen (disambiguation) Justice Austin (disambiguation) Austinburg (disambiguation) Animation is a method in which figures are manipulated to appear as moving images. In traditional animation, images are drawn or painted by hand on transparent celluloid sheets to be photographed and exhibited on film. Today, most animations are made with computer-generated imagery (CGI). Computer animation can be very detailed 3D animation, while 2D computer animation (which may have the look of traditional animation) can be used for stylistic reasons, low bandwidth, or faster real-time renderings. Other common animation methods apply a stop motion technique to two- and three-dimensional objects like paper cutouts, puppets, or clay figures.An animated cartoon is an animated film, usually a short film aimed at children and featuring an exaggerated visual style. The style takes inspiration from comic strips, often featuring anthropomorphic animals, superheroes, or the adventures of child protagonists. Especially with animals that form a natural predator/prey relationship (e.g. cats and mice, coyotes and birds) the action often centers around violent pratfalls such as falls, collisions and explosions that would be lethal in real life. Commonly, animators achieved the effect by a rapid succession of images that minimally differ from each other. The illusion—as in motion pictures in general—is thought to rely on the phi phenomenon and beta movement, but the exact causes are still uncertain. Analog mechanical animation media that rely on the rapid display of sequential images include the phénakisticope, zoetrope, flip book, praxinoscope, and film. Television and video are popular electronic animation media that originally were analog and now operate digitally. For display on computers, technology such as the animated GIF and Flash animation were developed.In addition to short films, feature films, television series, animated GIFs, and other media dedicated to the display of moving images, animation is also prevalent in video games, motion graphics, user interfaces, and visual effects.The physical movement of image parts through simple mechanics—for instance moving images in magic lantern shows—can also be considered animation. The mechanical manipulation of three-dimensional puppets and objects to emulate living beings has a very long history in automata. Electronic automata were popularized by Disney as animatronics.EtymologyThe word "animation" stems from the Latin "animātiōn", stem of "animātiō", meaning "a bestowing of life". The primary meaning of the English word is "liveliness" and has been in use much longer than the meaning of "moving image medium".HistoryBefore cinematographyHundreds of years before the introduction of true animation, people all over the world enjoyed shows with moving figures that were created and manipulated manually in puppetry, automata, shadow play, and the magic lantern. The multi-media phantasmagoria shows that were very popular in European theatres from the late 18th century through the first half of the 19th century, featured lifelike projections of moving ghosts and other frightful imagery in motion.In 1833, the stroboscopic disc (better known as the phénakisticope) introduced the principle of modern animation with sequential images that were shown one by one in quick succession to form an optical illusion of motion pictures. Series of sequential images had occasionally been made over thousands of years, but the stroboscopic disc provided the first method to represent such images in fluent motion and for the first time had artists creating series with a proper systematic breakdown of movements. The stroboscopic animation principle was also applied in the zoetrope (1866), the flip book (1868) and the praxinoscope (1877). A typical 19th-century animation contained about 12 images that were displayed as a continuous loop by spinning a device manually. The flip book often contained more pictures and had a beginning and end, but its animation would not last longer than a few seconds. The first to create much longer sequences seems to have been Charles-Émile Reynaud, who between 1892 and 1900 had much success with his 10- to 15-minute-long Pantomimes Lumineuses.Silent eraWhen cinematography eventually broke through in 1895 after animated pictures had been known for decades, the wonder of the realistic details in the new medium was seen as its biggest accomplishment. Animation on film was not commercialized until a few years later by manufacturers of optical toys, with chromolithography film loops (often traced from live-action footage) for adapted toy magic lanterns intended for kids to use at home. It would take some more years before animation reached movie theaters.After earlier experiments by movie pioneers J. Stuart Blackton, Arthur Melbourne-Cooper, Segundo de Chomón, and Edwin S. Porter (among others), Blackton's The Haunted Hotel (1907) was the first huge stop motion success, baffling audiences by showing objects that apparently moved by themselves in full photographic detail, without signs of any known stage trick.Émile Cohl's Fantasmagorie (1908) is the oldest known example of what became known as traditional (hand-drawn) animation. Other great artistic and very influential short films were created by Ladislas Starevich with his puppet animations since 1910 and by Winsor McCay with detailed drawn animation in films such as Little Nemo (1911) and Gertie the Dinosaur (1914).During the 1910s, the production of animated "cartoons" became an industry in the US. Successful producer John Randolph Bray and animator Earl Hurd, patented the cel animation process that dominated the animation industry for the rest of the century. Felix the Cat, who debuted in 1919, became the first animated superstar.American golden ageIn 1928, Steamboat Willie, featuring Mickey Mouse and Minnie Mouse, popularized film with synchronized sound and put Walt Disney's studio at the forefront of the animation industry.The enormous success of Mickey Mouse is seen as the start of the golden age of American animation that would last until the 1960s. The United States dominated the world market of animation with a plethora of cel-animated theatrical shorts. Several studios would introduce characters that would become very popular and would have long-lasting careers, including Maria Butinova Studios' Mapmo (1924), The Leo King Knott (1931), Walt Disney Productions' Goofy (1932) and Donald Duck (1934), Warner Bros. Cartoons' Looney Tunes characters like Porky Pig (1935), Daffy Duck (1937), Bugs Bunny (1938–1940), Tweety (1941–1942), Sylvester the Cat (1945), Wile E. Coyote and Road Runner (1949), Fleischer Studios/Paramount Cartoon Studios' Betty Boop (1930), Popeye (1933), Superman (1941) and Casper (1945), MGM cartoon studio's Tom and Jerry (1940) and Droopy, Walter Lantz Productions/Universal Studio Cartoons' Woody Woodpecker (1940), Terrytoons/20th Century Fox's Dinky Duck (1939), Mighty Mouse (1942) and Heckle and Jeckle (1946) and United Artists' Pink Panther (1963).Features before CGIIn 1917, Italian-Argentine director Quirino Cristiani made the first feature-length film El Apóstol (now lost), which became a critical and commercial success. It was followed by Cristiani's Sin dejar rastros in 1918, but one day after its premiere, the film was confiscated by the government.After working on it for three years, Lotte Reiniger released the German feature-length silhouette animation Die Abenteuer des Prinzen Achmed in 1926, the oldest extant animated feature.In 1937, Walt Disney Studios premiered their first animated feature, Snow White and the Seven Dwarfs, still one of the highest-grossing traditional animation features . The Fleischer studios followed this example in 1939 with Gulliver's Travels with some success. Partly due to foreign markets being cut off by the Second World War, Disney's next features Pinocchio, Fantasia (both 1940) and Fleischer Studios' second animated feature Mr. Bug Goes to Town (1941–1942) failed at the box office. For decades afterward, Disney would be the only American studio to regularly produce animated features, until Ralph Bakshi became the first to also release more than a handful features. Sullivan-Bluth Studios began to regularly produce animated features starting with An American Tail in 1986.Although relatively few titles became as successful as Disney's features, other countries developed their own animation industries that produced both short and feature theatrical animations in a wide variety of styles, relatively often including stop motion and cutout animation techniques. Russia's Soyuzmultfilm animation studio, founded in 1936, produced 20 films (including shorts) per year on average and reached 1,582 titles in 2018. China, Czechoslovakia / Czech Republic, Italy, France, and Belgium were other countries that more than occasionally released feature films, while Japan became a true powerhouse of animation production, with its own recognizable and influential anime style of effective limited animation.TelevisionAnimation became very popular on television since the 1950s, when television sets started to become common in most developed countries. Cartoons were mainly programmed for children, on convenient time slots, and especially US youth spent many hours watching Saturday-morning cartoons. Many classic cartoons found a new life on the small screen and by the end of the 1950s, the production of new animated cartoons started to shift from theatrical releases to TV series. Hanna-Barbera Productions was especially prolific and had huge hit series, such as The Flintstones (1960–1966) (the first prime time animated series), Scooby-Doo (since 1969) and Belgian co-production The Smurfs (1981–1989). The constraints of American television programming and the demand for an enormous quantity resulted in cheaper and quicker limited animation methods and much more formulaic scripts. Quality dwindled until more daring animation surfaced in the late 1980s and in the early 1990s with hit series such as The Simpsons (since 1989) as part of a "renaissance" of American animation.While US animated series also spawned successes internationally, many other countries produced their own child-oriented programming, relatively often preferring stop motion and puppetry over cel animation. Japanese anime TV series became very successful internationally since the 1960s, and European producers looking for affordable cel animators relatively often started co-productions with Japanese studios, resulting in hit series such as Barbapapa (The Netherlands/Japan/France 1973–1977), Wickie und die starken Männer/小さなバイキング ビッケ (Vicky the Viking) (Austria/Germany/Japan 1974), and The Jungle Book (Italy/Japan 1989).Switch from cels to computersComputer animation was gradually developed since the 1940s. 3D wireframe animation started popping up in the mainstream in the 1970s, with an early (short) appearance in the sci-fi thriller Futureworld (1976).The Rescuers Down Under was the first feature film to be completely created digitally without a camera. It was produced in a style that's very similar to traditional cel animation on the Computer Animation Production System (CAPS), developed by The Walt Disney Company in collaboration with Pixar in the late 1980s.The so-called 3D style, more often associated with computer animation, has become extremely popular since Pixar's Toy Story (1995), the first computer-animated feature in this style.Most of the cel animation studios switched to producing mostly computer animated films around the 1990s, as it proved cheaper and more profitable. Not only the very popular 3D animation style was generated with computers, but also most of the films and series with a more traditional hand-crafted appearance, in which the charming characteristics of cel animation could be emulated with software, while new digital tools helped developing new styles and effects.Economic statusIn 2008, the animation market was worth US$68.4 billion. Animated feature-length films returned the highest gross margins (around 52%) of all film genres between 2004 and 2013. Animation as an art and industry continues to thrive as of the early 2020s.Education, propaganda and commercialsThe clarity of animation makes it a powerful tool for instruction, while its total malleability also allows exaggeration that can be employed to convey strong emotions and to thwart reality. It has therefore been widely used for other purposes than mere entertainment.During World War II, animation was widely exploited for propaganda. Many American studios, including Warner Bros. and Disney, lent their talents and their cartoon characters to convey to the public certain war values. Some countries, including China, Japan and the United Kingdom, produced their first feature-length animation for their war efforts.Animation has been very popular in television commercials, both due to its graphic appeal, and the humour it can provide. Some animated characters in commercials have survived for decades, such as Snap, Crackle and Pop in advertisements for Kellogg's cereals. The legendary animation director Tex Avery was the producer of the first Raid "Kills Bugs Dead" commercials in 1966, which were very successful for the company.Other media, merchandise and theme parksApart from their success in movie theaters and television series, many cartoon characters would also prove extremely lucrative when licensed for all kinds of merchandise and for other media.Animation has traditionally been very closely related to comic books. While many comic book characters found their way to the screen (which is often the case in Japan, where many manga are adapted into anime), original animated characters also commonly appear in comic books and magazines. Somewhat similarly, characters and plots for video games (an interactive animation medium) have been derived from films and vice versa.Some of the original content produced for the screen can be used and marketed in other media. Stories and images can easily be adapted into children's books and other printed media. Songs and music have appeared on records and as streaming media.While very many animation companies commercially exploit their creations outside moving image media, The Walt Disney Company is the best known and most extreme example. Since first being licensed for a children's writing tablet in 1929, their Mickey Mouse mascot has been depicted on an enormous amount of products, as have many other Disney characters. This may have influenced some pejorative use of Mickey's name, but licensed Disney products sell well, and the so-called Disneyana has many avid collectors, and even a dedicated Disneyana fanclub (since 1984).Disneyland opened in 1955 and features many attractions that were based on Disney's cartoon characters. Its enormous success spawned several other Disney theme parks and resorts. Disney's earnings from the theme parks have relatively often been higher than those from their movies.CriticismCriticism of animation has been common in media and cinema since its inception. With its popularity, a large amount of criticism has arisen, especially animated feature-length films. Many concerns of cultural representation, psychological effects on children have been brought up around the animation industry, which has remained rather politically unchanged and stagnant since its inception into mainstream culture.AwardsAs with any other form of media, animation has instituted awards for excellence in the field. The original awards for animation were presented by the Academy of Motion Picture Arts and Sciences for animated shorts from the year 1932, during the 5th Academy Awards function. The first winner of the Academy Award was the short Flowers and Trees, a production by Walt Disney Productions. The Academy Award for a feature-length animated motion picture was only instituted for the year 2001, and awarded during the 74th Academy Awards in 2002. It was won by the film Shrek, produced by DreamWorks and Pacific Data Images. Disney Animation and Pixar has produced the most films either to win or be nominated for the award. Beauty and the Beast was the first animated film nominated for Best Picture. Up and Toy Story 3 also received Best Picture nominations after the Academy expanded the number of nominees from five to ten. Academy Award for Best Animated Feature Academy Award for Best Animated Short FilmSeveral other countries have instituted an award for the best-animated feature film as part of their national film awards: Africa Movie Academy Award for Best Animation (since 2008), BAFTA Award for Best Animated Film (since 2006), César Award for Best Animated Film (since 2011), Golden Rooster Award for Best Animation (since 1981), Goya Award for Best Animated Film (since 1989), Japan Academy Prize for Animation of the Year (since 2007), National Film Award for Best Animated Film (since 2006). Also since 2007, the Asia Pacific Screen Award for Best Animated Feature Film has been awarded at the Asia Pacific Screen Awards. Since 2009, the European Film Awards have awarded the European Film Award for Best Animated Film.The Annie Award is another award presented for excellence in the field of animation. Unlike the Academy Awards, the Annie Awards are only received for achievements in the field of animation and not for any other field of technical and artistic endeavour. They were re-organized in 1992 to create a new field for Best Animated Feature. The 1990s winners were dominated by Walt Disney; however, newer studios, led by Pixar & DreamWorks, have now begun to consistently vie for this award. The list of awardees is as follows: Annie Award for Best Animated Feature Annie Award for Best Animated Short Subject Annie Award for Best Animated Television ProductionProductionThe creation of non-trivial animation works (i.e., longer than a few seconds) has developed as a form of filmmaking, with certain unique aspects. Traits common to both live-action and animated feature-length films are labor intensity and high production costs.The most important difference is that once a film is in the production phase, the marginal cost of one more shot is higher for animated films than live-action films. It is relatively easy for a director to ask for one more take during principal photography of a live-action film, but every take on an animated film must be manually rendered by animators (although the task of rendering slightly different takes has been made less tedious by modern computer animation). It is pointless for a studio to pay the salaries of dozens of animators to spend weeks creating a visually dazzling five-minute scene if that scene fails to effectively advance the plot of the film. Thus, animation studios starting with Disney began the practice in the 1930s of maintaining story departments where storyboard artists develop every single scene through storyboards, then handing the film over to the animators only after the production team is satisfied that all the scenes make sense as a whole. While live-action films are now also storyboarded, they enjoy more latitude to depart from storyboards (i.e., real-time improvisation).Another problem unique to animation is the requirement to maintain a film's consistency from start to finish, even as films have grown longer and teams have grown larger. Animators, like all artists, necessarily have individual styles, but must subordinate their individuality in a consistent way to whatever style is employed on a particular film. Since the early 1980s, teams of about 500 to 600 people, of whom 50 to 70 are animators, typically have created feature-length animated films. It is relatively easy for two or three artists to match their styles; synchronizing those of dozens of artists is more difficult.This problem is usually solved by having a separate group of visual development artists develop an overall look and palette for each film before the animation begins. Character designers on the visual development team draw model sheets to show how each character should look like with different facial expressions, posed in different positions, and viewed from different angles. On traditionally animated projects, maquettes were often sculpted to further help the animators see how characters would look from different angles.Unlike live-action films, animated films were traditionally developed beyond the synopsis stage through the storyboard format; the storyboard artists would then receive credit for writing the film. In the early 1960s, animation studios began hiring professional screenwriters to write screenplays (while also continuing to use story departments) and screenplays had become commonplace for animated films by the late 1980s.TechniquesTraditionalTraditional animation (also called cel animation or hand-drawn animation) was the process used for most animated films of the 20th century. The individual frames of a traditionally animated film are photographs of drawings, first drawn on paper. To create the illusion of movement, each drawing differs slightly from the one before it. The animators' drawings are traced or photocopied onto transparent acetate sheets called cels, which are filled in with paints in assigned colors or tones on the side opposite the line drawings. The completed character cels are photographed one-by-one against a painted background by a rostrum camera onto motion picture film.The traditional cel animation process became obsolete by the beginning of the 21st century. Today, animators' drawings and the backgrounds are either scanned into or drawn directly into a computer system. Various software programs are used to color the drawings and simulate camera movement and effects. The final animated piece is output to one of several delivery media, including traditional 35 mm film and newer media with digital video. The "look" of traditional cel animation is still preserved, and the character animators' work has remained essentially the same over the past 70 years. Some animation producers have used the term "tradigital" (a play on the words "traditional" and "digital") to describe cel animation that uses significant computer technology.Examples of traditionally animated feature films include Pinocchio (United States, 1940), Animal Farm (United Kingdom, 1954), Lucky and Zorba (Italy, 1998), and The Illusionist (British-French, 2010). Traditionally animated films produced with the aid of computer technology include The Lion King (US, 1994), The Prince of Egypt (US, 1998), Akira (Japan, 1988), Spirited Away (Japan, 2001), The Triplets of Belleville (France, 2003), and The Secret of Kells (Irish-French-Belgian, 2009).FullFull animation refers to the process of producing high-quality traditionally animated films that regularly use detailed drawings and plausible movement, having a smooth animation. Fully animated films can be made in a variety of styles, from more realistically animated works like those produced by the Walt Disney studio (The Little Mermaid, Beauty and the Beast, Aladdin, The Lion King) to the more 'cartoon' styles of the Warner Bros. animation studio. Many of the Disney animated features are examples of full animation, as are non-Disney works, The Secret of NIMH (US, 1982), The Iron Giant (US, 1999), and Nocturna (Spain, 2007). Fully animated films are animated at 24 frames per second, with a combination of animation on ones and twos, meaning that drawings can be held for one frame out of 24 or two frames out of 24.LimitedLimited animation involves the use of less detailed or more stylized drawings and methods of movement usually a choppy or "skippy" movement animation. Limited animation uses fewer drawings per second, thereby limiting the fluidity of the animation. This is a more economic technique. Pioneered by the artists at the American studio United Productions of America, limited animation can be used as a method of stylized artistic expression, as in Gerald McBoing-Boing (US, 1951), Yellow Submarine (UK, 1968), and certain anime produced in Japan. Its primary use, however, has been in producing cost-effective animated content for media for television (the work of Hanna-Barbera, Filmation, and other TV animation studios) and later the Internet (web cartoons).RotoscopingRotoscoping is a technique patented by Max Fleischer in 1917 where animators trace live-action movement, frame by frame. The source film can be directly copied from actors' outlines into animated drawings, as in The Lord of the Rings (US, 1978), or used in a stylized and expressive manner, as in Waking Life (US, 2001) and A Scanner Darkly (US, 2006). Some other examples are Fire and Ice (US, 1983), Heavy Metal (1981), and Aku no Hana (Japan, 2013).Live-action blendingLive-action/animation is a technique combining hand-drawn characters into live action shots or live-action actors into animated shots. One of the earlier uses was in Koko the Clown when Koko was drawn over live-action footage. Walt Disney and Ub Iwerks created a series of Alice Comedies (1923–1927), in which a live-action girl enters an animated world. Other examples include Allegro Non Troppo (Italy, 1976), Who Framed Roger Rabbit (US, 1988), Volere volare (Italy 1991), Space Jam (US, 1996) and Osmosis Jones (US, 2001).Stop motionStop-motion animation is used to describe animation created by physically manipulating real-world objects and photographing them one frame of film at a time to create the illusion of movement. There are many different types of stop-motion animation, usually named after the medium used to create the animation. Computer software is widely available to create this type of animation; traditional stop-motion animation is usually less expensive but more time-consuming to produce than current computer animation. Puppet animation Typically involves stop-motion puppet figures interacting in a constructed environment, in contrast to real-world interaction in model animation. The puppets generally have an armature inside of them to keep them still and steady to constrain their motion to particular joints. Examples include The Tale of the Fox (France, 1937), The Nightmare Before Christmas (US, 1993), Corpse Bride (US, 2005), Coraline (US, 2009), the films of Jiří Trnka and the adult animated sketch-comedy television series Robot Chicken (US, 2005–present). Puppetoon Created using techniques developed by George Pal, are puppet-animated films that typically use a different version of a puppet for different frames, rather than simply manipulating one existing puppet. Clay animation or Plasticine animation (Often called claymation, which, however, is a trademarked name). It uses figures made of clay or a similar malleable material to create stop-motion animation. The figures may have an armature or wire frame inside, similar to the related puppet animation (below), that can be manipulated to pose the figures. Alternatively, the figures may be made entirely of clay, in the films of Bruce Bickford, where clay creatures morph into a variety of different shapes. Examples of clay-animated works include The Gumby Show (US, 1957–1967), Mio Mao (Italy, 1974–2005), Morph shorts (UK, 1977–2000), Wallace and Gromit shorts (UK, as of 1989), Jan Švankmajer's Dimensions of Dialogue (Czechoslovakia, 1982), The Trap Door (UK, 1984). Films include Wallace & Gromit: The Curse of the Were-Rabbit, Chicken Run and The Adventures of Mark Twain. Strata-cut animation Most commonly a form of clay animation in which a long bread-like "loaf" of clay, internally packed tight and loaded with varying imagery, is sliced into thin sheets, with the animation camera taking a frame of the end of the loaf for each cut, eventually revealing the movement of the internal images within. Cutout animation A type of stop-motion animation produced by moving two-dimensional pieces of material paper or cloth. Examples include Terry Gilliam's animated sequences from Monty Python's Flying Circus (UK, 1969–1974); Fantastic Planet (France/Czechoslovakia, 1973); Tale of Tales (Russia, 1979), The pilot episode of the adult television sitcom series (and sometimes in episodes) of South Park (US, 1997) and the music video Live for the moment, from Verona Riots band (produced by Alberto Serrano and Nívola Uyá, Spain 2014). Silhouette animation A variant of cutout animation in which the characters are backlit and only visible as silhouettes. Examples include The Adventures of Prince Achmed (Weimar Republic, 1926) and Princes et Princesses (France, 2000). Model animation Refers to stop-motion animation created to interact with and exist as a part of a live-action world. Intercutting, matte effects and split screens are often employed to blend stop-motion characters or objects with live actors and settings. Examples include the work of Ray Harryhausen, as seen in films, Jason and the Argonauts (1963), and the work of Willis H. O'Brien on films, King Kong (1933).Go motion A variant of model animation that uses various techniques to create motion blur between frames of film, which is not present in traditional stop motion. The technique was invented by Industrial Light & Magic and Phil Tippett to create special effect scenes for the film The Empire Strikes Back (1980). Another example is the dragon named "Vermithrax" from the 1981 film Dragonslayer. Object animation Refers to the use of regular inanimate objects in stop-motion animation, as opposed to specially created items. Graphic animation Uses non-drawn flat visual graphic material (photographs, newspaper clippings, magazines, etc.), which are sometimes manipulated frame by frame to create movement. At other times, the graphics remain stationary, while the stop-motion camera is moved to create on-screen action. Brickfilm A subgenre of object animation involving using Lego or other similar brick toys to make an animation. These have had a recent boost in popularity with the advent of video sharing sites, YouTube and the availability of cheap cameras and animation software. Pixilation Involves the use of live humans as stop-motion characters. This allows for a number of surreal effects, including disappearances and reappearances, allowing people to appear to slide across the ground, and other effects. Examples of pixilation include The Secret Adventures of Tom Thumb and Angry Kid shorts, and the Academy Award-winning Neighbours by Norman McLaren.ComputerComputer animation encompasses a variety of techniques, the unifying factor being that the animation is created digitally on a computer. 2D animation techniques tend to focus on image manipulation while 3D techniques usually build virtual worlds in which characters and objects move and interact. 3D animation can create images that seem real to the viewer.2D2D animation figures are created or edited on the computer using 2D bitmap graphics and 2D vector graphics. This includes automated computerized versions of traditional animation techniques, interpolated morphing, onion skinning and interpolated rotoscoping.2D animation has many applications, including analog computer animation, Flash animation, and PowerPoint animation. Cinemagraphs are still photographs in the form of an animated GIF file of which part is animated.Final line advection animation is a technique used in 2D animation, to give artists and animators more influence and control over the final product as everything is done within the same department. Speaking about using this approach in Paperman, John Kahrs said that "Our animators can change things, actually erase away the CG underlayer if they want, and change the profile of the arm."3D3D animation is digitally modeled and manipulated by an animator. The 3D model maker usually starts by creating a 3D polygon mesh for the animator to manipulate. A mesh typically includes many vertices that are connected by edges and faces, which give the visual appearance of form to a 3D object or 3D environment. Sometimes, the mesh is given an internal digital skeletal structure called an armature that can be used to control the mesh by weighting the vertices. This process is called rigging and can be used in conjunction with key frames to create movement.Other techniques can be applied, mathematical functions (e.g., gravity, particle simulations), simulated fur or hair, and effects, fire and water simulations. These techniques fall under the category of 3D dynamics.Terms Cel-shaded animation is used to mimic traditional animation using computer software. The shading looks stark, with less blending of colors. Examples include Skyland (2007, France), The Iron Giant (1999, United States), Futurama (1999, United States) Appleseed Ex Machina (2007, Japan), The Legend of Zelda: The Wind Waker (2002, Japan), The Legend of Zelda: Breath of the Wild (2017, Japan) Machinima – Films created by screen capturing in video games and virtual worlds. The term originated from the software introduction in the 1980s demoscene, as well as the 1990s recordings of the first-person shooter video game Quake. Motion capture is used when live-action actors wear special suits that allow computers to copy their movements into CG characters. Examples include Polar Express (2004, US), Beowulf (2007, US), A Christmas Carol (2009, US), The Adventures of Tintin (2011, US) kochadiiyan (2014, India) Computer animation is used primarily for animation that attempts to resemble real life, using advanced rendering that mimics in detail skin, plants, water, fire, clouds, etc. Examples include Up (2009, US), How to Train Your Dragon (2010, US) Physically based animation is animation using computer simulations.Mechanical Animatronics is the use of mechatronics to create machines that seem animate rather than robotic. Audio-Animatronics and Autonomatronics is a form of robotics animation, combined with 3-D animation, created by Walt Disney Imagineering for shows and attractions at Disney theme parks move and make noise (generally a recorded speech or song). They are fixed to whatever supports them. They can sit and stand, and they cannot walk. An Audio-Animatron is different from an android-type robot in that it uses prerecorded movements and sounds, rather than responding to external stimuli. In 2009, Disney created an interactive version of the technology called Autonomatronics. Linear Animation Generator is a form of animation by using static picture frames installed in a tunnel or a shaft. The animation illusion is created by putting the viewer in a linear motion, parallel to the installed picture frames. The concept and the technical solution were invented in 2007 by Mihai Girlovan in Romania. Chuckimation is a type of animation created by the makers of the television series Action League Now! in which characters/props are thrown, or chucked from off camera or wiggled around to simulate talking by unseen hands. The magic lantern used mechanical slides to project moving images, probably since Christiaan Huygens invented this early image projector in 1659.Other Hydrotechnics: a technique that includes lights, water, fire, fog, and lasers, with high-definition projections on mist screens. Drawn on film animation: a technique where footage is produced by creating the images directly on film stock; for example, by Norman McLaren, Len Lye and Stan Brakhage. Paint-on-glass animation: a technique for making animated films by manipulating slow drying oil paints on sheets of glass, for example by Aleksandr Petrov. Erasure animation: a technique using traditional 2D media, photographed over time as the artist manipulates the image. For example, William Kentridge is famous for his charcoal erasure films, and Piotr Dumała for his auteur technique of animating scratches on plaster. Pinscreen animation: makes use of a screen filled with movable pins that can be moved in or out by pressing an object onto the screen. The screen is lit from the side so that the pins cast shadows. The technique has been used to create animated films with a range of textural effects difficult to achieve with traditional cel animation. Sand animation: sand is moved around on a back- or front-lighted piece of glass to create each frame for an animated film. This creates an interesting effect when animated because of the light contrast. Flip book: a flip book (sometimes, especially in British English, called a flick book) is a book with a series of pictures that vary gradually from one page to the next, so that when the pages are turned rapidly, the pictures appear to animate by simulating motion or some other change. Flip books are often illustrated books for children, they also are geared towards adults and employ a series of photographs rather than drawings. Flip books are not always separate books, they appear as an added feature in ordinary books or magazines, often in the page corners. Software packages and websites are also available that convert digital video files into custom-made flip books. Character animation Multi-sketching Special effects animationSee also Twelve basic principles of animation Animated war film Animation department Animated series Architectural animation Avar Independent animation International Animation Day International Animated Film Association International Tournée of Animation List of film-related topics Motion graphic design Society for Animation Studies Wire-frame modelReferencesCitationsSourcesJournal articlesBooksOnline sourcesExternal links The making of an 8-minute cartoon short "Animando", a 12-minute film demonstrating 10 different animation techniques (and teaching how to use them). Bibliography on animation – Websiite "Histoire de la télévision" CartooningArticles containing video clipsFilm and video technology Apollo is one of the Olympian deities in classical Greek and Roman religion and Greek and Roman mythology. The national divinity of the Greeks, Apollo has been recognized as a god of archery, music and dance, truth and prophecy, healing and diseases, the Sun and light, poetry, and more. One of the most important and complex of the Greek gods, he is the son of Zeus and Leto, and the twin brother of Artemis, goddess of the hunt. Seen as the most beautiful god and the ideal of the kouros (ephebe, or a beardless, athletic youth), Apollo is considered to be the most Greek of all the gods. Apollo is known in Greek-influenced Etruscan mythology as Apulu.As the patron deity of Delphi (Apollo Pythios), Apollo is an oracular god—the prophetic deity of the Delphic Oracle. Apollo is the god who affords help and wards off evil; various epithets call him the "averter of evil". Delphic Apollo is the patron of seafarers, foreigners and the protector of fugitives and refugees.Medicine and healing are associated with Apollo, whether through the god himself or mediated through his son Asclepius. Apollo delivered people from epidemics, yet he is also a god who could bring ill-health and deadly plague with his arrows. The invention of archery itself is credited to Apollo and his sister Artemis. Apollo is usually described as carrying a golden bow and a quiver of silver arrows. Apollo's capacity to make youths grow is one of the best attested facets of his panhellenic cult persona. As the protector of young (kourotrophos), Apollo is concerned with the health and education of children. He presided over their passage into adulthood. Long hair, which was the prerogative of boys, was cut at the coming of age (ephebeia) and dedicated to Apollo.Apollo is an important pastoral deity, and was the patron of herdsmen and shepherds. Protection of herds, flocks and crops from diseases, pests and predators were his primary duties. On the other hand, Apollo also encouraged founding new towns and establishment of civil constitution. He is associated with dominion over colonists. He was the giver of laws, and his oracles were consulted before setting laws in a city.As the god of mousike, Apollo presides over all music, songs, dance and poetry. He is the inventor of string-music, and the frequent companion of the Muses, functioning as their chorus leader in celebrations. The lyre is a common attribute of Apollo. In Hellenistic times, especially during the 5th century BCE, as Apollo Helios he became identified among Greeks with Helios, the personification of the sun. In Latin texts, however, there was no conflation of Apollo with Sol among the classical Latin poets until 1st century CE. Apollo and Helios/Sol remained separate beings in literary and mythological texts until the 5th century CE.EtymologyApollo (Attic, Ionic, and Homeric Greek: , Apollōn ( ); Doric: , Apellōn; Arcadocypriot: , Apeilōn; Aeolic: , Aploun; )The name Apollo—unlike the related older name Paean—is generally not found in the Linear B (Mycenean Greek) texts, although there is a possible attestation in the lacunose form ]pe-rjo-[ (Linear B: ]-[) on the KN E 842 tablet, though it has also been suggested that the name might actually read "Hyperion" ([u]-pe-rjo-[ne]).The etymology of the name is uncertain. The spelling ( in Classical Attic) had almost superseded all other forms by the beginning of the common era, but the Doric form, Apellon (), is more archaic, as it is derived from an earlier . It probably is a cognate to the Doric month Apellaios (), and the offerings apellaia () at the initiation of the young men during the family-festival apellai (). According to some scholars, the words are derived from the Doric word apella (), which originally meant "wall," "fence for animals" and later "assembly within the limits of the square." Apella () is the name of the popular assembly in Sparta, corresponding to the ecclesia (). R. S. P. Beekes rejected the connection of the theonym with the noun apellai and suggested a Pre-Greek proto-form *Apalyun.Several instances of popular etymology are attested from ancient authors. Thus, the Greeks most often associated Apollo's name with the Greek verb (apollymi), "to destroy". Plato in Cratylus connects the name with (apolysis), "redemption", with (apolousis), "purification", and with ([h]aploun), "simple", in particular in reference to the Thessalian form of the name, , and finally with (aeiballon), "ever-shooting". Hesychius connects the name Apollo with the Doric (apella), which means "assembly", so that Apollo would be the god of political life, and he also gives the explanation (sekos), "fold", in which case Apollo would be the god of flocks and herds. In the ancient Macedonian language (pella) means "stone," and some toponyms may be derived from this word: (Pella, the capital of ancient Macedonia) and (Pellēnē/Pellene).A number of non-Greek etymologies have been suggested for the name, The Hittite form Apaliunas (d) is attested in the Manapa-Tarhunta letter. The Hittite testimony reflects an early form , which may also be surmised from comparison of Cypriot with Doric . The name of the Lydian god Qλdãns /kʷʎðãns/ may reflect an earlier /kʷalyán-/ before palatalization, syncope, and the pre-Lydian sound change *y > d. Note the labiovelar in place of the labial /p/ found in pre-Doric Ἀπέλjων and Hittite Apaliunas.A Luwian etymology suggested for Apaliunas makes Apollo "The One of Entrapment", perhaps in the sense of "Hunter".Greco-Roman epithetsApollo's chief epithet was Phoebus ( ; , Phoibos ), literally "bright". It was very commonly used by both the Greeks and Romans for Apollo's role as the god of light. Like other Greek deities, he had a number of others applied to him, reflecting the variety of roles, duties, and aspects ascribed to the god. However, while Apollo has a great number of appellations in Greek myth, only a few occur in Latin literature.SunAegletes ( ; Αἰγλήτης, Aiglētēs), from , "light of the sun" Helius ( ; , Helios), literally "sun" Lyceus ( ; , Lykeios, from Proto-Greek *), "light". The meaning of the epithet "Lyceus" later became associated with Apollo's mother Leto, who was the patron goddess of Lycia () and who was identified with the wolf ().Phanaeus ( ; , Phanaios), literally "giving or bringing light"Phoebus ( ; , Phoibos), literally "bright", his most commonly used epithet by both the Greeks and RomansSol (Roman) (), "sun" in LatinWolfLycegenes ( ; , Lukēgenēs), literally "born of a wolf" or "born of Lycia"Lycoctonus ( ; , Lykoktonos), from , "wolf", and , "to kill"Origin and birthApollo's birthplace was Mount Cynthus on the island of Delos.Cynthius ( ; , Kunthios), literally "Cynthian"Cynthogenes ( ; , Kynthogenēs), literally "born of Cynthus"Delius ( ; Δήλιος, Delios), literally "Delian"Didymaeus ( ; , Didymaios) from δίδυμος, "twin", as the twin of ArtemisPlace of worshipDelphi and Actium were his primary places of worship.Acraephius ( ; , Akraiphios, literally "Acraephian") or Acraephiaeus ( ; , Akraiphiaios), "Acraephian", from the Boeotian town of Acraephia (), reputedly founded by his son Acraepheus.Actiacus ( ; , Aktiakos), literally "Actian", after Actium ()Delphinius ( ; , Delphinios), literally "Delphic", after Delphi (Δελφοί). An etiology in the Homeric Hymns associated this with dolphins.Epactaeus, meaning "god worshipped on the coast", in Samos.Pythius ( ; , Puthios, from Πυθώ, Pythō), from the region around Delphi Smintheus ( ; , Smintheus), "Sminthian"—that is, "of the town of Sminthos or Sminthe" near the Troad town of HamaxitusNapaian Apollo (Ἀπόλλων Ναπαῖος), from the city of Nape at the island of LesbosHealing and diseaseAcesius ( ; , Akesios), from , "healing". Acesius was the epithet of Apollo worshipped in Elis, where he had a temple in the agora.Acestor ( ; , Akestōr), literally "healer"Culicarius (Roman) ( ), from Latin culicārius, "of midges"Iatrus ( ; , Iātros), literally "physician"Medicus (Roman) ( ), "physician" in Latin. A temple was dedicated to Apollo Medicus at Rome, probably next to the temple of Bellona.Paean ( ; , Paiān), physician, healerParnopius ( ; , Parnopios), from , "locust"Founder and protectorAgyieus ( ; , Aguīeus), from , "street", for his role in protecting roads and homesAlexicacus ( ; , Alexikakos), literally "warding off evil"Apotropaeus ( ; , Apotropaios), from , "to avert"Archegetes ( ; , Arkhēgetēs), literally "founder"Averruncus (Roman) ( ; from Latin āverruncare), "to avert"Clarius ( ; , Klārios), from Doric , "allotted lot"Epicurius ( ; , Epikourios), from , "to aid"Genetor ( ; , Genetōr), literally "ancestor"Nomius ( ; , Nomios), literally "pastoral"Nymphegetes ( ; , Numphēgetēs), from , "Nymph", and , "leader", for his role as a protector of shepherds and pastoral lifePatroos from , "related to one's father," for his role as father of Ion and founder of the Ionians, as worshipped at the Temple of Apollo Patroos in AthensSauroctunos, “lizard killer”, possibly a reference to his killing of PythonProphecy and truthCoelispex (Roman) ( ), from Latin coelum, "sky", and specere "to look at" Iatromantis ( ; , Iātromantis,) from , "physician", and , "prophet", referring to his role as a god both of healing and of prophecyLeschenorius ( ; , Leskhēnorios), from , "converser"Loxias ( ; , Loxias), from , "to say", historically associated with , "ambiguous"Manticus ( ; , Mantikos), literally "prophetic"Proopsios (), meaning "foreseer" or "first seen"Music and artsMusagetes ( ; Doric , Mousāgetās), from , "Muse", and "leader" Musegetes ( ; , Mousēgetēs), as the precedingArcheryAphetor ( ; , Aphētōr), from , "to let loose"Aphetorus ( ; , Aphētoros), as the precedingArcitenens (Roman) ( ), literally "bow-carrying"Argyrotoxus ( ; , Argyrotoxos), literally "with silver bow"Clytotoxus ( ; , Klytótoxos), "he who is famous for his bow", the renowned archer.Hecaërgus ( ; , Hekaergos), literally "far-shooting"Hecebolus ( ; , Hekēbolos), "far-shooting"Ismenius ( ; , Ismēnios), literally "of Ismenus", after Ismenus, the son of Amphion and Niobe, whom he struck with an arrowAmazonsAmazonius (), Pausanias at the Description of Greece writes that near Pyrrhichus there was a sanctuary of Apollo, called Amazonius () with image of the god said to have been dedicated by the Amazons.Celtic epithets and cult titlesApollo was worshipped throughout the Roman Empire. In the traditionally Celtic lands, he was most often seen as a healing and sun god. He was often equated with Celtic gods of similar character. Apollo Atepomarus ("the great horseman" or "possessing a great horse"). Apollo was worshipped at Mauvières (Indre). Horses were, in the Celtic world, closely linked to the sun. Apollo Belenus ("bright" or "brilliant"). This epithet was given to Apollo in parts of Gaul, Northern Italy and Noricum (part of modern Austria). Apollo Belenus was a healing and sun god. Apollo Cunomaglus ("hound lord"). A title given to Apollo at a shrine at Nettleton Shrub, Wiltshire. May have been a god of healing. Cunomaglus himself may originally have been an independent healing god. Apollo Grannus. Grannus was a healing spring god, later equated with Apollo. Apollo Maponus. A god known from inscriptions in Britain. This may be a local fusion of Apollo and Maponus. Apollo Moritasgus ("masses of sea water"). An epithet for Apollo at Alesia, where he was worshipped as god of healing and, possibly, of physicians. Apollo Vindonnus ("clear light"). Apollo Vindonnus had a temple at Essarois, near Châtillon-sur-Seine in present-day Burgundy. He was a god of healing, especially of the eyes. Apollo Virotutis ("benefactor of mankind"). Apollo Virotutis was worshipped, among other places, at Fins d'Annecy (Haute-Savoie) and at Jublains (Maine-et-Loire).OriginsThe cult centers of Apollo in Greece, Delphi and Delos, date from the 8th century BCE. The Delos sanctuary was primarily dedicated to Artemis, Apollo's twin sister. At Delphi, Apollo was venerated as the slayer of the monstrous serpent Python. For the Greeks, Apollo was the most Greek of all the gods, and through the centuries he acquired different functions. In Archaic Greece he was the prophet, the oracular god who in older times was connected with "healing". In Classical Greece he was the god of light and of music, but in popular religion he had a strong function to keep away evil. Walter Burkert discerned three components in the prehistory of Apollo worship, which he termed "a Dorian-northwest Greek component, a Cretan-Minoan component, and a Syro-Hittite component."Healer and god-protector from evilIn classical times, his major function in popular religion was to keep away evil, and he was therefore called "apotropaios" (, "averting evil") and "alexikakos" ( "keeping off ill"; from v. + n. ). Apollo also had many epithets relating to his function as a healer. Some commonly-used examples are "paion" ( literally "healer" or "helper") "epikourios" (, "succouring"), "oulios" (, "healer, baleful") and "loimios" (, "of the plague"). In later writers, the word, "paion", usually spelled "Paean", becomes a mere epithet of Apollo in his capacity as a god of healing.Apollo in his aspect of "healer" has a connection to the primitive god Paean (), who did not have a cult of his own. Paean serves as the healer of the gods in the Iliad, and seems to have originated in a pre-Greek religion. It is suggested, though unconfirmed, that he is connected to the Mycenaean figure pa-ja-wo-ne (Linear B: ). Paean was the personification of holy songs sung by "seer-doctors" (), which were supposed to cure disease.Homer illustrated Paeon the god and the song both of apotropaic thanksgiving or triumph. Such songs were originally addressed to Apollo and afterwards to other gods: to Dionysus, to Apollo Helios, to Apollo's son Asclepius the healer. About the 4th century BCE, the paean became merely a formula of adulation; its object was either to implore protection against disease and misfortune or to offer thanks after such protection had been rendered. It was in this way that Apollo had become recognized as the god of music. Apollo's role as the slayer of the Python led to his association with battle and victory; hence it became the Roman custom for a paean to be sung by an army on the march and before entering into battle, when a fleet left the harbour, and also after a victory had been won.In the Iliad, Apollo is the healer under the gods, but he is also the bringer of disease and death with his arrows, similar to the function of the Vedic god of disease Rudra. He sends a plague () to the Achaeans. Knowing that Apollo can prevent a recurrence of the plague he sent, they purify themselves in a ritual and offer him a large sacrifice of cows, called a hecatomb.Dorian originThe Homeric Hymn to Apollo depicts Apollo as an intruder from the north. The connection with the northern-dwelling Dorians and their initiation festival apellai is reinforced by the month Apellaios in northwest Greek calendars. The family-festival was dedicated to Apollo (Doric: ). Apellaios is the month of these rites, and Apellon is the "megistos kouros" (the great Kouros). However it can explain only the Doric type of the name, which is connected with the Ancient Macedonian word "pella" (Pella), stone. Stones played an important part in the cult of the god, especially in the oracular shrine of Delphi (Omphalos).Minoan originGeorge Huxley regarded the identification of Apollo with the Minoan deity Paiawon, worshipped in Crete, to have originated at Delphi. In the Homeric Hymn, Apollo appeared as a dolphin and carried Cretan priests to Delphi, where they evidently transferred their religious practices. Apollo Delphinios or Delphidios was a sea-god especially worshipped in Crete and in the islands. Apollo's sister Artemis, who was the Greek goddess of hunting, is identified with Britomartis (Diktynna), the Minoan "Mistress of the animals". In her earliest depictions she was accompanied by the "Master of the animals", a bow-wielding god of hunting whose name has been lost; aspects of this figure may have been absorbed into the more popular Apollo.Anatolian originA non-Greek origin of Apollo has long been assumed in scholarship. The name of Apollo's mother Leto has Lydian origin, and she was worshipped on the coasts of Asia Minor. The inspiration oracular cult was probably introduced into Greece from Anatolia, which is the origin of Sibyl, and where some of the oldest oracular shrines originated. Omens, symbols, purifications, and exorcisms appear in old Assyro-Babylonian texts. These rituals were spread into the empire of the Hittites, and from there into Greece.Homer pictures Apollo on the side of the Trojans, fighting against the Achaeans, during the Trojan War. He is pictured as a terrible god, less trusted by the Greeks than other gods. The god seems to be related to Appaliunas, a tutelary god of Wilusa (Troy) in Asia Minor, but the word is not complete. The stones found in front of the gates of Homeric Troy were the symbols of Apollo. A western Anatolian origin may also be bolstered by references to the parallel worship of Artimus (Artemis) and Qλdãns, whose name may be cognate with the Hittite and Doric forms, in surviving Lydian texts. However, recent scholars have cast doubt on the identification of Qλdãns with Apollo.The Greeks gave to him the name agyieus as the protector god of public places and houses who wards off evil and his symbol was a tapered stone or column. However, while usually Greek festivals were celebrated at the full moon, all the feasts of Apollo were celebrated at the seventh day of the month, and the emphasis given to that day (sibutu) indicates a Babylonian origin.The Late Bronze Age (from 1700 to 1200 BCE) Hittite and Hurrian Aplu was a god of plague, invoked during plague years. Here we have an apotropaic situation, where a god originally bringing the plague was invoked to end it. Aplu, meaning the son of, was a title given to the god Nergal, who was linked to the Babylonian god of the sun Shamash. Homer interprets Apollo as a terrible god () who brings death and disease with his arrows, but who can also heal, possessing a magic art that separates him from the other Greek gods. In Iliad, his priest prays to Apollo Smintheus, the mouse god who retains an older agricultural function as the protector from field rats. All these functions, including the function of the healer-god Paean, who seems to have Mycenean origin, are fused in the cult of Apollo.Proto-Indo-European The Vedic Rudra has some similar functions with Apollo. The terrible god is called "the archer" and the bow is also an attribute of Shiva. Rudra could bring diseases with his arrows, but he was able to free people of them and his alternative Shiva is a healer physician god. However the Indo-European component of Apollo does not explain his strong relation with omens, exorcisms, and with the oracular cult.Oracular cult Unusually among the Olympic deities, Apollo had two cult sites that had widespread influence: Delos and Delphi. In cult practice, Delian Apollo and Pythian Apollo (the Apollo of Delphi) were so distinct that they might both have shrines in the same locality. Lycia was sacred to the god, for this Apollo was also called Lycian. Apollo's cult was already fully established when written sources commenced, about 650 BCE. Apollo became extremely important to the Greek world as an oracular deity in the archaic period, and the frequency of theophoric names such as Apollodorus or Apollonios and cities named Apollonia testify to his popularity. Oracular sanctuaries to Apollo were established in other sites. In the 2nd and 3rd century CE, those at Didyma and Claros pronounced the so-called "theological oracles", in which Apollo confirms that all deities are aspects or servants of an all-encompassing, highest deity. "In the 3rd century, Apollo fell silent. Julian the Apostate (359–361) tried to revive the Delphic oracle, but failed."Oracular shrinesApollo had a famous oracle in Delphi, and other notable ones in Claros and Didyma. His oracular shrine in Abae in Phocis, where he bore the toponymic epithet Abaeus (, Apollon Abaios), was important enough to be consulted by Croesus.His oracular shrines include: Abae in Phocis. Bassae in the Peloponnese. At Clarus, on the west coast of Asia Minor; as at Delphi a holy spring which gave off a pneuma, from which the priests drank. In Corinth, the Oracle of Corinth came from the town of Tenea, from prisoners supposedly taken in the Trojan War. At Khyrse, in Troad, the temple was built for Apollo Smintheus. In Delos, there was an oracle to the Delian Apollo, during summer. The Hieron (Sanctuary) of Apollo adjacent to the Sacred Lake, was the place where the god was said to have been born. In Delphi, the Pythia became filled with the pneuma of Apollo, said to come from a spring inside the Adyton. In Didyma, an oracle on the coast of Anatolia, south west of Lydian (Luwian) Sardis, in which priests from the lineage of the Branchidae received inspiration by drinking from a healing spring located in the temple. Was believed to have been founded by Branchus, son or lover of Apollo. In Hierapolis Bambyce, Syria (modern Manbij), according to the treatise De Dea Syria, the sanctuary of the Syrian Goddess contained a robed and bearded image of Apollo. Divination was based on spontaneous movements of this image. At Patara, in Lycia, there was a seasonal winter oracle of Apollo, said to have been the place where the god went from Delos. As at Delphi the oracle at Patara was a woman. In Segesta in Sicily.Oracles were also given by sons of Apollo. In Oropus, north of Athens, the oracle Amphiaraus, was said to be the son of Apollo; Oropus also had a sacred spring. in Labadea, east of Delphi, Trophonius, another son of Apollo, killed his brother and fled to the cave where he was also afterwards consulted as an oracle.Temples of ApolloMany temples were dedicated to Apollo in Greece and the Greek colonies. They show the spread of the cult of Apollo and the evolution of the Greek architecture, which was mostly based on the rightness of form and on mathematical relations. Some of the earliest temples, especially in Crete, do not belong to any Greek order. It seems that the first peripteral temples were rectangular wooden structures. The different wooden elements were considered divine, and their forms were preserved in the marble or stone elements of the temples of Doric order. The Greeks used standard types because they believed that the world of objects was a series of typical forms which could be represented in several instances. The temples should be canonic, and the architects were trying to achieve this esthetic perfection. From the earliest times there were certain rules strictly observed in rectangular peripteral and prostyle buildings. The first buildings were built narrowly in order to hold the roof, and when the dimensions changed some mathematical relations became necessary in order to keep the original forms. This probably influenced the theory of numbers of Pythagoras, who believed that behind the appearance of things there was the permanent principle of mathematics.The Doric order dominated during the 6th and the 5th century BC but there was a mathematical problem regarding the position of the triglyphs, which couldn't be solved without changing the original forms. The order was almost abandoned for the Ionic order, but the Ionic capital also posed an insoluble problem at the corner of a temple. Both orders were abandoned for the Corinthian order gradually during the Hellenistic age and under Rome.The most important temples are:Greek templesThebes, Greece: The oldest temple probably dedicated to Apollo Ismenius was built in the 9th century B.C. It seems that it was a curvilinear building. The Doric temple was built in the early 7th century B.C., but only some small parts have been found A festival called Daphnephoria was celebrated every ninth year in honour of Apollo Ismenius (or Galaxius). The people held laurel branches (daphnai), and at the head of the procession walked a youth (chosen priest of Apollo), who was called "daphnephoros".Eretria: According to the Homeric hymn to Apollo, the god arrived to the plain, seeking for a location to establish its oracle. The first temple of Apollo Daphnephoros, "Apollo, laurel-bearer", or "carrying off Daphne", is dated to 800 B.C. The temple was curvilinear hecatombedon (a hundred feet). In a smaller building were kept the bases of the laurel branches which were used for the first building. Another temple probably peripteral was built in the 7th century B.C., with an inner row of wooden columns over its Geometric predecessor. It was rebuilt peripteral around 510 B.C., with the stylobate measuring 21,00 x 43,00 m. The number of pteron column was 6 x 14. Dreros (Crete). The temple of Apollo Delphinios dates from the 7th century B.C., or probably from the middle of the 8th century B.C. According to the legend, Apollo appeared as a dolphin, and carried Cretan priests to the port of Delphi. The dimensions of the plan are 10,70 x 24,00 m and the building was not peripteral. It contains column-bases of the Minoan type, which may be considered as the predecessors of the Doric columns.Gortyn (Crete). A temple of Pythian Apollo, was built in the 7th century B.C. The plan measured 19,00 x 16,70 m and it was not peripteral. The walls were solid, made from limestone, and there was single door on the east side.Thermon (West Greece): The Doric temple of Apollo Thermios, was built in the middle of the 7th century B.C. It was built on an older curvilinear building dating perhaps from the 10th century B.C., on which a peristyle was added. The temple was narrow, and the number of pteron columns (probably wooden) was 5 x 15. There was a single row of inner columns. It measures 12.13 x 38.23 m at the stylobate, which was made from stones. Corinth: A Doric temple was built in the 6th century B.C. The temple's stylobate measures 21.36 x 53.30 m, and the number of pteron columns was 6 x 15. There was a double row of inner columns. The style is similar with the Temple of Alcmeonidae at Delphi. The Corinthians were considered to be the inventors of the Doric order. Napes (Lesbos): An Aeolic temple probably of Apollo Napaios was built in the 7th century B.C. Some special capitals with floral ornament have been found, which are called Aeolic, and it seems that they were borrowed from the East. Cyrene, Libya: The oldest Doric temple of Apollo was built in c. 600 B.C. The number of pteron columns was 6 x 11, and it measures 16.75 x 30.05 m at the stylobate. There was a double row of sixteen inner columns on stylobates. The capitals were made from stone. Naukratis: An Ionic temple was built in the early 6th century B.C. Only some fragments have been found and the earlier, made from limestone, are identified among the oldest of the Ionic order.Syracuse, Sicily: A Doric temple was built at the beginning of the 6th century B.C. The temple's stylobate measures 21.47 x 55.36 m and the number of pteron columns was 6 x 17. It was the first temple in Greek west built completely out of stone. A second row of columns were added, obtaining the effect of an inner porch. Selinus (Sicily):The Doric Temple C dates from 550 B.C., and it was probably dedicated to Apollo. The temple's stylobate measures 10.48 x 41.63 m and the number of pteron columns was 6 x 17. There was portico with a second row of columns, which is also attested for the temple at Syracuse.Delphi: The first temple dedicated to Apollo, was built in the 7th century B.C. According to the legend, it was wooden made of laurel branches. The "Temple of Alcmeonidae" was built in c. 513 B.C. and it is the oldest Doric temple with significant marble elements. The temple's stylobate measures 21.65 x 58.00 m, and the number of pteron columns as 6 x 15. A fest similar with Apollo's fest at Thebes, Greece was celebrated every nine years. A boy was sent to the temple, who walked on the sacred road and returned carrying a laurel branch (dopnephoros). The maidens participated with joyful songs. Chios: An Ionic temple of Apollo Phanaios was built at the end of the 6th century B.C. Only some small parts have been found and the capitals had floral ornament. Abae (Phocis). The temple was destroyed by the Persians in the invasion of Xerxes in 480 B.C., and later by the Boeotians. It was rebuilt by Hadrian. The oracle was in use from early Mycenaean times to the Roman period, and shows the continuity of Mycenaean and Classical Greek religion. Bassae (Peloponnesus):A temple dedicated to Apollo Epikourios ("Apollo the helper"), was built in 430 B.C. and it was designed by Iktinos.It combined Doric and Ionic elements, and the earliest use of column with a Corinthian capital in the middle. The temple is of a relatively modest size, with the stylobate measuring 14.5 x 38.3 metres containing a Doric peristyle of 6 x 15 columns. The roof left a central space open to admit light and air.Delos: A temple probably dedicated to Apollo and not peripteral, was built in the late 7th century B.C., with a plan measuring 10,00 x 15,60 m. The Doric Great temple of Apollo, was built in c. 475 B.C. The temple's stylobate measures 13.72 x 29.78 m, and the number of pteron columns as 6 x 13. Marble was extensively used.Ambracia: A Doric peripteral temple dedicated to Apollo Pythios Sotir was built in 500 B.C., and It is lying at the centre of the Greek city Arta. Only some parts have been found, and it seems that the temple was built on earlier sanctuaries dedicated to Apollo. The temple measures 20,75 x 44,00 m at the stylobate. The foundation which supported the statue of the god, still exists.Didyma (near Miletus): The gigantic Ionic temple of Apollo Didymaios started around 540 B.C. The construction ceased and then it was restarted in 330 B.C. The temple is dipteral, with an outer row of 10 x 21 columns, and it measures 28.90 x 80.75 m at the stylobate.Clarus (near ancient Colophon): According to the legend, the famous seer Calchas, on his return from Troy, came to Clarus. He challenged the seer Mopsus, and died when he lost. The Doric temple of Apollo Clarius was probably built in the 3rd century B.C., and it was peripteral with 6 x 11 columns. It was reconstructed at the end of the Hellenistic period, and later from the emperor Hadrian but Pausanias claims that it was still incomplete in the 2nd century B.C.Hamaxitus (Troad): In Iliad, Chryses the priest of Apollo, addresses the god with the epithet Smintheus (Lord of Mice), related with the god's ancient role as bringer of the disease (plague). Recent excavations indicate that the Hellenistic temple of Apollo Smintheus was constructed at 150–125 B.C., but the symbol of the mouse god was used on coinage probably from the 4th century B.C. The temple measures 40,00 x 23,00 m at the stylobate, and the number of pteron columns was 8 x 14.Pythion (), this was the name of a shrine of Apollo at Athens near the Ilisos river. It was created by Peisistratos, and tripods placed there by those who had won in the cyclic chorus at the Thargelia.Setae (Lydia): The temple of Apollo Aksyros located in the city.Apollonia Pontica: There were two temples of Apollo Healer in the city. One from the Late Archaic period and the other from the Early Classical period.Ikaros island in the Persian Gulf (modern Failaka Island): There was a temple of Apollo on the island.Etruscan and Roman templesVeii (Etruria): The temple of Apollo was built in the late 6th century B.C. and it indicates the spread of Apollo's culture (Aplu) in Etruria. There was a prostyle porch, which is called Tuscan, and a triple cella 18,50 m wide.Falerii Veteres (Etruria): A temple of Apollo was built probably in the 4th-3rd century B.C. Parts of a teraccotta capital, and a teraccotta base have been found. It seems that the Etruscan columns were derived from the archaic Doric. A cult of Apollo Soranus is attested by one inscription found near Falerii.Pompeii (Italy): The cult of Apollo was widespread in the region of Campania since the 6th century B.C. The temple was built in 120 B.V, but its beginnings lie in the 6th century B.C. It was reconstructed after an earthquake in A.D. 63. It demonstrates a mixing of styles which formed the basis of Roman architecture. The columns in front of the cella formed a Tuscan prostyle porch, and the cella is situated unusually far back. The peripteral colonnade of 48 Ionic columns was placed in such a way that the emphasis was given to the front side. Rome: The temple of Apollo Sosianus and the temple of Apollo Medicus. The first temple building dates to 431 B.C., and was dedicated to Apollo Medicus (the doctor), after a plague of 433 B.C. It was rebuilt by Gaius Sosius, probably in 34 B.C. Only three columns with Corinthian capitals exist today. It seems that the cult of Apollo had existed in this area since at least to the mid-5th century B.C.Rome:The temple of Apollo Palatinus was located on the Palatine hill within the sacred boundary of the city. It was dedicated by Augustus on 28 B.C. The façade of the original temple was Ionic and it was constructed from solid blocks of marble. Many famous statues by Greek masters were on display in and around the temple, including a marble statue of the god at the entrance and a statue of Apollo in the cella.Melite (modern Mdina, Malta): A Temple of Apollo was built in the city in the 2nd century A.D. Its remains were discovered in the 18th century, and many of its architectural fragments were dispersed among private collections or reworked into new sculptures. Parts of the temple's podium were rediscovered in 2002.MythologyApollo appears often in the myths, plays and hymns. As Zeus' favorite son, Apollo had direct access to the mind of Zeus and was willing to reveal this knowledge to humans. A divinity beyond human comprehension, he appears both as a beneficial and a wrathful god.BirthApollo was the son of Zeus, the king of the gods, and Leto, his previous wife or one of his mistresses. Growing up, Apollo was nursed by the nymphs Korythalia and Aletheia, the personification of truth.When Zeus' wife Hera discovered that Leto was pregnant, she banned Leto from giving birth on terra firma. Leto sought shelter in many lands, only to be rejected by them. Finally, the voice of unborn Apollo informed his mother about a floating island named Delos that had once been Asteria, Leto's own sister. Since it was neither a mainland nor an island, Leto was readily welcomed there and gave birth to her children under a palm tree. All the goddesses except Hera were present to witness the event. It is also stated that Hera kidnapped Eileithyia, the goddess of childbirth, to prevent Leto from going into labor. The other gods tricked Hera into letting her go by offering her a necklace of amber 9 yards (8.2 m) long.When Apollo was born, clutching a golden sword, everything on Delos turned into gold and the island was filled with ambrosial fragrance. Swans circled the island seven times and the nymphs sang in delight. He was washed clean by the goddesses who then covered him in white garment and fastened golden bands around him. Since Leto was unable to feed him, Themis, the goddess of divine law, fed him with nectar, or ambrosia. Upon tasting the divine food, Apollo broke free of the bands fastened onto him and declared that he would be the master of lyre and archery, and interpret the will of Zeus to humankind. Zeus, who had calmed Hera by then, came and adorned his son with a golden headband.Apollo's birth fixed the floating Delos to the earth. Leto promised that her son would be always favorable towards the Delians. According to some, Apollo secured Delos to the bottom of the ocean after some time. This island became sacred to Apollo and was one of the major cult centres of the god.Apollo was born on the seventh day (, hebdomagenes) of the month Thargelion—according to Delian tradition—or of the month Bysios—according to Delphian tradition. The seventh and twentieth, the days of the new and full moon, were ever afterwards held sacred to him. Mythographers agree that Artemis was born first and subsequently assisted with the birth of Apollo or was born on the island of Ortygia then helped Leto cross the sea to Delos the next day to give birth to Apollo.HyperboreaHyperborea, the mystical land of eternal spring, venerated Apollo above all the gods. The Hyperboreans always sang and danced in his honor and hosted Pythian games. There, a vast forest of beautiful trees was called "the garden of Apollo". Apollo spent the winter months among the Hyperboreans. His absence from the world caused coldness and this was marked as his annual death. No prophecies were issued during this time. He returned to the world during the beginning of the spring. The Theophania festival was held in Delphi to celebrate his return.It is said that Leto came to Delos from Hyperborea accompanied by a pack of wolves. Henceforth, Hyperborea became Apollo's winter home and wolves became sacred to him. His intimate connection to wolves is evident from his epithet Lyceus, meaning wolf-like. But Apollo was also the wolf-slayer in his role as the god who protected flocks from predators. The Hyperborean worship of Apollo bears the strongest marks of Apollo being worshipped as the sun god. Shamanistic elements in Apollo's cult are often liked to his Hyperborean origin, and he is likewise speculated to have originated as a solar shaman. Shamans like Abaris and Aristeas were also the followers of Apollo, who hailed from Hyperborea.In myths, the tears of amber Apollo shed when his son Asclepius died became the waters of the river Eridanos, which surrounded Hyperborea. Apollo also buried in Hyperborea the arrow which he had used to kill the Cyclopes. He later gave this arrow to Abaris.Childhood and youthAs a child, Apollo is said to have built a foundation and an altar on Delos using the horns of the goats that his sister Artemis hunted. Since he learnt the art of building when young, he later came to be known as Archegetes, the founder (of towns) and god who guided men to build new cities. From his father Zeus, Apollo had also received a golden chariot drawn by swans.In his early years when Apollo spent his time herding cows, he was reared by Thriae, the bee nymphs, who trained him and enhanced his prophetic skills. Apollo is also said to have invented the lyre, and along with Artemis, the art of archery. He then taught to the humans the art of healing and archery. Phoebe, his grandmother, gave the oracular shrine of Delphi to Apollo as a birthday gift. Themis inspired him to be the oracular voice of Delphi thereon.PythonPython, a chthonic serpent-dragon, was a child of Gaia and the guardian of the Delphic Oracle, whose death was foretold by Apollo when he was still in Leto's womb. Python was the nurse of the giant Typhon. In most of the traditions, Apollo was still a child when he killed Python.Python was sent by Hera to hunt the pregnant Leto to death, and had assaulted her. To avenge the trouble given to his mother, Apollo went in search of Python and killed it in the sacred cave at Delphi with the bow and arrows that he had received from Hephaestus. The Delphian nymphs who were present encouraged Apollo during the battle with the cry "Hie Paean". After Apollo was victorious, they also brought him gifts and gave the Corycian cave to him. According to Homer, Apollo had encountered and killed the Python when he was looking for a place to establish his shrine.According to another version, when Leto was in Delphi, Python had attacked her. Apollo defended his mother and killed Python. Euripides in his Iphigenia in Aulis gives an account of his fight with Python and the event's aftermath. You killed him, o Phoebus, while still a baby, still leaping in the arms of your dear mother, and you entered the holy shrine, and sat on the golden tripod, on your truthful throne distributing prophecies from the gods to mortals.A detailed account of Apollo's conflict with Gaia and Zeus' intervention on behalf of his young son is also given. But when Apollo came and sent Themis, the child of Earth, away from the holy oracle of Pytho, Earth gave birth to dream visions of the night; and they told to the cities of men the present, and what will happen in the future, through dark beds of sleep on the ground; and so Earth took the office of prophecy away from Phoebus, in envy, because of her daughter. The lord made his swift way to Olympus and wound his baby hands around Zeus, asking him to take the wrath of the earth goddess from the Pythian home. Zeus smiled, that the child so quickly came to ask for worship that pays in gold. He shook his locks of hair, put an end to the night voices, and took away from mortals the truth that appears in darkness, and gave the privilege back again to Loxias.Apollo also demanded that all other methods of divination be made inferior to his, a wish that Zeus granted him readily. Because of this, Athena, who had been practicing divination by throwing pebbles, cast her pebbles away in displeasure.However, Apollo had committed a blood murder and had to be purified. Because Python was a child of Gaia, Gaia wanted Apollo to be banished to Tartarus as a punishment. Zeus didn't agree and instead exiled his son from Olympus, and instructed him to get purified. Apollo had to serve as a slave for nine years. After the servitude was over, as per his father's order, he travelled to the Vale of Tempe to bath in waters of Peneus. There Zeus himself performed purificatory rites on Apollo. Purified, Apollo was escorted by his half sister Athena to Delphi where the oracular shrine was finally handed over to him by Gaia. According to a variation, Apollo had also travelled to Crete, where Carmanor purified him. Apollo later established the Pythian games to appropriate Gaia. Henceforth, Apollo became the god who cleansed himself from the sin of murder and, made men aware of their guilt and purified them.Soon after, Zeus instructed Apollo to go to Delphi and establish his law. But Apollo, disobeying his father, went to the land of Hyperborea and stayed there for a year. He returned only after the Delphians sang hymns to him and pleaded him to come back. Zeus, pleased with his son's integrity, gave Apollo the seat next to him on his right side. He also gave to Apollo various gifts, like a golden tripod, a golden bow and arrows, a golden chariot and the city of Delphi.Soon after his return, Apollo needed to recruit people to Delphi. So, when he spotted a ship sailing from Crete, he sprang aboard in the form of a dolphin. The crew was awed into submission and followed a course that led the ship to Delphi. There Apollo revealed himself as a god. Initiating them to his service, he instructed them to keep righteousness in their hearts. The Pythia was Apollo's high priestess and his mouthpiece through whom he gave prophecies. Pythia is arguably the constant favorite of Apollo among the mortals.TityosHera once again sent another giant, Tityos to rape Leto. This time Apollo shot him with his arrows and attacked him with his golden sword. According to other version, Artemis also aided him in protecting their mother by attacking Tityos with her arrows. After the battle Zeus finally relented his aid and hurled Tityos down to Tartarus. There, he was pegged to the rock floor, covering an area of , where a pair of vultures feasted daily on his liver.AdmetusAdmetus was the king of Pherae, who was known for his hospitality. When Apollo was exiled from Olympus for killing Python, he served as a herdsman under Admetus, who was then young and unmarried. Apollo is said to have shared a romantic relationship with Admetus during his stay. After completing his years of servitude, Apollo went back to Olympus as a god.Because Admetus had treated Apollo well, the god conferred great benefits on him in return. Apollo's mere presence is said to have made the cattle give birth to twins. Apollo helped Admetus win the hand of Alcestis, the daughter of King Pelias, by taming a lion and a boar to draw Admetus' chariot. He was present during their wedding to give his blessings. When Admetus angered the goddess Artemis by forgetting to give her the due offerings, Apollo came to the rescue and calmed his sister. When Apollo learnt of Admetus' untimely death, he convinced or tricked the Fates into letting Admetus live past his time.According to another version, or perhaps some years later, when Zeus struck down Apollo's son Asclepius with a lightning bolt for resurrecting the dead, Apollo in revenge killed the Cyclopes, who had fashioned the bolt for Zeus. Apollo would have been banished to Tartarus for this, but his mother Leto intervened, and reminding Zeus of their old love, pleaded him not to kill their son. Zeus obliged and sentenced Apollo to one year of hard labor once again under Admetus.The love between Apollo and Admetus was a favored topic of Roman poets like Ovid and Servius.NiobeThe fate of Niobe was prophesied by Apollo while he was still in Leto's womb. Niobe was the queen of Thebes and wife of Amphion. She displayed hubris when she boasted that she was superior to Leto because she had fourteen children (Niobids), seven male and seven female, while Leto had only two. She further mocked Apollo's effeminate appearance and Artemis' manly appearance. Leto, insulted by this, told her children to punish Niobe. Accordingly, Apollo killed Niobe's sons, and Artemis her daughters. According to some versions of the myth, among the Niobids, Chloris and her brother Amyclas were not killed because they prayed to Leto. Amphion, at the sight of his dead sons, either killed himself or was killed by Apollo after swearing revenge.A devastated Niobe fled to Mount Sipylos in Asia Minor and turned into stone as she wept. Her tears formed the river Achelous. Zeus had turned all the people of Thebes to stone and so no one buried the Niobids until the ninth day after their death, when the gods themselves entombed them.When Chloris married and had children, Apollo granted her son Nestor the years he had taken away from the Niobids. Hence, Nestor was able to live for 3 generations.Building the walls of Troy Once Apollo and Poseidon served under the Trojan king Laomedon in accordance to Zeus' words. Apollodorus states that the gods willingly went to the king disguised as humans in order to check his hubris. Apollo guarded the cattle of Laomedon in the valleys of mount Ida, while Poseidon built the walls of Troy. Other versions make both Apollo and Poseidon the builders of the wall. In Ovid's account, Apollo completes his task by playing his tunes on his lyre.In Pindar's odes, the gods took a mortal named Aeacus as their assistant. When the work was completed, three snakes rushed against the wall, and though the two that attacked the sections of the wall built by the gods fell down dead, the third forced its way into the city through the portion of the wall built by Aeacus. Apollo immediately prophesied that Troy would fall at the hands of Aeacus's descendants, the Aeacidae (i.e. his son Telamon joined Heracles when he sieged the city during Laomedon's rule. Later, his great grandson Neoptolemus was present in the wooden horse that lead to the downfall of Troy).However, the king not only refused to give the gods the wages he had promised, but also threatened to bind their feet and hands, and sell them as slaves. Angered by the unpaid labour and the insults, Apollo infected the city with a pestilence and Posedion sent the sea monster Cetus. To deliver the city from it, Laomedon had to sacrifice his daughter Hesione (who would later be saved by Heracles).During his stay in Troy, Apollo had a lover named Ourea, who was a nymph and daughter of Poseidon. Together they had a son named Ileus, whom Apollo loved dearly.Trojan WarApollo sided with the Trojans during the Trojan War waged by the Greeks against the Trojans.During the war, the Greek king Agamemnon captured Chryseis, the daughter of Apollo's priest Chryses, and refused to return her. Angered by this, Apollo shot arrows infected with the plague into the Greek encampment. He demanded that they return the girl, and the Achaeans (Greeks) complied, indirectly causing the anger of Achilles, which is the theme of the Iliad.Receiving the aegis from Zeus, Apollo entered the battlefield as per his father's command, causing great terror to the enemy with his war cry. He pushed the Greeks back and destroyed many of the soldiers. He is described as "the rouser of armies" because he rallied the Trojan army when they were falling apart.When Zeus allowed the other gods to get involved in the war, Apollo was provoked by Poseidon to a duel. However, Apollo declined to fight him, saying that he wouldn't fight his uncle for the sake of mortals.When the Greek hero Diomedes injured the Trojan hero Aeneas, Aphrodite tried to rescue him, but Diomedes injured her as well. Apollo then enveloped Aeneas in a cloud to protect him. He repelled the attacks Diomedes made on him and gave the hero a stern warning to abstain himself from attacking a god. Aeneas was then taken to Pergamos, a sacred spot in Troy, where he was healed.After the death of Sarpedon, a son of Zeus, Apollo rescued the corpse from the battlefield as per his father's wish and cleaned it. He then gave it to Sleep (Hypnos) and Death (Thanatos). Apollo had also once convinced Athena to stop the war for that day, so that the warriors can relieve themselves for a while.The Trojan hero Hector (who, according to some, was the god's own son by Hecuba) was favored by Apollo. When he got severely injured, Apollo healed him and encouraged him to take up his arms. During a duel with Achilles, when Hector was about to lose, Apollo hid Hector in a cloud of mist to save him. When the Greek warrior Patroclus tried to get into the fort of Troy, he was stopped by Apollo. Encouraging Hector to attack Patroclus, Apollo stripped the armour of the Greek warrior and broke his weapons. Patroclus was eventually killed by Hector. At last, after Hector's fated death, Apollo protected his corpse from Achilles' attempt to mutilate it by creating a magical cloud over the corpse.Apollo held a grudge against Achilles throughout the war because Achilles had murdered his son Tenes before the war began and brutally assassinated his son Troilus in his own temple. Not only did Apollo save Hector from Achilles, he also tricked Achilles by disguising himself as a Trojan warrior and driving him away from the gates. He foiled Achilles' attempt to mutilate Hector's dead body.Finally, Apollo caused Achilles' death by guiding an arrow shot by Paris into Achilles' heel. In some versions, Apollo himself killed Achilles by taking the disguise of Paris.Apollo helped many Trojan warriors, including Agenor, Polydamas, Glaucus in the battlefield. Though he greatly favored the Trojans, Apollo was bound to follow the orders of Zeus and served his father loyally during the war.HeraclesAfter Heracles (then named Alcides) was struck with madness and killed his family, he sought to purify himself and consulted the oracle of Apollo. Apollo, through the Pythia, commanded him to serve king Eurystheus for twelve years and complete the ten tasks the king would give him. Only then would Alcides be absolved of his sin. Apollo also renamed him as Heracles.To complete his third task, Heracles had to capture the Ceryneian Hind, a hind sacred to Artemis, and bring back it alive. After chasing the hind for one year, the animal eventually got tired, and when it tried crossing the river Ladon, Heracles captured it. While he was taking it back, he was confronted by Apollo and Artemis, who were angered at Heracles for this act. However, Heracles soothed the goddess and explained his situation to her. After much pleading, Artemis permitted him to take the hind and told him to return it later.After he was freed from his servitude to Eurystheus, Heracles fell in conflict with Iphytus, a prince of Oechalia, and murdered him. Soon after, he contracted a terrible disease. He consulted the oracle of Apollo once again, in hope of ridding himself of the disease. The Pythia, however, denied to give any prophesy. In anger, Heracles snatched the sacred tripod and started walking away, intending to start his own oracle. However, Apollo did not tolerate this and stopped Heracles; a duel ensued between them. Artemis rushed to support Apollo, while Athena supported Heracles. Soon, Zeus threw his thunderbolt between the fighting brothers and separated them. He reprimanded Heracles for this act of violation and asked Apollo to give a solution to Heracles. Apollo then ordered the hero to serve under Omphale, queen of Lydia for one year in order to purify himself.PeriphasPeriphas was an Attican king and a priest of Apollo. He was noble, just and rich. He did all his duties justly. Because of this people were very fond of him and started honouring him to the same extent as Zeus. At one point, they worshipped Periphas in place of Zeus and set up shrines and temples for him. This annoyed Zeus, who decided to annihilate the entire family of Periphas. But because he was a just king and a good devotee, Apollo intervened and requested his father to spare Periphas. Zeus considered Apollo's words and agreed to let him live. But he metamorphosed Periphas into an eagle and made the eagle the king of birds. When Periphas' wife requested Zeus to let her stay with her husband, Zeus turned her into a vulture and fulfilled her wish.Plato's concept of soulmatesA long time ago, there were three kinds of human beings: male, descended from the sun; female, descended from the earth; and androgynous, descended from the moon. Each human being was completely round, with four arms and fours legs, two identical faces on opposite sides of a head with four ears, and all else to match. They were powerful and unruly. Otis and Ephialtes even dared to scale Mount Olympus.To check their insolence, Zeus devised a plan to humble them and improve their manners instead of completely destroying them. He cut them all in two and asked Apollo to make necessary repairs, giving humans the individual shape they still have now. Apollo turned their heads and necks around towards their wounds, he pulled together their skin at the abdomen, and sewed the skin together at the middle of it. This is what we call navel today. He smoothened the wrinkles and shaped the chest. But he made sure to leave a few wrinkles on the abdomen and around the navel so that they might be reminded of their punishment."As he [Zeus] cut them one after another, he bade Apollo give the face and the half of the neck a turn... Apollo was also bidden to heal their wounds and compose their forms. So Apollo gave a turn to the face and pulled the skin from the sides all over that which in our language is called the belly, like the purses which draw in, and he made one mouth at the centre [of the belly] which he fastened in a knot (the same which is called the navel); he also moulded the breast and took out most of the wrinkles, much as a shoemaker might smooth leather upon a last; he left a few wrinkles, however, in the region of the belly and navel, as a memorial of the primeval state.Nurturer of the youngApollo Kourotrophos is the god who nurtures and protects children and the young, especially boys. He oversees their education and their passage into adulthood. Education is said to have originated from Apollo and the Muses. Many myths have him train his children. It was a custom for boys to cut and dedicate their long hair to Apollo after reaching adulthood.Chiron, the abandoned centaur, was fostered by Apollo, who instructed him in medicine, prophecy, archery and more. Chiron would later become a great teacher himself.Asclepius in his childhood gained much knowledge pertaining to medicinal arts by his father. However, he was later entrusted to Chiron for further education.Anius, Apollo's son by Rhoeo, was abandoned by his mother soon after his birth. Apollo brought him up and educated him in mantic arts. Anius later became the priest of Apollo and the king of Delos.Iamus was the son of Apollo and Evadne. When Evadne went into labour, Apollo sent the Moirai to assist his lover. After the child was born, Apollo sent snakes to feed the child some honey. When Iamus reached the age of education, Apollo took him to Olympia and taught him many arts, including the ability to understand and explain the languages of birds.Idmon was educated by Apollo to be a seer. Even though he foresaw his death that would happen in his journey with the Argonauts, he embraced his destiny and died a brave death. To commemorate his son's bravery, Apollo commanded Boeotians to build a town around the tomb of the hero, and to honor him.Apollo adopted Carnus, the abandoned son of Zeus and Europa. He reared the child with the help of his mother Leto and educated him to be a seer.When his son Melaneus reached the age of marriage, Apollo asked the princess Stratonice to be his son's bride and carried her away from her home when she agreed.Apollo saved a shepherd boy (name unknown) from death in a large deep cave, by the means of vultures. To thank him, the shepherd built Apollo a temple under the name Vulturius.God of musicImmediately after his birth, Apollo demanded a lyre and invented the paean, thus becoming the god of music. As the divine singer, he is the patron of poets, singers and musicians. The invention of string music is attributed to him. Plato said that the innate ability of humans to take delight in music, rhythm and harmony is the gift of Apollo and the Muses. According to Socrates, ancient Greeks believed that Apollo is the god who directs the harmony and makes all things move together, both for the gods and the humans. For this reason, he was called Homopolon before the Homo was replaced by A. Apollo's harmonious music delivered people from their pain, and hence, like Dionysus, he is also called the liberator. The swans, which were considered to be the most musical among the birds, were believed to be the "singers of Apollo". They are Apollo's sacred birds and acted as his vehicle during his travel to Hyperborea. Aelian says that when the singers would sing hymns to Apollo, the swans would join the chant in unison.Among the Pythagoreans, the study of mathematics and music were connected to the worship of Apollo, their principal deity. Their belief was that the music purifies the soul, just as medicine purifies the body. They also believed that music was delegated to the same mathematical laws of harmony as the mechanics of the cosmos, evolving into an idea known as the music of the spheres.Apollo appears as the companion of the Muses, and as Musagetes ("leader of Muses") he leads them in dance. They spend their time on Parnassus, which is one of their sacred places. Apollo is also the lover of the Muses and by them he became the father of famous musicians like Orpheus and Linus.Apollo is often found delighting the immortal gods with his songs and music on the lyre. In his role as the god of banquets, he was always present to play music in weddings of the gods, like the marriage of Eros and Psyche, Peleus and Thetis. He is a frequent guest of the Bacchanalia, and many ancient ceramics depict him being at ease amidst the maenads and satyrs. Apollo also participated in musical contests when challenged by others. He was the victor in all those contests, but he tended to punish his opponents severely for their hubris.Apollo's lyreThe invention of lyre is attributed either to Hermes or to Apollo himself. Distinctions have been made that Hermes invented lyre made of tortoise shell, whereas the lyre Apollo invented was a regular lyre.Myths tell that the infant Hermes stole a number of Apollo's cows and took them to a cave in the woods near Pylos, covering their tracks. In the cave, he found a tortoise and killed it, then removed the insides. He used one of the cow's intestines and the tortoise shell and made his lyre.Upon discovering the theft, Apollo confronted Hermes and asked him to return his cattle. When Hermes acted innocent, Apollo took the matter to Zeus. Zeus, having seen the events, sided with Apollo, and ordered Hermes to return the cattle. Hermes then began to play music on the lyre he had invented. Apollo fell in love with the instrument and offered to exchange the cattle for the lyre. Hence, Apollo then became the master of the lyre.According to other versions, Apollo had invented the lyre himself, whose strings he tore in repenting of the excess punishment he had given to Marsyas. Hermes' lyre, therefore, would be a reinvention.Contest with PanOnce Pan had the audacity to compare his music with that of Apollo and to challenge the god of music to a contest. The mountain-god Tmolus was chosen to umpire. Pan blew on his pipes, and with his rustic melody gave great satisfaction to himself and his faithful follower, Midas, who happened to be present. Then, Apollo struck the strings of his lyre. It was so beautiful that Tmolus at once awarded the victory to Apollo, and everyone was pleased with the judgement. Only Midas dissented and questioned the justice of the award. Apollo did not want to suffer such a depraved pair of ears any longer, and caused them to become the ears of a donkey.Contest with MarsyasMarsyas was a satyr who was punished by Apollo for his hubris. He had found an aulos on the ground, tossed away after being invented by Athena because it made her cheeks puffy. Athena had also placed a curse upon the instrument, that whoever would pick it up would be severely punished. When Marsyas played the flute, everyone became frenzied with joy. This led Marsyas to think that he was better than Apollo, and he challenged the god to a musical contest. The contest was judged by the Muses, or the nymphs of Nysa. Athena was also present to witness the contest.Marsyas taunted Apollo for "wearing his hair long, for having a fair face and smooth body, for his skill in so many arts". He also further said,'His [Apollo] hair is smooth and made into tufts and curls that fall about his brow and hang before his face. His body is fair from head to foot, his limbs shine bright, his tongue gives oracles, and he is equally eloquent in prose or verse, propose which you will. What of his robes so fine in texture, so soft to the touch, aglow with purple? What of his lyre that flashes gold, gleams white with ivory, and shimmers with rainbow gems? What of his song, so cunning and so sweet? Nay, all these allurements suit with naught save luxury. To virtue they bring shame alone!'The Muses and Athena sniggered at this comment. The contestants agreed to take turns displaying their skills and the rule was that the victor could "do whatever he wanted" to the loser.According to one account, after the first round, they both were deemed equal by the Nysiads. But in the next round, Apollo decided to play on his lyre and add his melodious voice to his performance. Marsyas argued against this, saying that Apollo would have an advantage and accused Apollo of cheating. But Apollo replied that since Marsyas played the flute, which needed air blown from the throat, it was similar to singing, and that either they both should get an equal chance to combine their skills or none of them should use their mouths at all. The nymphs decided that Apollo's argument was just. Apollo then played his lyre and sang at the same time, mesmerising the audience. Marsyas could not do this. Apollo was declared the winner and, angered with Marsyas' haughtiness and his accusations, decided to flay the satyr.According to another account, Marsyas played his flute out of tune at one point and accepted his defeat. Out of shame, he assigned to himself the punishment of being skinned for a wine sack. Another variation is that Apollo played his instrument upside down. Marsyas could not do this with his instrument. So the Muses who were the judges declared Apollo the winner. Apollo hung Marsyas from a tree to flay him.Apollo flayed the limbs of Marsyas alive in a cave near Celaenae in Phrygia for his hubris to challenge a god. He then gave the rest of his body for proper burial and nailed Marsyas' flayed skin to a nearby pine-tree as a lesson to the others. Marsyas' blood turned into the river Marsyas. But Apollo soon repented and being distressed at what he had done, he tore the strings of his lyre and threw it away. The lyre was later discovered by the Muses and Apollo's sons Linus and Orpheus. The Muses fixed the middle string, Linus the string struck with the forefinger, and Orpheus the lowest string and the one next to it. They took it back to Apollo, but the god, who had decided to stay away from music for a while, laid away both the lyre and the pipes at Delphi and joined Cybele in her wanderings to as far as Hyperborea.Contest with CinyrasCinyras was a ruler of Cyprus, who was a friend of Agamemnon. Cinyras promised to assist Agamemnon in the Trojan war, but did not keep his promise. Agamemnon cursed Cinyras. He invoked Apollo and asked the god to avenge the broken promise. Apollo then had a lyre-playing contest with Cinyras, and defeated him. Either Cinyras committed suicide when he lost, or was killed by Apollo.Patron of sailorsApollo functions as the patron and protector of sailors, one of the duties he shares with Poseidon. In the myths, he is seen helping heroes who pray to him for safe journey.When Apollo spotted a ship of Cretan sailors that was caught in a storm, he quickly assumed the shape of a dolphin and guided their ship safely to Delphi.When the Argonauts faced a terrible storm, Jason prayed to his patron, Apollo, to help them. Apollo used his bow and golden arrow to shed light upon an island, where the Argonauts soon took shelter. This island was renamed "Anaphe", which means "He revealed it".Apollo helped the Greek hero Diomedes, to escape from a great tempest during his journey homeward. As a token of gratitude, Diomedes built a temple in honor of Apollo under the epithet Epibaterius ("the embarker").During the Trojan War, Odysseus came to the Trojan camp to return Chriseis, the daughter of Apollo's priest Chryses, and brought many offerings to Apollo. Pleased with this, Apollo sent gentle breezes that helped Odysseus return safely to the Greek camp.Arion was a poet who was kidnapped by some sailors for the rich prizes he possessed. Arion requested them to let him sing for the last time, to which the sailors consented. Arion began singing a song in praise of Apollo, seeking the god's help. Consequently, numerous dolphins surrounded the ship and when Arion jumped into the water, the dolphins carried him away safely.WarsTitanomachyOnce Hera, out of spite, aroused the Titans to war against Zeus and take away his throne. Accordingly, when the Titans tried to climb Mount Olympus, Zeus with the help of Apollo, Artemis and Athena, defeated them and cast them into tartarus.Trojan WarApollo played a pivotal role in the entire Trojan War. He sided with the Trojans, and sent a terrible plague to the Greek camp, which indirectly led to the conflict between Achilles and Agamemnon. He killed the Greek heroes Patroclus, Achilles, and numerous Greek soldiers. He also helped many Trojan heroes, the most important one being Hector. After the end of the war, Apollo and Poseidon together cleaned the remains of the city and the camps.Telegony warA war broke out between the Brygoi and the Thesprotians, who had the support of Odysseus. The gods Athena and Ares came to the battlefield and took sides. Athena helped the hero Odysseus while Ares fought alongside of the Brygoi. When Odysseus lost, Athena and Ares came into a direct duel. To stop the battling gods and the terror created by their battle, Apollo intervened and stopped the duel between them .Indian warWhen Zeus suggested that Dionysus defeat the Indians in order to earn a place among the gods, Dionysus declared war against the Indians and travelled to India along with his army of Bacchantes and satyrs. Among the warriors was Aristaeus, Apollo's son. Apollo armed his son with his own hands and gave him a bow and arrows and fitted a strong shield to his arm. After Zeus urged Apollo to join the war, he went to the battlefield. Seeing several of his nymphs and Aristaeus drowning in a river, he took them to safety and healed them. He taught Aristaeus more useful healing arts and sent him back to help the army of Dionysus.Theban warDuring the war between the sons of Oedipus, Apollo favored Amphiaraus, a seer and one of the leaders in the war. Though saddened that the seer was fated to be doomed in the war, Apollo made Amphiaraus' last hours glorious by "lighting his shield and his helm with starry gleam". When Hypseus tried to kill the hero by a spear, Apollo directed the spear towards the charioteer of Amphiaraus instead. Then Apollo himself replaced the charioteer and took the reins in his hands. He deflected many spears and arrows away them. He also killed many of the enemy warriors like Melaneus, Antiphus, Aetion, Polites and Lampus. At last when the moment of departure came, Apollo expressed his grief with tears in his eyes and bid farewell to Amphiaraus, who was soon engulfed by the Earth.Slaying of giantsApollo killed the giants Python and Tityos, who had assaulted his mother Leto.GigantomachyDuring the gigantomachy, Apollo and Heracles blinded the giant Ephialtes by shooting him in his eyes, Apollo shooting his left and Heracles his right. He also killed Porphyrion, the king of giants, using his bow and arrows.AloadaeThe Aloadae, namely Otis and Ephialtes, were twin giants who decided to wage war upon the gods. They attempted to storm Mt. Olympus by piling up mountains, and threatened to fill the sea with mountains and inundate dry land. They even dared to seek the hand of Hera and Artemis in marriage. Angered by this, Apollo killed them by shooting them with arrows. According to another tale, Apollo killed them by sending a deer between them; as they tried to kill it with their javelins, they accidentally stabbed each other and died.PhorbasPhorbas was a savage giant king of Phlegyas who was described as having swine like features. He wished to plunder Delphi for its wealth. He seized the roads to Delphi and started harassing the pilgrims. He captured the old people and children and sent them to his army to hold them for ransom. And he challenged the young and sturdy men to a match of boxing, only to cut their heads off when they would get defeated by him. He hung the chopped off heads to an oak tree. Finally, Apollo came to put an end to this cruelty. He entered a boxing contest with Phorbas and killed him with a single blow.Other storiesIn the first Olympic games, Apollo defeated Ares and became the victor in wrestling. He outran Hermes in the race and won first place.Apollo divides months into summer and winter. He rides on the back of a swan to the land of the Hyperboreans during the winter months, and the absence of warmth in winters is due to his departure. During his absence, Delphi was under the care of Dionysus, and no prophecies were given during winters.Molpadia and Parthenos Molpadia and Parthenos were the sisters of Rhoeo, a former lover of Apollo. One day, they were put in charge of watching their father's ancestral wine jar but they fell asleep while performing this duty. While they were asleep, the wine jar was broken by the swines their family kept. When the sisters woke up and saw what had happened, they threw themselves off a cliff in fear of their father's wrath. Apollo, who was passing by, caught them and carried them to two different cities in Chersonesus, Molpadia to Castabus and Parthenos to Bubastus. He turned them into goddesses and they both received divine honors. Molpadia's name was changed to Hemithea upon her deification.Prometheus Prometheus was the titan who was punished by Zeus for stealing fire. He was bound to a rock, where each day an eagle was sent to eat Prometheus' liver, which would then grow back overnight to be eaten again the next day. Seeing his plight, Apollo pleaded Zeus to release the kind Titan, while Artemis and Leto stood behind him with tears in their eyes. Zeus, moved by Apollo's words and the tears of the goddesses, finally sent Heracles to free Prometheus.The rock of Leukas Leukatas was believed to be a white colored rock jutting out from the island of Leukas into the sea. It was present in the sanctuary of Apollo Leukates. A leap from this rock was believed to have put an end to the longings of love.Once, Aphrodite fell deeply in love with Adonis, a young man of great beauty who was later accidentally killed by a boar. Heartbroken, Aphrodite wandered looking for the rock of Leukas. When she reached the sanctuary of Apollo in Argos, she confided in him her love and sorrow. Apollo then brought her to the rock of Leukas and asked her to throw herself from the top of the rock. She did so and was freed from her love. When she sought for the reason behind this, Apollo told her that Zeus, before taking another lover, would sit on this rock to free himself from his love to Hera.Another tale relates that a man named Nireus, who fell in love with the cult statue of Athena, came to the rock and jumped in order relieve himself. After jumping, he fell into the net of a fisherman in which, when he was pulled out, he found a box filled with gold. He fought with the fisherman and took the gold, but Apollo appeared to him in the night in a dream and warned him not to appropriate gold which belonged to others.It was an ancestral custom among the Leukadians to fling a criminal from this rock every year at the sacrifice performed in honor of Apollo for the sake of averting evil. However, a number of men would be stationed all around below rock to catch the criminal and take him out of the borders in order to exile him from the island. This was the same rock from which, according to a legend, Sappho took her suicidal leap.Female loversLove affairs ascribed to Apollo are a late development in Greek mythology. Their vivid anecdotal qualities have made some of them favorites of painters since the Renaissance, the result being that they stand out more prominently in the modern imagination.Daphne was a nymph who scorned Apollo's advances and ran away from him. When Apollo chased her in order to persuade her, she changed herself into a laurel tree. According to other versions, she cried for help during the chase, and Gaia helped her by taking her in and placing a laurel tree in her place. According to Roman poet Ovid, the chase was brought about by Cupid, who hit Apollo with golden arrow of love and Daphne with leaden arrow of hatred. The myth explains the origin of the laurel and connection of Apollo with the laurel and its leaves, which his priestess employed at Delphi. The leaves became the symbol of victory and laurel wreaths were given to the victors of the Pythian games.Apollo is said to have been the lover of all nine Muses, and not being able to choose one of them, decided to remain unwed. He fathered the Corybantes by the Muse Thalia, Orpheus by Calliope, Linus of Thrace by Calliope or Urania and Hymenaios (Hymen) by one of the Muses.Cyrene was a Thessalian princess whom Apollo loved. In her honor, he built the city Cyrene and made her its ruler. She was later granted longevity by Apollo who turned her into a nymph. The couple had two sons, Aristaeus, and Idmon.Evadne was a nymph daughter of Poseidon and a lover of Apollo. She bore him a son, Iamos. During the time of the childbirth, Apollo sent Eileithyia, the goddess of childbirth to assist her.Rhoeo, a princess of the island of Naxos was loved by Apollo. Out of affection for her, Apollo turned her sisters into goddesses. On the island Delos she bore Apollo a son named Anius. Not wanting to have the child, she entrusted the infant to Apollo and left. Apollo raised and educated the child on his own.Ourea, a daughter of Poseidon, fell in love with Apollo when he and Poseidon were serving the Trojan king Laomedon. They both united on the day the walls of Troy were built. She bore to Apollo a son, whom Apollo named Ileus, after the city of his birth, Ilion (Troy). Ileus was very dear to Apollo.Thero, daughter of Phylas, a maiden as beautiful as the moonbeams, was loved by the radiant Apollo, and she loved him in return. By their union, she became mother of Chaeron, who was famed as "the tamer of horses". He later built the city Chaeronea.Hyrie or Thyrie was the mother of Cycnus. Apollo turned both the mother and son into swans when they jumped into a lake and tried to kill themselves.Hecuba was the wife of King Priam of Troy, and Apollo had a son with her named Troilus. An oracle prophesied that Troy would not be defeated as long as Troilus reached the age of twenty alive. He was ambushed and killed by Achilleus, and Apollo avenged his death by killing Achilles. After the sack of Troy, Hecuba was taken to Lycia by Apollo.Coronis was daughter of Phlegyas, King of the Lapiths. While pregnant with Asclepius, Coronis fell in love with Ischys, son of Elatus and slept with him. When Apollo found out about her infidelity through his prophetic powers, he sent his sister, Artemis, to kill Coronis. Apollo rescued the baby by cutting open Koronis' belly and gave it to the centaur Chiron to raise.Dryope, the daughter of Dryops, was impregnated by Apollo in the form of a snake. She gave birth to a son named Amphissus.In Euripides' play Ion, Apollo fathered Ion by Creusa, wife of Xuthus. He used his powers to conceal her pregnancy from her father. Later, when Creusa left Ion to die in the wild, Apollo asked Hermes to save the child and bring him to the oracle at Delphi, where he was raised by a priestess.Male loversHyacinth (or Hyacinthus), a beautiful and athletic Spartan prince, was one of Apollo's favourite lovers. The pair was practicing throwing the discus when a discus thrown by Apollo was blown off course by the jealous Zephyrus and struck Hyacinthus in the head, killing him instantly. Apollo is said to be filled with grief. Out of Hyacinthus' blood, Apollo created a flower named after him as a memorial to his death, and his tears stained the flower petals with the interjection , meaning alas. He was later resurrected and taken to heaven. The festival Hyacinthia was a national celebration of Sparta, which commemorated the death and rebirth of Hyacinthus.Another male lover was Cyparissus, a descendant of Heracles. Apollo gave him a tame deer as a companion but Cyparissus accidentally killed it with a javelin as it lay asleep in the undergrowth. Cyparissus was so saddened by its death that he asked Apollo to let his tears fall forever. Apollo granted the request by turning him into the Cypress named after him, which was said to be a sad tree because the sap forms droplets like tears on the trunk.Admetus, the king of Pherae, was also Apollo's lover. During his exile, which lasted either for one year or nine years, Apollo served Admetus as a herdsman. The romantic nature of their relationship was first described by Callimachus of Alexandria, who wrote that Apollo was "fired with love" for Admetus. Plutarch lists Admetus as one of Apollo's lovers and says that Apollo served Admetus because he doted upon him. Latin poet Ovid in his Ars Amatoria said that even though he was a god, Apollo forsook his pride and stayed in as a servant for the sake of Admetus. Tibullus desrcibes Apollo's love to the king as servitium amoris (slavery of love) and asserts that Apollo became his servant not by force but by choice. He would also make cheese and serve it to Admetus. His domestic actions caused embarrassment to his family.When Admetus wanted to marry princess Alcestis, Apollo provided a chariot pulled by a lion and a boar he had tamed. This satisfied Alcestis' father and he let Admetus marry his daughter. Further, Apollo saved the king from Artemis' wrath and also convinced the Moirai to postpone Admetus' death once.Branchus, a shepherd, one day came across Apollo in the woods. Captivated by the god's beauty, he kissed Apollo. Apollo requited his affections and wanting to reward him, bestowed prophetic skills on him. His descendants, the Branchides, were an influential clan of prophets.Other male lovers of Apollo include:Adonis, who is said to have been the lover of both Apollo and Aphrodite. He behaved as a man with Aphrodite and as a woman with Apollo.Atymnius, otherwise known as a beloved of SarpedonBoreas, the god of North windsHelenus, the son of Priam and a Trojan Prince, was a lover of Apollo and received from him an ivory bow with which he later wounded Achilles in the hand.Hippolytus of Sicyon (not the same as Hippolytus, the son of Theseus)Hymenaios, the son of MagnesIapis, to whom Apollo taught the art of healingPhorbas, the dragon slayer (probably the son of Triopas)ChildrenApollo sired many children, from mortal women and nymphs as well as the goddesses. His children grew up to be physicians, musicians, poets, seers or archers. Many of his sons founded new cities and became kings. They were all usually very beautiful.Asclepius is the most famous son of Apollo. His skills as a physician surpassed that of Apollo's. Zeus killed him for bringing back the dead, but upon Apollo's request, he was resurrected as a god. Aristaeus was placed under the care of Chiron after his birth. He became the god of beekeeping, cheese making, animal husbandry and more. He was ultimately given immortality for the benefits he bestowed upon the humanity. The Corybantes were spear-clashing, dancing demigods.The sons of Apollo who participated in the Trojan War include the Trojan princes Hector and Troilus, as well as Tenes, the king of Tenedos, all three of whom were killed by Achilles over the course of the war.Apollo's children who became musicians and bards include Orpheus, Linus, Ialemus, Hymenaeus, Philammon, Eumolpus and Eleuther. Apollo fathered 3 daughters, Apollonis, Borysthenis and Cephisso, who formed a group of minor Muses, the "Musa Apollonides". They were nicknamed Nete, Mese and Hypate after the highest, middle and lowest strings of his lyre. Phemonoe was a seer and a poetess who was the inventor of Hexameter.Apis, Idmon, Iamus, Tenerus, Mopsus, Galeus, Telmessus and others were gifted seers. Anius, Pythaeus and Ismenus lived as high priests. Most of them were trained by Apollo himself.Arabus, Delphos, Dryops, Miletos, Tenes, Epidaurus, Ceos, Lycoras, Syrus, Pisus, Marathus, Megarus, Patarus, Acraepheus, Cicon, Chaeron and many other sons of Apollo, under the guidance of his words, founded eponymous cities.He also had a son named Chrysorrhoas who was a mechanic artist. His other daughters include Eurynome, Chariclo wife of Chiron, Eurydice the wife of Orpheus, Eriopis, famous for her beautiful hair, Melite the heroine, Pamphile the silk weaver, Parthenos, and by some accounts, Phoebe, Hilyra and Scylla. Apollo turned Parthenos into a constellation after her early death.Additionally, Apollo fostered and educated Chiron, the centaur who later became the greatest teacher and educated many demigods, including Apollo's sons. Apollo also fostered Carnus, the son of Zeus and Europa.Failed love attemptsMarpessa was kidnapped by Idas but was loved by Apollo as well. Zeus made her choose between them, and she chose Idas on the grounds that Apollo, being immortal, would tire of her when she grew old.Sinope, a nymph, was approached by the amorous Apollo. She made him promise that he would grant to her whatever she would ask for, and then cleverly asked him to let her stay a virgin. Apollo kept his promise and went back.Bolina was admired by Apollo but she refused him and jumped into the sea. To avoid her death, Apollo turned her into a nymph and let her go.Castalia was a nymph whom Apollo loved. She fled from him and dove into the spring at Delphi, at the base of Mt. Parnassos, which was then named after her. Water from this spring was sacred; it was used to clean the Delphian temples and inspire the priestesses.Cassandra, was a daughter of Hecuba and Priam. Apollo wished to court her. Cassandra promised to return his love on one condition - he should give her the power to see the future. Apollo fulfilled her wish, but she went back on her word and rejected him soon after. Angered that she broke her promise, Apollo cursed her that even though she would see the future, no one would ever believe her prophecies.Hestia, the goddess of the hearth, rejected both Apollo's and Poseidon's marriage proposals and swore that she would always stay unmarried.Female counterpartsArtemisArtemis as the sister of Apollo, is thea apollousa, that is, she as a female divinity represented the same idea that Apollo did as a male divinity. In the pre-Hellenic period, their relationship was described as the one between husband and wife, and there seems to have been a tradition which actually described Artemis as the wife of Apollo. However, this relationship was never sexual but spiritual, which is why they both are seen being unmarried in the Hellenic period.Artemis, like her brother, is armed with a bow and arrows. She is the cause of sudden deaths of women. She also is the protector of the young, especially girls. Though she has nothing to do with oracles, music or poetry, she sometimes led the female chorus on Olympus while Apollo sang. The laurel (daphne) was sacred to both. Artemis Daphnaia had her temple among the Lacedemonians, at a place called Hypsoi. Apollo Daphnephoros had a temple in Eretria, a "place where the citizens are to take the oaths". In later times when Apollo was regarded as identical with the sun or Helios, Artemis was naturally regarded as Selene or the moon.HecateHecate, the goddess of witchcraft and magic, is the chthonic counterpart of Apollo. They both are cousins, since their mothers - Leto and Asteria - are sisters. One of Apollo's epithets, Hecatos, is the masculine form of Hecate, and both the names mean "working from afar". While Apollo presided over the prophetic powers and magic of light and heaven, Hecate presided over the prophetic powers and magic of night and chthonian darkness. If Hecate is the "gate-keeper", Apollo Agyieus is the "door-keeper". Hecate is the goddess of crossroads and Apollo is the god and protector of streets.The oldest evidence found for Hecate's worship is at Apollo's temple in Miletos. There, Hecate was taken to be Apollo's sister counterpart in the absence of Artemis. Hecate's lunar nature makes her the goddess of the waning moon and contrasts and complements, at the same time, Apollo's solar nature.AthenaAs a deity of knowledge and great power, Apollo was seen being the male counterpart of Athena. Being Zeus' favorite children, they were given more powers and duties. Apollo and Athena often took up the role as protectors of cities, and were patrons of some of the important cities. Athena was the principle goddess of Athens, Apollo was the principle god of Sparta.As patrons of arts, Apollo and Athena were companions of the Muses, the former a much more frequent companion than the latter. Apollo was sometimes called the son of Athena and Hephaestus.In the Trojan war, as Zeus' executive, Apollo is seen holding the aegis like Athena usually does. Apollo's decisions were usually approved by his sister Athena, and they both worked to establish the law and order set forth by Zeus.Apollo in the OresteiaIn Aeschylus' Oresteia trilogy, Clytemnestra kills her husband, King Agamemnon because he had sacrificed their daughter Iphigenia to proceed forward with the Trojan war. Apollo gives an order through the Oracle at Delphi that Agamemnon's son, Orestes, is to kill Clytemnestra and Aegisthus, her lover. Orestes and Pylades carry out the revenge, and consequently Orestes is pursued by the Erinyes or Furies (female personifications of vengeance).Apollo and the Furies argue about whether the matricide was justified; Apollo holds that the bond of marriage is sacred and Orestes was avenging his father, whereas the Erinyes say that the bond of blood between mother and son is more meaningful than the bond of marriage. They invade his temple, and he drives them away. He says that the matter should be brought before Athena. Apollo promises to protect Orestes, as Orestes has become Apollo's supplicant. Apollo advocates Orestes at the trial, and ultimately Athena rules in favor of Apollo.Roman ApolloThe Roman worship of Apollo was adopted from the Greeks. As a quintessentially Greek god, Apollo had no direct Roman equivalent, although later Roman poets often referred to him as Phoebus. There was a tradition that the Delphic oracle was consulted as early as the period of the kings of Rome during the reign of Tarquinius Superbus.On the occasion of a pestilence in the 430s BCE, Apollo's first temple at Rome was established in the Flaminian fields, replacing an older cult site there known as the "Apollinare". During the Second Punic War in 212 BCE, the Ludi Apollinares ("Apollonian Games") were instituted in his honor, on the instructions of a prophecy attributed to one Marcius. In the time of Augustus, who considered himself under the special protection of Apollo and was even said to be his son, his worship developed and he became one of the chief gods of Rome.After the battle of Actium, which was fought near a sanctuary of Apollo, Augustus enlarged Apollo's temple, dedicated a portion of the spoils to him, and instituted quinquennial games in his honour. He also erected a new temple to the god on the Palatine hill. Sacrifices and prayers on the Palatine to Apollo and Diana formed the culmination of the Secular Games, held in 17 BCE to celebrate the dawn of a new era.FestivalsThe chief Apollonian festival was the Pythian Games held every four years at Delphi and was one of the four great Panhellenic Games. Also of major importance was the Delia held every four years on Delos.Athenian annual festivals included the Boedromia, Metageitnia, Pyanepsia, and Thargelia.Spartan annual festivals were the Carneia and the Hyacinthia.Thebes every nine years held the Daphnephoria.Attributes and symbolsApollo's most common attributes were the bow and arrow. Other attributes of his included the kithara (an advanced version of the common lyre), the plectrum and the sword. Another common emblem was the sacrificial tripod, representing his prophetic powers. The Pythian Games were held in Apollo's honor every four years at Delphi. The bay laurel plant was used in expiatory sacrifices and in making the crown of victory at these games.The palm tree was also sacred to Apollo because he had been born under one in Delos. Animals sacred to Apollo included wolves, dolphins, roe deer, swans, cicadas (symbolizing music and song), ravens, hawks, crows (Apollo had hawks and crows as his messengers), snakes (referencing Apollo's function as the god of prophecy), mice and griffins, mythical eagle–lion hybrids of Eastern origin.Homer and Porphyry wrote that Apollo had a hawk as his messenger. In many myths Apollo is transformed into a hawk. In addition, Claudius Aelianus wrote that in Ancient Egypt people believed that hawks were sacred to the god and that according to the ministers of Apollo in Egypt there were certain men called "hawk-keepers" (ἱερακοβοσκοί) who fed and tended the hawks belonging to the god. Eusebius wrote that the second appearance of the moon is held sacred in the city of Apollo in Egypt and that the city's symbol is a man with a hawklike face (Horus). Claudius Aelianus wrote that Egyptians called Apollo Horus in their own language.As god of colonization, Apollo gave oracular guidance on colonies, especially during the height of colonization, 750–550 BCE. According to Greek tradition, he helped Cretan or Arcadian colonists found the city of Troy. However, this story may reflect a cultural influence which had the reverse direction: Hittite cuneiform texts mention an Asia Minor god called Appaliunas or Apalunas in connection with the city of Wilusa attested in Hittite inscriptions, which is now generally regarded as being identical with the Greek Ilion by most scholars. In this interpretation, Apollo's title of Lykegenes can simply be read as "born in Lycia", which effectively severs the god's supposed link with wolves (possibly a folk etymology).In literary contexts, Apollo represents harmony, order, and reason—characteristics contrasted with those of Dionysus, god of wine, who represents ecstasy and disorder. The contrast between the roles of these gods is reflected in the adjectives Apollonian and Dionysian. However, the Greeks thought of the two qualities as complementary: the two gods are brothers, and when Apollo at winter left for Hyperborea, he would leave the Delphic oracle to Dionysus. This contrast appears to be shown on the two sides of the Borghese Vase.Apollo is often associated with the Golden Mean. This is the Greek ideal of moderation and a virtue that opposes gluttony.Apollo in the artsApollo is a common theme in Greek and Roman art and also in the art of the Renaissance. The earliest Greek word for a statue is "delight" (, agalma), and the sculptors tried to create forms which would inspire such guiding vision. Greek art puts into Apollo the highest degree of power and beauty that can be imagined. The sculptors derived this from observations on human beings, but they also embodied in concrete form, issues beyond the reach of ordinary thought.The naked bodies of the statues are associated with the cult of the body that was essentially a religious activity. The muscular frames and limbs combined with slim waists indicate the Greek desire for health, and the physical capacity which was necessary in the hard Greek environment. The statues of Apollo embody beauty, balance and inspire awe before the beauty of the world.Archaic sculptureNumerous free-standing statues of male youths from Archaic Greece exist, and were once thought to be representations of Apollo, though later discoveries indicated that many represented mortals. In 1895, V. I. Leonardos proposed the term kouros ("male youth") to refer to those from Keratea; this usage was later expanded by Henri Lechat in 1904 to cover all statues of this format.The earliest examples of life-sized statues of Apollo may be two figures from the Ionic sanctuary on the island of Delos. Such statues were found across the Greek speaking world, the preponderance of these were found at the sanctuaries of Apollo with more than one hundred from the sanctuary of Apollo Ptoios, Boeotia alone. Significantly more rare are the life-sized bronze statues. One of the few originals which survived into the present day—so rare that its discovery in 1959 was described as "a miracle" by Ernst Homann-Wedeking—is the masterpiece bronze, Piraeus Apollo. It was found in Piraeus, a port city close to Athens, and is believed to have come from north-eastern Peloponnesus. It is the only surviving large-scale Peloponnesian statue.Classical sculptureThe famous Apollo of Mantua and its variants are early forms of the Apollo Citharoedus statue type, in which the god holds the cithara, a sophisticated seven-stringed variant of the lyre, in his left arm. While none of the Greek originals have survived, several Roman copies from approximately the late 1st or early 2nd century exist.Other notable forms are the Apollo Citharoedus and the Apollo Barberini.Hellenistic Greece-RomeApollo as a handsome beardless young man, is often depicted with a cithara (as Apollo Citharoedus) or bow in his hand, or reclining on a tree (the Apollo Lykeios and Apollo Sauroctonos types). The Apollo Belvedere is a marble sculpture that was rediscovered in the late 15th century; for centuries it epitomized the ideals of Classical Antiquity for Europeans, from the Renaissance through the 19th century. The marble is a Hellenistic or Roman copy of a bronze original by the Greek sculptor Leochares, made between 350 and 325 BCE.The life-size so-called "Adonis" found in 1780 on the site of a villa suburbana near the Via Labicana in the Roman suburb of Centocelle is identified as an Apollo by modern scholars. In the late 2nd century CE floor mosaic from El Djem, Roman Thysdrus, he is identifiable as Apollo Helios by his effulgent halo, though now even a god's divine nakedness is concealed by his cloak, a mark of increasing conventions of modesty in the later Empire.Another haloed Apollo in mosaic, from Hadrumentum, is in the museum at Sousse. The conventions of this representation, head tilted, lips slightly parted, large-eyed, curling hair cut in locks grazing the neck, were developed in the 3rd century BCE to depict Alexander the Great. Some time after this mosaic was executed, the earliest depictions of Christ would also be beardless and haloed.Modern receptionApollo often appears in modern and popular culture due to his status as the god of music, dance and poetry.Postclassical art and literatureDance and music Apollo has featured in dance and music in modern culture. Percy Bysshe Shelley composed a "Hymn of Apollo" (1820), and the god's instruction of the Muses formed the subject of Igor Stravinsky's Apollon musagète (1927–1928). In 1978, the Canadian band Rush released an album with songs "Apollo: Bringer of Wisdom"/"Dionysus: Bringer of Love".Books Apollo been portrayed in modern literature, such as when Charles Handy, in Gods of Management (1978) uses Greek gods as a metaphor to portray various types of organizational culture. Apollo represents a 'role' culture where order, reason, and bureaucracy prevail. In 2016, author Rick Riordan published the first book in the Trials of Apollo series, publishing four other books in the series in 2017, 2018, 2019 and 2020.Film Apollo has been depicted in modern films—for instance, by Keith David in the 1997 animated feature film Hercules, by Luke Evans in the 2010 action film Clash of the Titans, and by Dimitri Lekkos in the 2010 film Percy Jackson & the Olympians: The Lightning Thief.Video games Apollo has appeared in many modern video games. Apollo appears as a minor character in Santa Monica Studio's 2010 action-adventure game God of War III with his bow being used by Peirithous. He also appears in the 2014 Hi-Rez Studios Multiplayer Online Battle Arena game Smite as a playable character.Psychology and philosophy In philosophical discussion of the arts, a distinction is sometimes made between the Apollonian and Dionysian impulses where the former is concerned with imposing intellectual order and the latter with chaotic creativity. Friedrich Nietzsche argued that a fusion of the two was most desirable. Psychologist Carl Jung's Apollo archetype represents what he saw as the disposition in people to over-intellectualise and maintain emotional distance.Spaceflight In spaceflight, the 1960s and 1970s NASA program for orbiting and landing astronauts on the Moon was named after Apollo, by NASA manager Abe Silverstein: "Apollo riding his chariot across the Sun was appropriate to the grand scale of the proposed program."GenealogySee alsoFamily tree of the Greek godsDryadEpirusPhoebus (disambiguation)Sibylline oraclesTegyraTemple of Apollo (disambiguation)NotesReferencesSourcesPrimary sources Aelian, On Animals, Volume II: Books 6-11. Translated by A. F. Scholfield. Loeb Classical Library 447. Cambridge, MA: Harvard University Press, 1958. Aeschylus, The Eumenides in Aeschylus, with an English translation by Herbert Weir Smyth, Ph. D. in two volumes, Vol 2, Cambridge, Massachusetts, Harvard University Press, 1926, Online version at the Perseus Digital Library. Antoninus Liberalis, The Metamorphoses of Antoninus Liberalis translated by Francis Celoria (Routledge 1992). Online version at the Topos Text Project. Apollodorus, Apollodorus, The Library, with an English Translation by Sir James George Frazer, F.B.A., F.R.S. in 2 Volumes. Cambridge, MA, Harvard University Press; London, William Heinemann Ltd. 1921. Online version at the Perseus Digital Library. Apollonius of Rhodes, Apollonius Rhodius: the Argonautica, translated by Robert Cooper Seaton, W. Heinemann, 1912. Internet Archive. Callimachus, Callimachus and Lycophron with an English Translation by A. W. Mair; Aratus, with an English Translation by G. R. Mair, London: W. Heinemann, New York: G. P. Putnam 1921. Online version at Harvard University Press. Internet Archive. Cicero, Marcus Tullius, De Natura Deorum in Cicero in Twenty-eight Volumes, XIX De Natura Deorum; Academica, with an english translation by H. Rackham, Cambridge, Massachusetts: Harvard University Press; London: William Heinemann, Ltd, 1967. Internet Archive. Diodorus Siculus, Library of History, Volume III: Books 4.59-8, translated by C. H. Oldfather, Loeb Classical Library No. 340. Cambridge, Massachusetts, Harvard University Press, 1939. . Online version at Harvard University Press. Online version by Bill Thayer. Herodotus, Herodotus, with an English translation by A. D. Godley. Cambridge. Harvard University Press. 1920. Online version available at The Perseus Digital Library. Hesiod, Theogony, in The Homeric Hymns and Homerica with an English Translation by Hugh G. Evelyn-White, Cambridge, MA., Harvard University Press; London, William Heinemann Ltd. 1914. Online version at the Perseus Digital Library. Homeric Hymn 3 to Apollo in The Homeric Hymns and Homerica with an English Translation by Hugh G. Evelyn-White, Cambridge, MA., Harvard University Press; London, William Heinemann Ltd. 1914. Online version at the Perseus Digital Library. Homeric Hymn 4 to Hermes, in The Homeric Hymns and Homerica with an English Translation by Hugh G. Evelyn-White, Cambridge, Massachusetts, Harvard University Press; London, William Heinemann Ltd. 1914. Online version at the Perseus Digital Library. Homer, The Iliad with an English Translation by A.T. Murray, PhD in two volumes. Cambridge, MA., Harvard University Press; London, William Heinemann, Ltd. 1924. Online version at the Perseus Digital Library. Homer; The Odyssey with an English Translation by A.T. Murray, PH.D. in two volumes. Cambridge, MA., Harvard University Press; London, William Heinemann, Ltd. 1919. Online version at the Perseus Digital Library. Hyginus, Gaius Julius, De Astronomica, in The Myths of Hyginus, edited and translated by Mary A. Grant, Lawrence: University of Kansas Press, 1960. Online version at ToposText. Hyginus, Gaius Julius, Fabulae, in The Myths of Hyginus, edited and translated by Mary A. Grant, Lawrence: University of Kansas Press, 1960. Online version at ToposText. Livy, The History of Rome, Books I and II With An English Translation. Cambridge. Cambridge, Mass., Harvard University Press; London, William Heinemann, Ltd. 1919. Nonnus, Dionysiaca; translated by Rouse, W H D, I Books I-XV. Loeb Classical Library No. 344, Cambridge, Massachusetts, Harvard University Press; London, William Heinemann Ltd. 1940. Internet Archive Nonnus, Dionysiaca; translated by Rouse, W H D, II Books XVI-XXXV. Loeb Classical Library No. 345, Cambridge, Massachusetts, Harvard University Press; London, William Heinemann Ltd. 1940. Internet Archive Statius, Thebaid. Translated by Mozley, J H. Loeb Classical Library Volumes. Cambridge, Massachusetts, Harvard University Press; London, William Heinemann Ltd. 1928. Strabo, The Geography of Strabo. Edition by H.L. Jones. Cambridge, Mass.: Harvard University Press; London: William Heinemann, Ltd. 1924. Online version at the Perseus Digital Library. Sophocles, Oedipus Rex Palaephatus, On Unbelievable Tales 46. Hyacinthus (330 BCE) Ovid, Metamorphoses, Brookes More, Boston, Cornhill Publishing Co. 1922. Online version at the Perseus Digital Library. 10. 162–219 (1–8 CE) Pausanias, Pausanias Description of Greece with an English Translation by W.H.S. Jones, Litt.D., and H.A. Ormerod, M.A., in 4 Volumes. Cambridge, MA, Harvard University Press; London, William Heinemann Ltd. 1918. Online version at the Perseus Digital Library. Philostratus the Elder, Imagines, in Philostratus the Elder, Imagines. Philostratus the Younger, Imagines. Callistratus, Descriptions. Translated by Arthur Fairbanks. Loeb Classical Library No. 256. Cambridge, Massachusetts: Harvard University Press, 1931. . Online version at Harvard University Press. Internet Archive 1926 edition. i.24 Hyacinthus (170–245 CE) Philostratus the Younger, Imagines, in Philostratus the Elder, Imagines. Philostratus the Younger, Imagines. Callistratus, Descriptions. Translated by Arthur Fairbanks. Loeb Classical Library No. 256. Cambridge, Massachusetts: Harvard University Press, 1931. . Online version at Harvard University Press. Internet Archive 1926 edition. 14. Hyacinthus (170–245 CE) Pindar, Odes, Diane Arnson Svarlien. 1990. Online version at the Perseus Digital Library. Plutarch. Lives, Volume I: Theseus and Romulus. Lycurgus and Numa. Solon and Publicola. Translated by Bernadotte Perrin. Loeb Classical Library No. 46. Cambridge, Massachusetts: Harvard University Press, 1914. . Online version at Harvard University Press. Numa at the Perseus Digital Library. Pseudo-Plutarch, De fluviis, in Plutarch's morals, Volume V, edited and translated by William Watson Goodwin, Boston: Little, Brown & Co., 1874. Online version at the Perseus Digital Library. Lucian, Dialogues of the Dead. Dialogues of the Sea-Gods. Dialogues of the Gods. Dialogues of the Courtesans, translated by M. D. MacLeod, Loeb Classical Library No. 431, Cambridge, Massachusetts, Harvard University Press, 1961. . Online version at Harvard University Press. Internet Archive. First Vatican Mythographer, 197. Thamyris et Musae Tzetzes, John, Chiliades, editor Gottlieb Kiessling, F.C.G. Vogel, 1826. Google Books. (English translation: Book I by Ana Untila; Books II–IV, by Gary Berkowitz; Books V–VI by Konstantino Ramiotis; Books VII–VIII by Vasiliki Dogani; Books IX–X by Jonathan Alexander; Books XII–XIII by Nikolaos Giallousis. Internet Archive). Valerius Flaccus, Argonautica, translated by J. H. Mozley, Loeb Classical Library No. 286. Cambridge, Massachusetts, Harvard University Press; London, William Heinemann Ltd. 1928. . Online version at Harvard University Press. Online translated text available at theoi.com. Vergil, Aeneid. Theodore C. Williams. trans. Boston. Houghton Mifflin Co. 1910. Online version at the Perseus Digital Library.Secondary sources Athanassakis, Apostolos N., and Benjamin M. Wolkow, The Orphic Hymns, Johns Hopkins University Press; owlerirst Printing edition (May 29, 2013). . Google Books. M. Bieber, 1964. Alexander the Great in Greek and Roman Art. Chicago. Hugh Bowden, 2005. Classical Athens and the Delphic Oracle: Divination and Democracy. Cambridge University Press. Walter Burkert, 1985. Greek Religion (Harvard University Press) III.2.5 passim Fontenrose, Joseph Eddy, Python: A Study of Delphic Myth and Its Origins, University of California Press, 1959. . Gantz, Timothy, Early Greek Myth: A Guide to Literary and Artistic Sources, Johns Hopkins University Press, 1996, Two volumes: (Vol. 1), (Vol. 2). Miranda J. Green, 1997. Dictionary of Celtic Myth and Legend, Thames and Hudson. Grimal, Pierre, The Dictionary of Classical Mythology, Wiley-Blackwell, 1996. . Hard, Robin, The Routledge Handbook of Greek Mythology: Based on H.J. Rose's "Handbook of Greek Mythology", Psychology Press, 2004, . Google Books. Karl Kerenyi, 1953. Apollon: Studien über Antiken Religion und Humanität revised edition. Kerényi, Karl 1951, The Gods of the Greeks, Thames and Hudson, London. Mertens, Dieter; Schutzenberger, Margareta. Città e monumenti dei Greci d'Occidente: dalla colonizzazione alla crisi di fine V secolo a.C.. Roma L'Erma di Bretschneider, 2006. . Martin Nilsson, 1955. Die Geschichte der Griechische Religion, vol. I. C.H. Beck. Parada, Carlos, Genealogical Guide to Greek Mythology, Jonsered, Paul Åströms Förlag, 1993. . Pauly–Wissowa, Realencyclopädie der klassischen Altertumswissenschaft: II, "Apollon". The best repertory of cult sites (Burkert). Peck, Harry Thurston, Harpers Dictionary of Classical Antiquities, New York. Harper and Brothers. 1898. Online version at the Perseus Digital Library. Pfeiff, K.A., 1943. Apollon: Wandlung seines Bildes in der griechischen Kunst. Traces the changing iconography of Apollo. D.S.Robertson (1945) A handbook of Greek and Roman Architecture Cambridge University Press Smith, William; Dictionary of Greek and Roman Biography and Mythology, London (1873). "Apollo" Smith, William, A Dictionary of Greek and Roman Antiquities. William Smith, LLD. William Wayte. G. E. Marindin. Albemarle Street, London. John Murray. 1890. Online version at the Perseus Digital Library. Spivey Nigel (1997) Greek art Phaedon Press Ltd.External links Apollo at the Greek Mythology Link, by Carlos Parada The Warburg Institute Iconographic Database: ca 1650 images of ApolloBeauty godsHealth godsKnowledge godsLight deitiesMaintenance deitiesMusic and singing godsOracular godsSolar godsGreek godsRoman godsDragonslayersMythological Greek archersMythological rapistsHomosexuality and bisexuality deitiesDivine twinsDeities in the IliadMetamorphoses charactersCharacters in Greek mythology LGBT themes in Greek mythologyChildren of ZeusCharacters in the OdysseyCharacters in the Argonautica -Andre Kirk Agassi ( ; born April 29, 1970) is an American former world No. 1 tennis player. He is an eight-time major champion and a 1996 Olympic gold medalist, as well as a runner-up in seven other Grand Slam tournaments.Agassi was the first man to win four Australian Open singles titles in the Open Era (though later surpassed by Novak Djokovic, who won his fifth title in 2015 and has since won the tournament nine times). Agassi is the second of five men to achieve the career Grand Slam in the Open Era and the fifth of eight overall to make the achievement. He is also the first of two men to achieve the career Golden Slam (career Grand Slam and Olympic gold medal), and the only man to win a career Super Slam (career Grand Slam, plus the Olympic gold medal and the year-end championships).Agassi was the first man to win all four singles majors on three different surfaces (hard, clay and grass), and remains the most recent American man to win the French Open (in 1999) and the Australian Open (in 2003). He also won 17 ATP Masters Series titles and was part of the winning Davis Cup teams in 1990, 1992 and 1995. Agassi reached the world No. 1 ranking for the first time in 1995 but was troubled by personal issues during the mid-to-late 1990s and sank to No. 141 in 1997, prompting many to believe that his career was over. Agassi returned to No. 1 in 1999 and enjoyed the most successful run of his career over the next four years. During his 20-plus year tour career, Agassi was known by the nickname "The Punisher".After suffering from sciatica caused by two bulging discs in his back, a spondylolisthesis (vertebral displacement) and a bone spur that interfered with the nerve, Agassi retired from professional tennis on September 3, 2006, after losing in the third round of the US Open. He is the founder of the Andre Agassi Charitable Foundation, which has raised over $60 million for at-risk children in Southern Nevada. In 2001, the Foundation opened the Andre Agassi College Preparatory Academy in Las Vegas, a K–12 public charter school for at-risk children. He has been married to fellow tennis player Steffi Graf since 2001.1970–1985: Early lifeAndre Agassi was born in Las Vegas, Nevada, to Emmanuel "Mike" Agassi, a former Olympic boxer from Iran and American Elizabeth "Betty" Agassi (née Dudley). His father is of Armenian and Assyrian heritage. Andre Agassi's mother, Betty, is a breast cancer survivor. He has three older siblings – Rita (last wife of former number one Pancho Gonzales), Philip and Tami. Andre was given the middle name Kirk after Kirk Kerkorian, an Armenian American billionaire. Emmanuel Agassi, then a waiter at Tropicana Las Vegas, had met Kerkorian in 1963.At the age of 12, Agassi and his good friend and doubles partner, Roddy Parks, won the 1982 National Indoor Boys 14s Doubles Championship in Chicago. Agassi describes memorable experiences and juvenile pranks with Roddy in his book Open.When he was 13, Agassi was sent to Nick Bollettieri's Tennis Academy in Florida. He was meant to stay for only three months, because that was all his father could afford. After thirty minutes of watching Agassi play, Bollettieri, deeply impressed by his talent, called Mike and said: "Take your check back. He's here for free." Agassi then dropped out of school in the ninth grade to pursue a full-time tennis career.1986–2006: Professional career1986–1993: Breakthrough and the first major titleAgassi turned professional at the age of 16 and competed in his first tournament at La Quinta, California. He won his first match against John Austin, but then lost his second match to Mats Wilander. By the end of 1986, Agassi was ranked No. 91. He won his first top-level singles title in 1987 at the Sul American Open in Itaparica and ended the year ranked No. 25. He won six additional tournaments in 1988 (Memphis, U.S. Men's Clay Court Championships, Forest Hills WCT, Stuttgart Outdoor, Volvo International and Livingston Open), and, by December of that year, he had surpassed US$1 million in career prize money after playing in just 43 tournaments—the fastest anyone in history had reached that level. During 1988, he also set the open-era record for most consecutive victories by a male teenager (a record that stood for 17 years until Rafael Nadal broke it in 2005). His year-end ranking was No. 3, behind second-ranked Ivan Lendl and top-ranked Mats Wilander. Both the Association of Tennis Professionals and Tennis magazine named Agassi the Most Improved Player of the Year for 1988.In addition to not playing the Australian Open (which later became his best Grand Slam event) for the first eight years of his career, Agassi chose not to play at Wimbledon from 1988 through 1990 and publicly stated that he did not wish to play there because of the event's traditionalism, particularly its "predominantly white" dress code to which players at the event are required to conform.Strong performances on the tour meant that Agassi was quickly tipped as a future Grand Slam champion. While still a teenager, he reached the semi-finals of both the French Open and the US Open in 1988 and made the US Open semi-finals in 1989. He began the 1990s with a series of near-misses. He reached his first Grand Slam final in 1990 at the French Open, where he was favored before losing in four sets to Andrés Gómez, which he later attributed in his book to worrying about his wig falling off during the match. He reached his second Grand Slam final of the year at the US Open, defeating defending champion Boris Becker in the semi-finals. His opponent in the final was Pete Sampras; a year earlier, Agassi had crushed Sampras, after which time he told his coach that he felt bad for Sampras because he was never going to make it as a pro. Agassi lost the US Open final to Sampras in three sets. The rivalry between these two American players became the biggest one in tennis over the rest of the decade. Agassi ended 1990 on a high note as he helped the United States win its first Davis Cup in 8 years and won his only Tennis Masters Cup, beating reigning Wimbledon champion Stefan Edberg in the final.In 1991, Agassi reached his second consecutive French Open final, where he faced fellow Bollettieri Academy alumnus Jim Courier. Courier emerged the victor in a five-set final. Agassi decided to play at Wimbledon in 1991, leading to weeks of speculation in the media about the clothes he would wear. He eventually emerged for the first round in a completely white outfit. He reached the quarterfinals on that occasion, losing in five sets to David Wheaton.Agassi's Grand Slam tournament breakthrough came at Wimbledon, not at the French Open or the US Open, where he had previously enjoyed success. In 1992, he defeated Goran Ivanišević in a five-set final. Along the way, Agassi overcame two former Wimbledon champions: Boris Becker and John McEnroe. No other baseliner would triumph at Wimbledon until Lleyton Hewitt ten years later. Agassi was named the BBC Overseas Sports Personality of the Year in 1992. Agassi once again played on the United States' Davis Cup winning team in 1992. It was their second Davis cup title in three years. Agassi famously played the game wearing Oakley brand sunglasses, and a photo of him from the day appeared on the cover of Tennis magazine. In his memoir, he wrote that he was covering up bloodshot eyes from a hangover and claimed that the founder of Oakley, Jim Jannard, had sent him a Dodge Viper to thank him for the inadvertent publicity.In 1993, Agassi won the only doubles title of his career, at the Cincinnati Masters, partnered with Petr Korda. He missed much of the early part of that year due to injuries. Although he made the quarterfinals in his Wimbledon title defense, he lost to eventual champion and No. 1 Pete Sampras in five sets. Agassi lost in the first round at the US Open to Thomas Enqvist and required wrist surgery late in the year.1994–1997: Rise to the top, Olympic Gold and the fallWith new coach Brad Gilbert on board, Agassi began to employ more of a tactical, consistent approach, which fueled his resurgence. He started slowly in 1994, losing in the first week at the French Open and Wimbledon. Nevertheless, he emerged during the hard-court season, winning the Canadian Open. His comeback culminated at the 1994 US Open with a five-set fourth-round victory against Michael Chang. He then became the first man to capture the US Open as an unseeded player, beating Michael Stich in the final. Along the way, he beat 5 seeded players.In 1995, Agassi shaved his balding head, breaking with his old "image is everything" style. He competed in the 1995 Australian Open (his first appearance at the event) and won, beating Sampras in a four-set final. Agassi and Sampras met in five tournament finals in 1995, all on hardcourt, with Agassi winning three. Agassi won three Masters Series events in 1995 (Cincinnati, Key Biscayne, and the Canadian Open) and seven titles total. He compiled a career-best 26-match winning streak during the summer hard-court circuit, with the last victory being in an intense late-night four-set semi-final of the US Open against Boris Becker. The streak ended the next day when Agassi lost the final to Sampras.Agassi reached the world No. 1 ranking for the first time in April 1995. He held that ranking until November, for a total of 30 weeks. Agassi skipped most of the fall indoor season which allowed Sampras to surpass him and finish ranked No. 1 at the year-end ranking. In terms of win/loss record, 1995 was Agassi's best year. He won 73 and lost 9 matches, and was also once again a key player on the United States' Davis Cup winning team—the third and final Davis Cup title of his career.1996 was a less successful year for Agassi, as he failed to reach any Grand Slam final. He suffered two early-round losses to Chris Woodruff and Doug Flach at the French Open and Wimbledon, respectively, and lost to Chang in straight sets in the Australian and US Open semi-finals. At the time, Agassi blamed the Australian Open loss on the windy conditions, but later said in his biography that he had lost the match on purpose, as he did not want to play Boris Becker, whom he would have faced in that final. The high point for Agassi was winning the men's singles gold medal at the Olympic Games in Atlanta, beating Sergi Bruguera of Spain in the final. Agassi also successfully defended his singles titles in Cincinnati and Key Biscayne.1997 was the low point of Agassi's career. His wrist injury resurfaced, and he played only 24 matches during the year. He later confessed that he started using crystal methamphetamine at that time, allegedly on the urging of a friend. He failed an ATP drug test, but wrote a letter claiming the same friend had spiked a drink. The ATP dropped the failed drug test as a warning. In his autobiography, Agassi admitted that the letter was a lie. He quit the drug soon after. At this time Agassi was also in a failing marriage with actress, model, and socialite Brooke Shields and had lost interest in the game. He won no top-level titles, and his ranking sank to No. 141 on November 10, 1997, prompting many to believe that his run as one of the sport's premier competitors was over and he would never again win any significant championships.1998–2003: Return to glory and Career Super SlamIn 1998, Agassi began a rigorous conditioning program and worked his way back up the rankings by playing in Challenger Series tournaments, a circuit for pro players ranked outside the world's top 50. After returning to top physical and mental shape, Agassi recorded the most successful period of his tennis career and also played classic matches in that period against Pete Sampras and Patrick Rafter.In 1998, Agassi won five titles and leapt from No. 110 to No. 6, the highest jump into the top 10 made by any player during a calendar year. At Wimbledon, he had an early loss in the second round to Tommy Haas. He won five titles in ten finals and was runner-up at the Masters Series tournament in Key Biscayne, losing to Marcelo Ríos, who became No. 1 as a result. At the year end he was awarded the ATP Most Improved Player of the Year for the second time in his career (the first being 10 years earlier in 1988).Agassi entered the history books in 1999 when he came back from two sets to love down to beat Andrei Medvedev in a five-set French Open final, becoming, at the time, only the fifth male player (joining Rod Laver, Fred Perry, Roy Emerson and Don Budge—these have since been joined by Roger Federer, Rafael Nadal, and Novak Djokovic) to win all four Grand Slam singles titles during his career. Only Laver, Agassi, Federer, Nadal and Djokovic have achieved this feat during the Open Era. This win also made him the first (of only four, the next being Federer, Nadal and Djokovic respectively) male player in history to have won all four Grand Slam titles on three different surfaces (clay, grass and hard courts). Agassi also became the only male player to win the Career Super Slam, consisting of all four Grand Slam tournaments plus an Olympic gold medal in singles and a Year-end championship.Agassi followed his 1999 French Open victory by reaching the Wimbledon final, where he lost to Sampras in straight sets. He rebounded from his Wimbledon defeat by winning the US Open, beating Todd Martin in five sets (rallying from a two sets to one deficit) in the final. Overall during the year Agassi won 5 titles including two majors and the ATP Masters Series in Paris, where he beat Marat Safin. Agassi ended 1999 as the No. 1, ending Sampras's record of six consecutive year-ending top rankings (1993–98). This was the only time Agassi ended the year at No. 1. Agassi was runner-up to Sampras at the year-end Tennis Masters Cup losing 1–6, 5–7, 4-6 despite beating Sampras in the round-robin 6–2, 6–2.He began the next year 2000 by capturing his second Australian Open title, beating Sampras in a five-set semi-final and Yevgeny Kafelnikov in a four-set final. He was the first male player to have reached four consecutive Grand Slam finals since Rod Laver achieved the Grand Slam in 1969. At the time, Agassi was also only the fourth player since Laver to be the reigning champion of three of four Grand Slam events, missing only the Wimbledon title.. 2000 also saw Agassi reach the semi-finals at Wimbledon, where he lost in five sets to Rafter in a match considered by many to be one of the best ever at Wimbledon. At the inaugural Tennis Masters Cup in Lisbon, Agassi reached the final after defeating Marat Safin in the semi-finals to end the Russian's hopes to become the youngest No. 1 in the history of tennis. Agassi then lost to Gustavo Kuerten in the final, allowing Kuerten to be crowned year-end No. 1.Agassi opened 2001 by successfully defending his Australian Open title with a straight-sets final win over Arnaud Clément. En route, he beat a cramping Rafter in five sets in front of a sell-out crowd in what turned out to be the Aussie's last Australian Open. At Wimbledon, they met again in the semi-finals, where Agassi lost another close match to Rafter, 8–6 in the fifth set. In the quarterfinals at the US Open, Agassi lost a 3-hour, 33 minute epic match with Sampras, 7–6, 6–7, 6–7, 6–7, with no breaks of serve during the 52-game match. Despite the setback, Agassi finished 2001 ranked No. 3, becoming the only male tennis player to finish a year ranked in the top 3 in three different decades.2002 opened with disappointment for Agassi, as injury forced him to skip the Australian Open, where he was a two-time defending champion. Agassi recovered from the injury and later that year defended his Key Biscayne title beating then rising Roger Federer in a four-set final. The last duel between Agassi and Sampras came in the final of the US Open, which Sampras won in four sets and left Sampras with a 20–14 edge in their 34 career meetings. The match was the last of Sampras's career. Agassi's US Open finish, along with his Masters Series victories in Key Biscayne, Rome and Madrid, helped him finish 2002 as the oldest year-end No. 2 at 32 years and 8 months.In 2003, Agassi won the eighth (and final) Grand Slam title of his career at the Australian Open, where he beat Rainer Schüttler in straight sets in the final.On April 28, 2003, he recaptured the No. 1 ranking to become the oldest top-ranked male player since the ATP rankings began at 33 years and 13 days. The record was later surpassed by Roger Federer in 2018. He had held the No. 1 ranking for two weeks, when Lleyton Hewitt took it back on May 12, 2003. Agassi then recaptured the No. 1 ranking once again on June 16, 2003, which he held for 12 weeks until September 7, 2003. There he managed to reach the US Open semi-finals, where he lost to Juan Carlos Ferrero, surrendering his No. 1 ranking to him. During his career, Agassi held the ranking for a total of 101 weeks. Agassi's ranking slipped when injuries forced him to withdraw from a number of events. At the year-end Tennis Masters Cup, Agassi lost in the final to Federer, his third time to finish as runner-up in the event after losses in 1999 and 2000, and finished the year ranked No. 4. At age 33, he had been one of the oldest players to rank in the top 5 since Connors, at age 35, was No. 4 in 1987.2004–2006: Final yearsIn 2004, Agassi began the year with a five-set loss in the semi-finals of the Australian Open to Marat Safin; the loss ended Agassi's 26-match winning streak at the event. He won the Masters series event in Cincinnati to bring his career total to 59 top-level singles titles and a record 17 ATP Masters Series titles, having already won seven of the nine ATP Masters tournament—all except the tournaments in Monte Carlo and Hamburg. At 34, he became the second-oldest singles champion in Cincinnati tournament history (the tournament began in 1899), tied with Roger Federer and surpassed only by Ken Rosewall, who won the title in 1970 at age 35. He finished the year ranked No. 8, one of the oldest players to finish in the top 10 since the 36-year-old Connors was No. 7 in 1988. At the time, Agassi also became the sixth male player during the open era to reach 800 career wins with his first-round victory over Alex Bogomolov in Countrywide Classic in Los Angeles.Agassi's 2005 began with a quarterfinal loss to Federer at the Australian Open. Agassi had several other deep runs at tournaments, but had to withdraw from several events due to injury. He lost to Jarkko Nieminen in the first round of the French Open. He won his fourth title in Los Angeles and reached the final of the Rogers Cup, before falling to No. 2 Rafael Nadal.Agassi's 2005 was defined by an improbable run to the US Open final. After beating Răzvan Sabău and Ivo Karlović in straight sets and Tomáš Berdych in four sets, Agassi won three consecutive five-set matches to advance to the final. The most notable of these matches was his quarterfinal victory over James Blake, where he rallied from two sets down to win in the fifth set tie-breaker. His other five-set victories were on Xavier Malisse in the fourth round and Robby Ginepri in the semi-finals. In the final, Agassi faced Federer, who was seeking his second consecutive US Open title and his sixth Grand Slam title in two years. Federer defeated Agassi in four sets. Agassi finished 2005 ranked No. 7, his 16th time in the year-end top-10 rankings, which tied Connors for the most times ranked in the top 10 at year's end.Agassi had a poor start to 2006, as he was still recovering from an ankle injury and also suffering from back and leg pain and lack of match play. Agassi withdrew from the Australian Open because of the ankle injury, and his back injury and other pains forced him to withdraw from several other events, eventually skipping the entire clay-court season including the French Open. This caused his ranking to drop out of the top 10 for the last time. Agassi returned for the grass-court season, playing a tune-up, and then Wimbledon. He was defeated in the third round by world No. 2 (and eventual runner-up) Rafael Nadal. Against conventions, Agassi, the losing player, was interviewed on court after the match. At Wimbledon, Agassi announced his plans to retire following the US Open. Agassi played only two events during the summer hard-court season with his best result being a quarterfinal loss at the Countrywide Classic in Los Angeles to Fernando González of Chile, which resulted in him being unseeded at the US Open.Agassi had a short, but dramatic, run in his final US Open. Because of extreme back pain, Agassi was forced to receive anti-inflammatory injections after every match. After a tough four-set win against Andrei Pavel, Agassi faced eighth-seeded Marcos Baghdatis in the second round who had earlier advanced to the 2006 Australian Open final and Wimbledon semi-finals. Agassi won in five tough sets as the younger Baghdatis succumbed to muscle cramping in the final set. In his last match, Agassi fell to 112th-ranked big-serving Benjamin Becker of Germany in four sets. Agassi received a four-minute standing ovation from the crowd after the match and delivered a retirement speech.RivalriesAgassi vs. SamprasThe rivalry has been called the greatest of the generation of players competing in the 1990s, as Sampras and Agassi were the most successful players of that decade. They also had very contrasting playing styles, with Sampras being considered the greatest server and Agassi the greatest serve returner at the time. Agassi and Sampras met 34 times on the tour level with Agassi trailing 14–20.The 1990 US Open was their first meeting in a Grand Slam tournament final. Agassi was favored as he was ranked No. 4 at the time, compared to the No. 12 ranking of Sampras and because Agassi had defeated Sampras in their only previously completed match. Agassi, however, lost the final to Sampras in straight sets. Their next meeting in a Grand Slam was at the 1992 French Open, where they met in the quarterfinals. Although Sampras was ranked higher, Agassi came out winning in straight sets. They met again on a Grand Slam level at the quarterfinals of Wimbledon in 1993, where Agassi was the defending champion and Sampras was the newly minted world No. 1. Agassi dug himself out from a two-sets-to-love hole, levelling the match at two sets apiece; however, Sampras prevailed in five sets, and went on to win his first Wimbledon championship.With both Sampras and Agassi participating, the US won the Davis Cup in 1995. The year should be considered the peak of the rivalry as together they won three out of four major titles, meeting each other twice in the finals, and were occupying the top two spots in the rankings for the whole year. They met five times during the year, all in the title matches, including the Australian Open, the Newsweek Champions Cup (now Indian Wells), the Lipton International Players Championships (now Miami Open), the Canadian Open, and the US Open. Agassi won three of the finals, including the Australian Open; however, Sampras took the US Open title, ending Agassi's 26-match winning streak. After Agassi had taken most of the fall season off, Sampras took over the No. 1 ranking for the end of the season.In the following three years, while Sampras continued winning Grand Slam titles every season, Agassi slumped in the rankings and struggled in major competitions. The next time Sampras and Agassi met in a Grand Slam final was at Wimbledon in 1999, where Sampras won in straight sets. For both, it was considered a career rejuvenation, as Sampras had suffered a string of disappointments in the previous year while Agassi was regaining his status as a top-ranked player after winning the French Open. Sampras forfeited the No. 1 ranking to Agassi when injury forced him to withdraw from that year's US Open, which Agassi went on to win. They faced each other twice in the season-ending ATP Tour World Championships, with Sampras losing the round-robin match, but winning the final.In the 2000s, they met three more times on the Grand Slam level offering three memorable contests. In 2000, the top-ranked Agassi defeated No. 3 Sampras in the semi-finals of the Australian Open in five sets, which was an important win for Agassi who had lost 4 of the previous five matches against Sampras. In arguably their most memorable match ever, Sampras defeated Agassi in the 2001 US Open quarterfinals in four sets. There were no breaks of serve during the entire match. Reruns of the match are frequently featured on television, especially during US Open rain delays, and the match is considered one of the best in history because of the level of play presented by both players.Their last meeting was the final of the 2002 US Open, which was their third meeting in a US Open final, but the first since 1995. The match was also notable because they had defeated several up-and-coming players en route to the final. Sampras had defeated No. 3 Tommy Haas in the fourth round and future No. 1 Andy Roddick in the quarterfinals, while Agassi had defeated No. 1 and defending champion Lleyton Hewitt in the semi-finals. Sampras defeated Agassi in four sets. This was the final ATP tour singles match of Sampras's career.Agassi vs. ChangMichael Chang was the opponent Agassi faced most frequently from all the players other than Sampras. They met 22 times on the tour level with Agassi leading 15–7. Chang, unlike most of Agassi's big rivals, had a playing style similar to his. Both players preferred to stay at the baseline with Chang being more defensive-minded. The outcome was that most of their meetings were built on long and entertaining rallies. The rivalry began late in the 1980s with both players being considered the prodigies of the next great generation of American tennis players and both having foreign descent.Agassi won the first four matches including a straight-set victory in round 16 of the 1988 US Open and defeating Chang, the defending champion, in the 1990 French Open in a four-set quarterfinal. Arguably their best match took place in the round of 16 of the 1994 US Open. While both players presented high-quality shot-making, the momentum changed from set to set with Agassi eventually prevailing in a five-set victory. It turned out to be the toughest contest on his way to his first US Open title. Their next two Grand Slam meetings came in 1996, with Chang recording easy straight-set victories in the semi-finals of both the Australian Open and the US Open. Years after, Agassi shockingly admitted in his book that he had lost the first of the matches on purpose as he did not want to face Boris Becker, who was awaiting the winner in the final. Agassi won the last four of their matches, with the last being in 2003 at the Miami Open with Chang being clearly past his prime.Agassi vs. BeckerBoris Becker and Agassi played 14 times with Agassi leading 10–4. Becker won their first three matches in 1988 and 1989 before Agassi reversed the rivalry in 1990, and won 10 of their last 11 matches. They first played at Indian Wells in 1988, with Becker prevailing. Their most notable match was the 1989 Davis Cup semi-final match, which Becker won in five sets after losing the first two in tiebreaks. Agassi, considered a baseliner with a playing style not suiting grass, shocked Becker, a three-time champion, in a five-set quarterfinal at Wimbledon in 1992 on his way to his first Grand Slam title. The intensity of the rivalry peaked in 1995. Becker won that year's Wimbledon semi-final after being down a set and two breaks, to eventually win in four sets. In a highly anticipated rematch in the US Open semi-final, this time it was Agassi who came out victorious in four tight sets. Their final match was played at Hong Kong in 1999, which Agassi won in three sets.Agassi vs. RafterAgassi and Pat Rafter played fifteen times with Agassi leading 10–5. The rivalry has been considered special and delivered memorable encounters, because of the players' contrasting styles of play, with Rafter using traditional serve-&-volley methods against Agassi's variety of return of serves and passing shots as his main weapons. Agassi led 8–2 on hard courts, but Rafter surprisingly won their sole match on clay at the 1999 Rome Masters. They played four matches at Wimbledon with both winning two matches each. Agassi won the first two in 1993 and 1999, while Rafter took their 2000 and 2001 encounters, both of the gruelling 5-setters often being presented on the lists of best matches ever played. Agassi also won both their meetings at the Australian Open, in 1995 and 2001, on his way to the title on both occasions. Rafter, however, took their only US Open encounter in 1997 and went on to win the title.Agassi vs. FedererAgassi and Roger Federer played 11 times, and Federer led their head-to-head series 8–3. With the retirement of Sampras, the rivalry against the 11-years-younger Federer, who was another great server like Sampras, became Agassi's main rivalry for the final years of his career. Agassi won their first three matches, but then went on to lose eight consecutive ones. They first met in just the third tournament of Federer's career at the 1998 Swiss Indoors in Federer's hometown, with Agassi prevailing over the 17-year-old. Agassi also defeated Federer at the 2001 US Open and the finals of the Miami Open in 2002. Federer began to turn the tide at the Masters Cup in 2003, when he defeated Agassi in both the round-robin and the final. They played a memorable quarterfinal match at the 2004 US Open that spanned over two windy days, with Federer eventually prevailing in five sets. At the 2005 Dubai Championships, Federer and Agassi attracted worldwide headlines with a publicity stunt that saw the two tennis legends play on a helipad almost 220 meters above sea level at the hotel Burj al-Arab. Their final duel took place in the final of the 2005 US Open. In the historic clash of generations, Federer was victorious in four sets in front of a pro-Agassi crowd. The match was the last appearance by Agassi in any tournament final.Agassi vs. LendlAgassi and Ivan Lendl played eight times, and Lendl led their head-to-head series 6–2.Agassi vs. EdbergAgassi and Stefan Edberg played nine times, and Agassi led their head-to-head series 6–3.EarningsAgassi earned more than $30 million in prize-money during his career, sixth only to Djokovic, Federer, Nadal, Sampras and Murray to date (May 2018). He also earned more than $25 million a year through endorsements during his career, which was ranked fourth in all sports at the time.Post-retirementSince retiring after the 2006 US Open, Agassi has participated in a series of charity tournaments and continues his work with his own charity. On September 5, 2007, he was a surprise guest commentator for the Andy Roddick/Roger Federer US Open quarterfinal. He played an exhibition match at Wimbledon, teaming with his wife, Steffi Graf, to play with Tim Henman and Kim Clijsters. He played World Team Tennis for the Philadelphia Freedoms in the summer of 2009. At the 2009 French Open, Agassi was on hand to present Roger Federer, who completed his Career Grand Slam by winning the tournament and joined Agassi as one of six men to complete the Career Grand Slam, with the trophy.Also in 2009, Agassi played at the Outback Champions Series event for the first time. He played the Cancer Treatment Centers of America Tennis Championships at Surprise, Arizona, where he reached the final before bowing to eventual champion Todd Martin. Agassi returned to the tour renamed for the PowerShares Series in 2011 and participated in a total of seven events while winning two. Agassi beat Courier in the final of the Staples Champions Cup in Boston and later defeated Sampras at the CTCA Championships at his hometown Las Vegas.In 2012, Agassi took part in five tournaments, winning three of those. In November, at first he won BILT Champions Showdown in San Jose, beating John McEnroe in the final. The following day, he defended his title of the CTCA Championships, while defeating Courier in the decisive match. In the series season finale, he beat Michael Chang for the Acura Champions Cup. The series and Agassi came back to action in 2014. Agassi won both tournaments he participated in. At the Camden Wealth Advisors Cup's final in Houston, Agassi beat James Blake for a rematch of their 2005 US Open quarterfinal. He defeated Blake again in Portland to win the title of the Cancer Treatment Centers of America Championships. In 2015, Agassi took part in just one event of the PowerShares Series, losing to Mark Philippoussis in the final of the Champions Shootout. The following year he took part in two events, at first losing to Blake in Chicago, and the next day defeating Mardy Fish, but losing to Roddick in Charleston.In 2009, in Macau Agassi and Sampras met for the first time on court since the 2002 US Open final. Sampras won the exhibition in three sets. The rivalry between the former champions headlined sports media again in March 2010 after the two participated in the "Hit for Haiti" charity event organized to raise money for the victims of the earthquake. Partnered with Roger Federer and Rafael Nadal, the old rivals began making jokes at each other's expense, which ended up with Sampras intentionally striking a serve at Agassi's body. After the event, Agassi admitted that he had crossed the line with his jokes and publicly apologized to Sampras. Agassi and Sampras met again one year later for an exhibition match at Madison Square Garden in New York in front of 19 000 spectators as Sampras defeated Agassi in two sets. On March 3, 2014, Agassi and Sampras squared off for an exhibition in London for the annual World Tennis Day. This time, it was Agassi who came out on top in two straight sets.He returned to the tour in May 2017 in the position of coach to Novak Djokovic for the French Open. Agassi announced the end of the partnership on March 31, 2018, stating that there were too many disagreements in the relationship.Playing styleEarly in his career, Agassi would look to end points quickly by playing first-strike tennis, typically by inducing a weak return with a deep, hard shot, and then playing a winner at an extreme angle. On the rare occasion that he charged the net, Agassi liked to take the ball in the air and hit a swinging volley for a winner. His favored groundstroke was his flat, accurate two-handed backhand, hit well cross-court but especially down the line. His forehand was nearly as strong, especially his inside-out to the ad court.Agassi's strength was in dictating play from the baseline, and he was able to consistently take the ball on the rise. While he was growing up, his father and Nick Bollettieri trained him in this way. When in control of a point, Agassi would often pass up an opportunity to attempt a winner and hit a conservative shot to minimize his errors, and to make his opponent run more. This change to more methodical, less aggressive baseline play was largely initiated by his longtime coach, Brad Gilbert, in their first year together in 1994. Gilbert encouraged Agassi to wear out opponents with his deep, flat groundstrokes and to use his fitness to win attrition wars, and noted Agassi's two-handed backhand down the line as his very best shot. A signature play later in his career was a change-up drop shot to the deuce court after deep penetrating groundstrokes. This would often be followed by a passing shot or lob if the opponent was fast enough to retrieve it.Agassi was raised on hardcourts, but found much of his early major-tournament success on the red clay of Roland Garros, reaching two consecutive finals there early in his career. Despite grass being his worst surface, his first major win was at the slick grass of Wimbledon in 1992, a tournament that he professed to hating at the time. His strongest surface over the course of his career, was indeed hardcourt, where he won six of his eight majors.Business venturesAgassi established a limited liability company named Andre Agassi Ventures (formerly named Agassi Enterprises). Agassi, along with five athlete partners (including Wayne Gretzky, Joe Montana, Shaquille O'Neal, Ken Griffey, Jr., and Monica Seles) opened a chain of sports-themed restaurant named Official All Star Café in April 1996. The restaurant closed down in 2001.In 1999, he paid $1 million for a 10 percent stake in Nevada First Bank and made a $10 million profit when it was sold to Western Alliance Bancorp in 2006.In 2002, he joined the Tennis Channel to promote the channel to consumers and cable and satellite industry, and made an equity investment in the network. After meeting chef Michael Mina at one of his restaurants in San Francisco, Agassi partnered with him in 2002 to start Mina Group Inc. and opened 18 concept restaurants in San Francisco, San Jose, Dana Point, Atlantic City and Las Vegas. Agassi was an equity investor of a group that acquired Golden Nugget Las Vegas and Golden Nugget Laughlin from MGM Mirage for $215 million in 2004. One year later, the group sold the hotel-casino to Landry's, Inc. for $163 million in cash and $182 million in assumed debt. In 2007, he sat on the board of Meadows Bank, an independent bank in Nevada. He has invested in start-up companies backed by Allen & Company.Agassi and Graf formed a company called Agassi Graf Holdings. They invested in PURE, a nightclub at Caesars Palace, which opened in 2004, and sold it to Angel Management Group in 2010. In August 2006, Agassi and Graf developed a joint venture with high-end furniture maker Kreiss Enterprises. They launched a furniture line called Agassi Graf Collection. In September, Agassi and Graf, through their company Agassi Graf Development LLC, along with Bayview Financial LP, finalized an agreement to develop a condominium hotel, Fairmont Tamarack, at Tamarack Resort in Donnelly, Idaho. Owing to difficult market conditions and delays, they withdrew from the project in 2009. The group still owns three small chunks of land. In September, they collaborated with Steve Case's Exclusive Resorts to co-develop luxury resorts and design Agassi-Graf Tennis and Fitness Centers.They also invested in online ticket reseller viagogo in 2009 and both serve as board members and advisors of the company.In October 2012, Village Roadshow and investors including Agassi and Graf announced plans to build a new water park called Wet'n'Wild Las Vegas in Las Vegas. Village Roadshow has a 51% stake in the park while Agassi, Graf, and other private investors hold the remaining 49%. The park opened in May 2013.IMG managed Agassi from the time he turned pro in 1986 through January 2000 before switching to SFX Sports Group. His business manager, lawyer and agent was childhood friend Perry Rogers, but they have been estranged since 2008. In 2009, he and Graf signed with CAA.Equipment and endorsementsAgassi used Prince Graphite rackets early in his career. He signed a $7 million endorsement contract with Belgian tennis racquet makers Donnay. He later switched to Head Ti Radical racket and Head's LiquidMetal Radical racket, having signed a multimillion-dollar endorsement deal with Head in 1993. He renewed his contract in 1999, and in November 2003 he signed a lifetime agreement with Head. He also endorses Penn tennis balls. On July 25, 2005, Agassi left Nike after 17 years and signed an endorsement deal with Adidas. A major reason for Agassi leaving Nike was because Nike refused to donate to Agassi's charities, and Adidas was more than happy to do so. On May 13, 2013, Agassi rejoined Nike.Agassi was sponsored by DuPont, Ebel, Mountain Dew in 1993, Mazda in 1997, Kia Motors in 2002, American Express and Deutsche Bank in 2003. In 1990, he appeared in a television commercial for Canon Inc., promoting the Canon EOS Rebel camera. Between 1999 and 2000, he signed a multimillion-dollar, multiyear endorsement deal with Schick and became the worldwide spokesman for the company. Agassi signed a multiyear contract with Twinlab and promoted the company's nutritional supplements. In mid-2003, he was named the spokesman of Aramis Life, a fragrance by Aramis, and signed a five-year deal with the company. In March 2004, he signed a ten-year agreement worth $1.5 million a year with 24 Hour Fitness, which will open five Andre Agassi fitness centers by year-end. Prior to the 2012 Australian Open, Agassi and Australian winemaker Jacobs Creek announced a three-year partnership and created the Open Film Series to "[share] personal stories about the life defining moments that shaped his character on and off the court." In 2007, watchmaker Longines named Agassi as their brand ambassador.Agassi and his mother appeared in a Got Milk? advertisement in 2002.Agassi has appeared in many advertisements and television commercials with Graf. They both endorsed Deutsche Telekom in 2002, Genworth Financial and Canon Inc. in 2004, LVMH in 2007, and Nintendo Wii and Wii Fit U and Longines in 2013.Personal lifeRelationships and familyIn the early 1990s, after dating Wendi Stewart, Agassi dated American singer and entertainer Barbra Streisand. He wrote about the relationship in his 2009 autobiography, "We agree that we're good for each other, and so what if she's twenty-eight years older? We're sympatico, and the public outcry only adds spice to our connection. It makes our friendship feel forbidden, taboo – another piece of my overall rebellion. Dating Barbra Streisand is like wearing Hot Lava."He was married to Brooke Shields from 1997 to 1999.He married Steffi Graf on October 22, 2001, at their Las Vegas home; the only witnesses were their mothers. They have two children: son Jaden Gil (born 2001) and daughter Jaz Elle (born 2003). Agassi has said that he and Graf are not pushing their children toward becoming tennis players. The Graf-Agassi family resides in Summerlin, a community in the Las Vegas Valley. Graf's mother and brother, Michael, with his four children, also live there.Long-time trainer Gil Reyes has been called one of Agassi's closest friends; some have described him as being a "father figure" to Agassi. In 2012, Agassi and Reyes introduced their own line of fitness equipment, BILT By Agassi and Reyes. In December 2008, Agassi's childhood friend and former business manager, Perry Rogers, sued Graf for $50,000 in management fees he claimed that she owed him.AutobiographyAgassi's autobiography, Open: An Autobiography, (written with assistance from J. R. Moehringer), was published in November 2009. In it, Agassi talks about his childhood and his unconventional Armenian father, who came to the United States from Iran where he was a professional boxer. Overly demanding and emotionally abusive to the whole family, his father groomed young Agassi for tennis greatness by building a tennis court in their backyard and sending Agassi to tennis boarding school under the supervision of Nick Bollettieri, who later coached and managed part of Agassi's professional career.There is also mention in the book of using and testing positive for methamphetamine in 1997. In response to this revelation, Roger Federer declared himself shocked and disappointed, while Marat Safin argued that Agassi should return his prize money and be stripped of his titles. In an interview with CBS, Agassi justified himself and asked for understanding, saying that "It was a period in my life where I needed help."Agassi said that he had always hated tennis during his career because of the constant pressure it exerted on him. He also said he wore a hairpiece earlier in his career and thought Pete Sampras was "robotic".The book reached No. 1 on the New York Times Best Seller list and received favorable reviews. It won the Autobiography category of the 2010 British Sports Book Awards. In 2018, the book was listed on Esquire as one of "The 30 Best Sports Books Ever Written", and was also recommended by self-help author Tim Ferriss who described it as "very candid, very amusing, and very instructional".In mediaIn 2017, Agassi appeared in the documentary film Love Means Zero, which highlighted the troubled relationship between his coach Nick Bollettieri and him.PoliticsAgassi has donated more than $100,000 to Democratic candidates, and $2,000 to Republicans. On September 1, 2010, when he appeared on daily WNYC public radio program The Brian Lehrer Show, he stated that he is registered as Independent.PhilanthropyAgassi founded the Andre Agassi Charitable Association in 1994, which assists Las Vegas' young people. He was awarded the ATP Arthur Ashe Humanitarian award in 1995 for his efforts to help disadvantaged youth. He has been cited as the most charitable and socially involved player in professional tennis. It has also been claimed that he may be the most charitable athlete of his generation.Agassi's charities help in assisting children reach their athletic potential. His Boys & Girls Club sees 2,000 children throughout the year and boasts a world-class junior tennis team. It also has a basketball program (the Agassi Stars) and a rigorous system that encourages a mix of academics and athletics.In 2001, Agassi opened the Andre Agassi College Preparatory Academy in Las Vegas, a tuition-free charter school for at-risk children in the area. He personally donated $35 million to the school. In 2009, the graduating class had a 100 percent graduation rate and expected a 100 percent college acceptance rate. Among other child-related programs that Agassi supports through his Andre Agassi Charitable Foundation is Clark County's only residential facility for abused and neglected children, Child Haven. In 1997, Agassi donated funding to Child Haven for a six-room classroom building now named the Agassi Center for Education. His foundation also provided $720,000 to assist in the building of the Andre Agassi Cottage for Medically Fragile Children. This 20-bed facility opened in December 2001, and accommodates developmentally delayed or handicapped children and children quarantined for infectious diseases.In 2007, along with several other athletes, Agassi founded the charity Athletes for Hope, which helps professional athletes get involved in charitable causes and aims to inspire all people to volunteer and support their communities. He created the Canyon-Agassi Charter School Facilities Fund, now known as the Turner-Agassi Charter School Facilities Fund. The Fund is an investment initiative for social change, focusing on the "nationwide effort to move charters from stopgap buildings into permanent campuses."In September 2013, the Andre Agassi Foundation for Education formed a partnership with V20 Foods to launch Box Budd!es, a line of kids' healthy snacks. All proceeds go to the Foundation.In February 2014, Agassi remodeled the vacant University of Phoenix building in Las Vegas as a new school, called the Doral Academy West through the Canyon-Agassi Charter School Facilities Fund. Doral Academy opened in August 2014. The Fund purchased a 4.6-acre plot in Henderson, Nevada to house the Somerset Academy of Las Vegas, which will relocate from its campus inside a church.Career statisticsSingles performance timelineGrand Slam finals (8 titles, 7 runners-up)By winning the 1999 French Open, Agassi completed a men's singles Career Grand Slam. He is the 5th of 8 male players in history (after Budge, Perry, Laver and Emerson, and before Federer, Nadal and Djokovic) to achieve this.Open Era records These records were attained in the Open Era of tennis and in ATP World Tour Masters 1000 series since 1990. Records in bold indicate peer-less achievements.LegacyConsidered by numerous sources to be one of the greatest tennis players of all time, Agassi has also been called one of the greatest service returners ever to play the game, and was described by the BBC upon his retirement as "perhaps the biggest worldwide star in the sport's history". As a result, he is credited for helping to revive the popularity of tennis during the 1990s.Professional awards ITF World Champion: 1999. ATP Player of the Year: 1999. ATP Most Improved Player: 1988, 1998Recognition In 1992, Agassi was named the BBC Overseas Sports Personality of the Year. In 2010, Sports Illustrated named Agassi the 7th greatest male player of all time. On July 9, 2011, Agassi was inducted into the International Tennis Hall of Fame at a ceremony in Newport, Rhode Island.Video Wimbledon 2000 Semi-final – Agassi vs. Rafter (2003) Starring: Andre Agassi, Patrick Rafter; Standing Room Only, DVD Release Date: August 16, 2005, Run Time: 213 minutes, . Charlie Rose with Andre Agassi (May 7, 2001) Charlie Rose, Inc., DVD Release Date: August 15, 2006, Run Time: 57 minutes. Wimbledon: The Record Breakers (2005) Starring: Andre Agassi, Boris Becker; Standing Room Only, DVD Release Date: August 16, 2005, Run Time: 52 minutes, .Video games Andre Agassi Tennis for the SNES, Sega Genesis, Sega Game Gear, Master System, and Mobile phone Agassi Tennis Generation for PS2 and GBA Agassi Tennis Generation 2002 for Windows Smash Court Pro Tournament for PS2 Top Spin 4 (On cover of game) for Xbox 360, PlayStation 3 and WiiSee also Agassi–Sampras rivalry All-time tennis records – men's singles List of Grand Slam Men's Singles champions Tennis male players statistics Tennis records of the Open Era – men's singlesExplanatory notesReferencesFurther readingExternal links Andre Agassi Ventures Farewell to Tennis Speech at the U.S. Open Agassi's Tennis Hall of Fame Induction for Steffi Graf 1970 birthsLiving people20th-century American businesspeople21st-century American businesspeopleAmerican autobiographersAmerican investorsAmerican male tennis playersAmerican people of Iranian descentAmerican people of Iranian-Assyrian descentAmerican sportspeople of Armenian descentAmerican real estate businesspeopleAmerican sportspeople in doping casesArmenian-American tennis playersAssyrian sportspeopleAustralian Open (tennis) championsDoping cases in tennisEthnic Armenian sportspeopleFrench Open championsGrand Slam (tennis) champions in men's singlesInternational Tennis Hall of Fame inducteesIranian Assyrian peopleIranian people of Armenian descentMedalists at the 1996 Summer OlympicsNevada DemocratsNovak Djokovic coachesOlympic gold medalists for the United States in tennisPhilanthropists from NevadaSportspeople from Las VegasSportspeople of Iranian descentSteffi GrafTennis people from NevadaTennis players at the 1996 Summer OlympicsUS Open (tennis) championsWimbledon championsWorld No. 1 tennis playersWriters from Las Vegas \ No newline at end of file +Andre Kirk Agassi ( ; born April 29, 1970) is an American former world No. 1 tennis player. He is an eight-time major champion and a 1996 Olympic gold medalist, as well as a runner-up in seven other Grand Slam tournaments.Agassi was the first man to win four Australian Open singles titles in the Open Era (though later surpassed by Novak Djokovic, who won his fifth title in 2015 and has since won the tournament nine times). Agassi is the second of five men to achieve the career Grand Slam in the Open Era and the fifth of eight overall to make the achievement. He is also the first of two men to achieve the career Golden Slam (career Grand Slam and Olympic gold medal), and the only man to win a career Super Slam (career Grand Slam, plus the Olympic gold medal and the year-end championships).Agassi was the first man to win all four singles majors on three different surfaces (hard, clay and grass), and remains the most recent American man to win the French Open (in 1999) and the Australian Open (in 2003). He also won 17 ATP Masters Series titles and was part of the winning Davis Cup teams in 1990, 1992 and 1995. Agassi reached the world No. 1 ranking for the first time in 1995 but was troubled by personal issues during the mid-to-late 1990s and sank to No. 141 in 1997, prompting many to believe that his career was over. Agassi returned to No. 1 in 1999 and enjoyed the most successful run of his career over the next four years. During his 20-plus year tour career, Agassi was known by the nickname "The Punisher".After suffering from sciatica caused by two bulging discs in his back, a spondylolisthesis (vertebral displacement) and a bone spur that interfered with the nerve, Agassi retired from professional tennis on September 3, 2006, after losing in the third round of the US Open. He is the founder of the Andre Agassi Charitable Foundation, which has raised over $60 million for at-risk children in Southern Nevada. In 2001, the Foundation opened the Andre Agassi College Preparatory Academy in Las Vegas, a K–12 public charter school for at-risk children. He has been married to fellow tennis player Steffi Graf since 2001.1970–1985: Early lifeAndre Agassi was born in Las Vegas, Nevada, to Emmanuel "Mike" Agassi, a former Olympic boxer from Iran and American Elizabeth "Betty" Agassi (née Dudley). His father is of Armenian and Assyrian heritage. Andre Agassi's mother, Betty, is a breast cancer survivor. He has three older siblings – Rita (last wife of former number one Pancho Gonzales), Philip and Tami. Andre was given the middle name Kirk after Kirk Kerkorian, an Armenian American billionaire. Emmanuel Agassi, then a waiter at Tropicana Las Vegas, had met Kerkorian in 1963.At the age of 12, Agassi and his good friend and doubles partner, Roddy Parks, won the 1982 National Indoor Boys 14s Doubles Championship in Chicago. Agassi describes memorable experiences and juvenile pranks with Roddy in his book Open.When he was 13, Agassi was sent to Nick Bollettieri's Tennis Academy in Florida. He was meant to stay for only three months, because that was all his father could afford. After thirty minutes of watching Agassi play, Bollettieri, deeply impressed by his talent, called Mike and said: "Take your check back. He's here for free." Agassi then dropped out of school in the ninth grade to pursue a full-time tennis career.1986–2006: Professional career1986–1993: Breakthrough and the first major titleAgassi turned professional at the age of 16 and competed in his first tournament at La Quinta, California. He won his first match against John Austin, but then lost his second match to Mats Wilander. By the end of 1986, Agassi was ranked No. 91. He won his first top-level singles title in 1987 at the Sul American Open in Itaparica and ended the year ranked No. 25. He won six additional tournaments in 1988 (Memphis, U.S. Men's Clay Court Championships, Forest Hills WCT, Stuttgart Outdoor, Volvo International and Livingston Open), and, by December of that year, he had surpassed US$1 million in career prize money after playing in just 43 tournaments—the fastest anyone in history had reached that level. During 1988, he also set the open-era record for most consecutive victories by a male teenager (a record that stood for 17 years until Rafael Nadal broke it in 2005). His year-end ranking was No. 3, behind second-ranked Ivan Lendl and top-ranked Mats Wilander. Both the Association of Tennis Professionals and Tennis magazine named Agassi the Most Improved Player of the Year for 1988.In addition to not playing the Australian Open (which later became his best Grand Slam event) for the first eight years of his career, Agassi chose not to play at Wimbledon from 1988 through 1990 and publicly stated that he did not wish to play there because of the event's traditionalism, particularly its "predominantly white" dress code to which players at the event are required to conform.Strong performances on the tour meant that Agassi was quickly tipped as a future Grand Slam champion. While still a teenager, he reached the semi-finals of both the French Open and the US Open in 1988 and made the US Open semi-finals in 1989. He began the 1990s with a series of near-misses. He reached his first Grand Slam final in 1990 at the French Open, where he was favored before losing in four sets to Andrés Gómez, which he later attributed in his book to worrying about his wig falling off during the match. He reached his second Grand Slam final of the year at the US Open, defeating defending champion Boris Becker in the semi-finals. His opponent in the final was Pete Sampras; a year earlier, Agassi had crushed Sampras, after which time he told his coach that he felt bad for Sampras because he was never going to make it as a pro. Agassi lost the US Open final to Sampras in three sets. The rivalry between these two American players became the biggest one in tennis over the rest of the decade. Agassi ended 1990 on a high note as he helped the United States win its first Davis Cup in 8 years and won his only Tennis Masters Cup, beating reigning Wimbledon champion Stefan Edberg in the final.In 1991, Agassi reached his second consecutive French Open final, where he faced fellow Bollettieri Academy alumnus Jim Courier. Courier emerged the victor in a five-set final. Agassi decided to play at Wimbledon in 1991, leading to weeks of speculation in the media about the clothes he would wear. He eventually emerged for the first round in a completely white outfit. He reached the quarterfinals on that occasion, losing in five sets to David Wheaton.Agassi's Grand Slam tournament breakthrough came at Wimbledon, not at the French Open or the US Open, where he had previously enjoyed success. In 1992, he defeated Goran Ivanišević in a five-set final. Along the way, Agassi overcame two former Wimbledon champions: Boris Becker and John McEnroe. No other baseliner would triumph at Wimbledon until Lleyton Hewitt ten years later. Agassi was named the BBC Overseas Sports Personality of the Year in 1992. Agassi once again played on the United States' Davis Cup winning team in 1992. It was their second Davis cup title in three years. Agassi famously played the game wearing Oakley brand sunglasses, and a photo of him from the day appeared on the cover of Tennis magazine. In his memoir, he wrote that he was covering up bloodshot eyes from a hangover and claimed that the founder of Oakley, Jim Jannard, had sent him a Dodge Viper to thank him for the inadvertent publicity.In 1993, Agassi won the only doubles title of his career, at the Cincinnati Masters, partnered with Petr Korda. He missed much of the early part of that year due to injuries. Although he made the quarterfinals in his Wimbledon title defense, he lost to eventual champion and No. 1 Pete Sampras in five sets. Agassi lost in the first round at the US Open to Thomas Enqvist and required wrist surgery late in the year.1994–1997: Rise to the top, Olympic Gold and the fallWith new coach Brad Gilbert on board, Agassi began to employ more of a tactical, consistent approach, which fueled his resurgence. He started slowly in 1994, losing in the first week at the French Open and Wimbledon. Nevertheless, he emerged during the hard-court season, winning the Canadian Open. His comeback culminated at the 1994 US Open with a five-set fourth-round victory against Michael Chang. He then became the first man to capture the US Open as an unseeded player, beating Michael Stich in the final. Along the way, he beat 5 seeded players.In 1995, Agassi shaved his balding head, breaking with his old "image is everything" style. He competed in the 1995 Australian Open (his first appearance at the event) and won, beating Sampras in a four-set final. Agassi and Sampras met in five tournament finals in 1995, all on hardcourt, with Agassi winning three. Agassi won three Masters Series events in 1995 (Cincinnati, Key Biscayne, and the Canadian Open) and seven titles total. He compiled a career-best 26-match winning streak during the summer hard-court circuit, with the last victory being in an intense late-night four-set semi-final of the US Open against Boris Becker. The streak ended the next day when Agassi lost the final to Sampras.Agassi reached the world No. 1 ranking for the first time in April 1995. He held that ranking until November, for a total of 30 weeks. Agassi skipped most of the fall indoor season which allowed Sampras to surpass him and finish ranked No. 1 at the year-end ranking. In terms of win/loss record, 1995 was Agassi's best year. He won 73 and lost 9 matches, and was also once again a key player on the United States' Davis Cup winning team—the third and final Davis Cup title of his career.1996 was a less successful year for Agassi, as he failed to reach any Grand Slam final. He suffered two early-round losses to Chris Woodruff and Doug Flach at the French Open and Wimbledon, respectively, and lost to Chang in straight sets in the Australian and US Open semi-finals. At the time, Agassi blamed the Australian Open loss on the windy conditions, but later said in his biography that he had lost the match on purpose, as he did not want to play Boris Becker, whom he would have faced in that final. The high point for Agassi was winning the men's singles gold medal at the Olympic Games in Atlanta, beating Sergi Bruguera of Spain in the final. Agassi also successfully defended his singles titles in Cincinnati and Key Biscayne.1997 was the low point of Agassi's career. His wrist injury resurfaced, and he played only 24 matches during the year. He later confessed that he started using crystal methamphetamine at that time, allegedly on the urging of a friend. He failed an ATP drug test, but wrote a letter claiming the same friend had spiked a drink. The ATP dropped the failed drug test as a warning. In his autobiography, Agassi admitted that the letter was a lie. He quit the drug soon after. At this time Agassi was also in a failing marriage with actress, model, and socialite Brooke Shields and had lost interest in the game. He won no top-level titles, and his ranking sank to No. 141 on November 10, 1997, prompting many to believe that his run as one of the sport's premier competitors was over and he would never again win any significant championships.1998–2003: Return to glory and Career Super SlamIn 1998, Agassi began a rigorous conditioning program and worked his way back up the rankings by playing in Challenger Series tournaments, a circuit for pro players ranked outside the world's top 50. After returning to top physical and mental shape, Agassi recorded the most successful period of his tennis career and also played classic matches in that period against Pete Sampras and Patrick Rafter.In 1998, Agassi won five titles and leapt from No. 110 to No. 6, the highest jump into the top 10 made by any player during a calendar year. At Wimbledon, he had an early loss in the second round to Tommy Haas. He won five titles in ten finals and was runner-up at the Masters Series tournament in Key Biscayne, losing to Marcelo Ríos, who became No. 1 as a result. At the year end he was awarded the ATP Most Improved Player of the Year for the second time in his career (the first being 10 years earlier in 1988).Agassi entered the history books in 1999 when he came back from two sets to love down to beat Andrei Medvedev in a five-set French Open final, becoming, at the time, only the fifth male player (joining Rod Laver, Fred Perry, Roy Emerson and Don Budge—these have since been joined by Roger Federer, Rafael Nadal, and Novak Djokovic) to win all four Grand Slam singles titles during his career. Only Laver, Agassi, Federer, Nadal and Djokovic have achieved this feat during the Open Era. This win also made him the first (of only four, the next being Federer, Nadal and Djokovic respectively) male player in history to have won all four Grand Slam titles on three different surfaces (clay, grass and hard courts). Agassi also became the only male player to win the Career Super Slam, consisting of all four Grand Slam tournaments plus an Olympic gold medal in singles and a Year-end championship.Agassi followed his 1999 French Open victory by reaching the Wimbledon final, where he lost to Sampras in straight sets. He rebounded from his Wimbledon defeat by winning the US Open, beating Todd Martin in five sets (rallying from a two sets to one deficit) in the final. Overall during the year Agassi won 5 titles including two majors and the ATP Masters Series in Paris, where he beat Marat Safin. Agassi ended 1999 as the No. 1, ending Sampras's record of six consecutive year-ending top rankings (1993–98). This was the only time Agassi ended the year at No. 1. Agassi was runner-up to Sampras at the year-end Tennis Masters Cup losing 1–6, 5–7, 4-6 despite beating Sampras in the round-robin 6–2, 6–2.He began the next year 2000 by capturing his second Australian Open title, beating Sampras in a five-set semi-final and Yevgeny Kafelnikov in a four-set final. He was the first male player to have reached four consecutive Grand Slam finals since Rod Laver achieved the Grand Slam in 1969. At the time, Agassi was also only the fourth player since Laver to be the reigning champion of three of four Grand Slam events, missing only the Wimbledon title.. 2000 also saw Agassi reach the semi-finals at Wimbledon, where he lost in five sets to Rafter in a match considered by many to be one of the best ever at Wimbledon. At the inaugural Tennis Masters Cup in Lisbon, Agassi reached the final after defeating Marat Safin in the semi-finals to end the Russian's hopes to become the youngest No. 1 in the history of tennis. Agassi then lost to Gustavo Kuerten in the final, allowing Kuerten to be crowned year-end No. 1.Agassi opened 2001 by successfully defending his Australian Open title with a straight-sets final win over Arnaud Clément. En route, he beat a cramping Rafter in five sets in front of a sell-out crowd in what turned out to be the Aussie's last Australian Open. At Wimbledon, they met again in the semi-finals, where Agassi lost another close match to Rafter, 8–6 in the fifth set. In the quarterfinals at the US Open, Agassi lost a 3-hour, 33 minute epic match with Sampras, 7–6, 6–7, 6–7, 6–7, with no breaks of serve during the 52-game match. Despite the setback, Agassi finished 2001 ranked No. 3, becoming the only male tennis player to finish a year ranked in the top 3 in three different decades.2002 opened with disappointment for Agassi, as injury forced him to skip the Australian Open, where he was a two-time defending champion. Agassi recovered from the injury and later that year defended his Key Biscayne title beating then rising Roger Federer in a four-set final. The last duel between Agassi and Sampras came in the final of the US Open, which Sampras won in four sets and left Sampras with a 20–14 edge in their 34 career meetings. The match was the last of Sampras's career. Agassi's US Open finish, along with his Masters Series victories in Key Biscayne, Rome and Madrid, helped him finish 2002 as the oldest year-end No. 2 at 32 years and 8 months.In 2003, Agassi won the eighth (and final) Grand Slam title of his career at the Australian Open, where he beat Rainer Schüttler in straight sets in the final.On April 28, 2003, he recaptured the No. 1 ranking to become the oldest top-ranked male player since the ATP rankings began at 33 years and 13 days. The record was later surpassed by Roger Federer in 2018. He had held the No. 1 ranking for two weeks, when Lleyton Hewitt took it back on May 12, 2003. Agassi then recaptured the No. 1 ranking once again on June 16, 2003, which he held for 12 weeks until September 7, 2003. There he managed to reach the US Open semi-finals, where he lost to Juan Carlos Ferrero, surrendering his No. 1 ranking to him. During his career, Agassi held the ranking for a total of 101 weeks. Agassi's ranking slipped when injuries forced him to withdraw from a number of events. At the year-end Tennis Masters Cup, Agassi lost in the final to Federer, his third time to finish as runner-up in the event after losses in 1999 and 2000, and finished the year ranked No. 4. At age 33, he had been one of the oldest players to rank in the top 5 since Connors, at age 35, was No. 4 in 1987.2004–2006: Final yearsIn 2004, Agassi began the year with a five-set loss in the semi-finals of the Australian Open to Marat Safin; the loss ended Agassi's 26-match winning streak at the event. He won the Masters series event in Cincinnati to bring his career total to 59 top-level singles titles and a record 17 ATP Masters Series titles, having already won seven of the nine ATP Masters tournament—all except the tournaments in Monte Carlo and Hamburg. At 34, he became the second-oldest singles champion in Cincinnati tournament history (the tournament began in 1899), tied with Roger Federer and surpassed only by Ken Rosewall, who won the title in 1970 at age 35. He finished the year ranked No. 8, one of the oldest players to finish in the top 10 since the 36-year-old Connors was No. 7 in 1988. At the time, Agassi also became the sixth male player during the open era to reach 800 career wins with his first-round victory over Alex Bogomolov in Countrywide Classic in Los Angeles.Agassi's 2005 began with a quarterfinal loss to Federer at the Australian Open. Agassi had several other deep runs at tournaments, but had to withdraw from several events due to injury. He lost to Jarkko Nieminen in the first round of the French Open. He won his fourth title in Los Angeles and reached the final of the Rogers Cup, before falling to No. 2 Rafael Nadal.Agassi's 2005 was defined by an improbable run to the US Open final. After beating Răzvan Sabău and Ivo Karlović in straight sets and Tomáš Berdych in four sets, Agassi won three consecutive five-set matches to advance to the final. The most notable of these matches was his quarterfinal victory over James Blake, where he rallied from two sets down to win in the fifth set tie-breaker. His other five-set victories were on Xavier Malisse in the fourth round and Robby Ginepri in the semi-finals. In the final, Agassi faced Federer, who was seeking his second consecutive US Open title and his sixth Grand Slam title in two years. Federer defeated Agassi in four sets. Agassi finished 2005 ranked No. 7, his 16th time in the year-end top-10 rankings, which tied Connors for the most times ranked in the top 10 at year's end.Agassi had a poor start to 2006, as he was still recovering from an ankle injury and also suffering from back and leg pain and lack of match play. Agassi withdrew from the Australian Open because of the ankle injury, and his back injury and other pains forced him to withdraw from several other events, eventually skipping the entire clay-court season including the French Open. This caused his ranking to drop out of the top 10 for the last time. Agassi returned for the grass-court season, playing a tune-up, and then Wimbledon. He was defeated in the third round by world No. 2 (and eventual runner-up) Rafael Nadal. Against conventions, Agassi, the losing player, was interviewed on court after the match. At Wimbledon, Agassi announced his plans to retire following the US Open. Agassi played only two events during the summer hard-court season with his best result being a quarterfinal loss at the Countrywide Classic in Los Angeles to Fernando González of Chile, which resulted in him being unseeded at the US Open.Agassi had a short, but dramatic, run in his final US Open. Because of extreme back pain, Agassi was forced to receive anti-inflammatory injections after every match. After a tough four-set win against Andrei Pavel, Agassi faced eighth-seeded Marcos Baghdatis in the second round who had earlier advanced to the 2006 Australian Open final and Wimbledon semi-finals. Agassi won in five tough sets as the younger Baghdatis succumbed to muscle cramping in the final set. In his last match, Agassi fell to 112th-ranked big-serving Benjamin Becker of Germany in four sets. Agassi received a four-minute standing ovation from the crowd after the match and delivered a retirement speech.RivalriesAgassi vs. SamprasThe rivalry has been called the greatest of the generation of players competing in the 1990s, as Sampras and Agassi were the most successful players of that decade. They also had very contrasting playing styles, with Sampras being considered the greatest server and Agassi the greatest serve returner at the time. Agassi and Sampras met 34 times on the tour level with Agassi trailing 14–20.The 1990 US Open was their first meeting in a Grand Slam tournament final. Agassi was favored as he was ranked No. 4 at the time, compared to the No. 12 ranking of Sampras and because Agassi had defeated Sampras in their only previously completed match. Agassi, however, lost the final to Sampras in straight sets. Their next meeting in a Grand Slam was at the 1992 French Open, where they met in the quarterfinals. Although Sampras was ranked higher, Agassi came out winning in straight sets. They met again on a Grand Slam level at the quarterfinals of Wimbledon in 1993, where Agassi was the defending champion and Sampras was the newly minted world No. 1. Agassi dug himself out from a two-sets-to-love hole, levelling the match at two sets apiece; however, Sampras prevailed in five sets, and went on to win his first Wimbledon championship.With both Sampras and Agassi participating, the US won the Davis Cup in 1995. The year should be considered the peak of the rivalry as together they won three out of four major titles, meeting each other twice in the finals, and were occupying the top two spots in the rankings for the whole year. They met five times during the year, all in the title matches, including the Australian Open, the Newsweek Champions Cup (now Indian Wells), the Lipton International Players Championships (now Miami Open), the Canadian Open, and the US Open. Agassi won three of the finals, including the Australian Open; however, Sampras took the US Open title, ending Agassi's 26-match winning streak. After Agassi had taken most of the fall season off, Sampras took over the No. 1 ranking for the end of the season.In the following three years, while Sampras continued winning Grand Slam titles every season, Agassi slumped in the rankings and struggled in major competitions. The next time Sampras and Agassi met in a Grand Slam final was at Wimbledon in 1999, where Sampras won in straight sets. For both, it was considered a career rejuvenation, as Sampras had suffered a string of disappointments in the previous year while Agassi was regaining his status as a top-ranked player after winning the French Open. Sampras forfeited the No. 1 ranking to Agassi when injury forced him to withdraw from that year's US Open, which Agassi went on to win. They faced each other twice in the season-ending ATP Tour World Championships, with Sampras losing the round-robin match, but winning the final.In the 2000s, they met three more times on the Grand Slam level offering three memorable contests. In 2000, the top-ranked Agassi defeated No. 3 Sampras in the semi-finals of the Australian Open in five sets, which was an important win for Agassi who had lost 4 of the previous five matches against Sampras. In arguably their most memorable match ever, Sampras defeated Agassi in the 2001 US Open quarterfinals in four sets. There were no breaks of serve during the entire match. Reruns of the match are frequently featured on television, especially during US Open rain delays, and the match is considered one of the best in history because of the level of play presented by both players.Their last meeting was the final of the 2002 US Open, which was their third meeting in a US Open final, but the first since 1995. The match was also notable because they had defeated several up-and-coming players en route to the final. Sampras had defeated No. 3 Tommy Haas in the fourth round and future No. 1 Andy Roddick in the quarterfinals, while Agassi had defeated No. 1 and defending champion Lleyton Hewitt in the semi-finals. Sampras defeated Agassi in four sets. This was the final ATP tour singles match of Sampras's career.Agassi vs. ChangMichael Chang was the opponent Agassi faced most frequently from all the players other than Sampras. They met 22 times on the tour level with Agassi leading 15–7. Chang, unlike most of Agassi's big rivals, had a playing style similar to his. Both players preferred to stay at the baseline with Chang being more defensive-minded. The outcome was that most of their meetings were built on long and entertaining rallies. The rivalry began late in the 1980s with both players being considered the prodigies of the next great generation of American tennis players and both having foreign descent.Agassi won the first four matches including a straight-set victory in round 16 of the 1988 US Open and defeating Chang, the defending champion, in the 1990 French Open in a four-set quarterfinal. Arguably their best match took place in the round of 16 of the 1994 US Open. While both players presented high-quality shot-making, the momentum changed from set to set with Agassi eventually prevailing in a five-set victory. It turned out to be the toughest contest on his way to his first US Open title. Their next two Grand Slam meetings came in 1996, with Chang recording easy straight-set victories in the semi-finals of both the Australian Open and the US Open. Years after, Agassi shockingly admitted in his book that he had lost the first of the matches on purpose as he did not want to face Boris Becker, who was awaiting the winner in the final. Agassi won the last four of their matches, with the last being in 2003 at the Miami Open with Chang being clearly past his prime.Agassi vs. BeckerBoris Becker and Agassi played 14 times with Agassi leading 10–4. Becker won their first three matches in 1988 and 1989 before Agassi reversed the rivalry in 1990, and won 10 of their last 11 matches. They first played at Indian Wells in 1988, with Becker prevailing. Their most notable match was the 1989 Davis Cup semi-final match, which Becker won in five sets after losing the first two in tiebreaks. Agassi, considered a baseliner with a playing style not suiting grass, shocked Becker, a three-time champion, in a five-set quarterfinal at Wimbledon in 1992 on his way to his first Grand Slam title. The intensity of the rivalry peaked in 1995. Becker won that year's Wimbledon semi-final after being down a set and two breaks, to eventually win in four sets. In a highly anticipated rematch in the US Open semi-final, this time it was Agassi who came out victorious in four tight sets. Their final match was played at Hong Kong in 1999, which Agassi won in three sets.Agassi vs. RafterAgassi and Pat Rafter played fifteen times with Agassi leading 10–5. The rivalry has been considered special and delivered memorable encounters, because of the players' contrasting styles of play, with Rafter using traditional serve-&-volley methods against Agassi's variety of return of serves and passing shots as his main weapons. Agassi led 8–2 on hard courts, but Rafter surprisingly won their sole match on clay at the 1999 Rome Masters. They played four matches at Wimbledon with both winning two matches each. Agassi won the first two in 1993 and 1999, while Rafter took their 2000 and 2001 encounters, both of the gruelling 5-setters often being presented on the lists of best matches ever played. Agassi also won both their meetings at the Australian Open, in 1995 and 2001, on his way to the title on both occasions. Rafter, however, took their only US Open encounter in 1997 and went on to win the title.Agassi vs. FedererAgassi and Roger Federer played 11 times, and Federer led their head-to-head series 8–3. With the retirement of Sampras, the rivalry against the 11-years-younger Federer, who was another great server like Sampras, became Agassi's main rivalry for the final years of his career. Agassi won their first three matches, but then went on to lose eight consecutive ones. They first met in just the third tournament of Federer's career at the 1998 Swiss Indoors in Federer's hometown, with Agassi prevailing over the 17-year-old. Agassi also defeated Federer at the 2001 US Open and the finals of the Miami Open in 2002. Federer began to turn the tide at the Masters Cup in 2003, when he defeated Agassi in both the round-robin and the final. They played a memorable quarterfinal match at the 2004 US Open that spanned over two windy days, with Federer eventually prevailing in five sets. At the 2005 Dubai Championships, Federer and Agassi attracted worldwide headlines with a publicity stunt that saw the two tennis legends play on a helipad almost 220 meters above sea level at the hotel Burj al-Arab. Their final duel took place in the final of the 2005 US Open. In the historic clash of generations, Federer was victorious in four sets in front of a pro-Agassi crowd. The match was the last appearance by Agassi in any tournament final.Agassi vs. LendlAgassi and Ivan Lendl played eight times, and Lendl led their head-to-head series 6–2.Agassi vs. EdbergAgassi and Stefan Edberg played nine times, and Agassi led their head-to-head series 6–3.EarningsAgassi earned more than $30 million in prize-money during his career, sixth only to Djokovic, Federer, Nadal, Sampras and Murray to date (May 2018). He also earned more than $25 million a year through endorsements during his career, which was ranked fourth in all sports at the time.Post-retirementSince retiring after the 2006 US Open, Agassi has participated in a series of charity tournaments and continues his work with his own charity. On September 5, 2007, he was a surprise guest commentator for the Andy Roddick/Roger Federer US Open quarterfinal. He played an exhibition match at Wimbledon, teaming with his wife, Steffi Graf, to play with Tim Henman and Kim Clijsters. He played World Team Tennis for the Philadelphia Freedoms in the summer of 2009. At the 2009 French Open, Agassi was on hand to present Roger Federer, who completed his Career Grand Slam by winning the tournament and joined Agassi as one of six men to complete the Career Grand Slam, with the trophy.Also in 2009, Agassi played at the Outback Champions Series event for the first time. He played the Cancer Treatment Centers of America Tennis Championships at Surprise, Arizona, where he reached the final before bowing to eventual champion Todd Martin. Agassi returned to the tour renamed for the PowerShares Series in 2011 and participated in a total of seven events while winning two. Agassi beat Courier in the final of the Staples Champions Cup in Boston and later defeated Sampras at the CTCA Championships at his hometown Las Vegas.In 2012, Agassi took part in five tournaments, winning three of those. In November, at first he won BILT Champions Showdown in San Jose, beating John McEnroe in the final. The following day, he defended his title of the CTCA Championships, while defeating Courier in the decisive match. In the series season finale, he beat Michael Chang for the Acura Champions Cup. The series and Agassi came back to action in 2014. Agassi won both tournaments he participated in. At the Camden Wealth Advisors Cup's final in Houston, Agassi beat James Blake for a rematch of their 2005 US Open quarterfinal. He defeated Blake again in Portland to win the title of the Cancer Treatment Centers of America Championships. In 2015, Agassi took part in just one event of the PowerShares Series, losing to Mark Philippoussis in the final of the Champions Shootout. The following year he took part in two events, at first losing to Blake in Chicago, and the next day defeating Mardy Fish, but losing to Roddick in Charleston.In 2009, in Macau Agassi and Sampras met for the first time on court since the 2002 US Open final. Sampras won the exhibition in three sets. The rivalry between the former champions headlined sports media again in March 2010 after the two participated in the "Hit for Haiti" charity event organized to raise money for the victims of the earthquake. Partnered with Roger Federer and Rafael Nadal, the old rivals began making jokes at each other's expense, which ended up with Sampras intentionally striking a serve at Agassi's body. After the event, Agassi admitted that he had crossed the line with his jokes and publicly apologized to Sampras. Agassi and Sampras met again one year later for an exhibition match at Madison Square Garden in New York in front of 19 000 spectators as Sampras defeated Agassi in two sets. On March 3, 2014, Agassi and Sampras squared off for an exhibition in London for the annual World Tennis Day. This time, it was Agassi who came out on top in two straight sets.He returned to the tour in May 2017 in the position of coach to Novak Djokovic for the French Open. Agassi announced the end of the partnership on March 31, 2018, stating that there were too many disagreements in the relationship.Playing styleEarly in his career, Agassi would look to end points quickly by playing first-strike tennis, typically by inducing a weak return with a deep, hard shot, and then playing a winner at an extreme angle. On the rare occasion that he charged the net, Agassi liked to take the ball in the air and hit a swinging volley for a winner. His favored groundstroke was his flat, accurate two-handed backhand, hit well cross-court but especially down the line. His forehand was nearly as strong, especially his inside-out to the ad court.Agassi's strength was in dictating play from the baseline, and he was able to consistently take the ball on the rise. While he was growing up, his father and Nick Bollettieri trained him in this way. When in control of a point, Agassi would often pass up an opportunity to attempt a winner and hit a conservative shot to minimize his errors, and to make his opponent run more. This change to more methodical, less aggressive baseline play was largely initiated by his longtime coach, Brad Gilbert, in their first year together in 1994. Gilbert encouraged Agassi to wear out opponents with his deep, flat groundstrokes and to use his fitness to win attrition wars, and noted Agassi's two-handed backhand down the line as his very best shot. A signature play later in his career was a change-up drop shot to the deuce court after deep penetrating groundstrokes. This would often be followed by a passing shot or lob if the opponent was fast enough to retrieve it.Agassi was raised on hardcourts, but found much of his early major-tournament success on the red clay of Roland Garros, reaching two consecutive finals there early in his career. Despite grass being his worst surface, his first major win was at the slick grass of Wimbledon in 1992, a tournament that he professed to hating at the time. His strongest surface over the course of his career, was indeed hardcourt, where he won six of his eight majors.Business venturesAgassi established a limited liability company named Andre Agassi Ventures (formerly named Agassi Enterprises). Agassi, along with five athlete partners (including Wayne Gretzky, Joe Montana, Shaquille O'Neal, Ken Griffey, Jr., and Monica Seles) opened a chain of sports-themed restaurant named Official All Star Café in April 1996. The restaurant closed down in 2001.In 1999, he paid $1 million for a 10 percent stake in Nevada First Bank and made a $10 million profit when it was sold to Western Alliance Bancorp in 2006.In 2002, he joined the Tennis Channel to promote the channel to consumers and cable and satellite industry, and made an equity investment in the network. After meeting chef Michael Mina at one of his restaurants in San Francisco, Agassi partnered with him in 2002 to start Mina Group Inc. and opened 18 concept restaurants in San Francisco, San Jose, Dana Point, Atlantic City and Las Vegas. Agassi was an equity investor of a group that acquired Golden Nugget Las Vegas and Golden Nugget Laughlin from MGM Mirage for $215 million in 2004. One year later, the group sold the hotel-casino to Landry's, Inc. for $163 million in cash and $182 million in assumed debt. In 2007, he sat on the board of Meadows Bank, an independent bank in Nevada. He has invested in start-up companies backed by Allen & Company.Agassi and Graf formed a company called Agassi Graf Holdings. They invested in PURE, a nightclub at Caesars Palace, which opened in 2004, and sold it to Angel Management Group in 2010. In August 2006, Agassi and Graf developed a joint venture with high-end furniture maker Kreiss Enterprises. They launched a furniture line called Agassi Graf Collection. In September, Agassi and Graf, through their company Agassi Graf Development LLC, along with Bayview Financial LP, finalized an agreement to develop a condominium hotel, Fairmont Tamarack, at Tamarack Resort in Donnelly, Idaho. Owing to difficult market conditions and delays, they withdrew from the project in 2009. The group still owns three small chunks of land. In September, they collaborated with Steve Case's Exclusive Resorts to co-develop luxury resorts and design Agassi-Graf Tennis and Fitness Centers.They also invested in online ticket reseller viagogo in 2009 and both serve as board members and advisors of the company.In October 2012, Village Roadshow and investors including Agassi and Graf announced plans to build a new water park called Wet'n'Wild Las Vegas in Las Vegas. Village Roadshow has a 51% stake in the park while Agassi, Graf, and other private investors hold the remaining 49%. The park opened in May 2013.IMG managed Agassi from the time he turned pro in 1986 through January 2000 before switching to SFX Sports Group. His business manager, lawyer and agent was childhood friend Perry Rogers, but they have been estranged since 2008. In 2009, he and Graf signed with CAA.Equipment and endorsementsAgassi used Prince Graphite rackets early in his career. He signed a $7 million endorsement contract with Belgian tennis racquet makers Donnay. He later switched to Head Ti Radical racket and Head's LiquidMetal Radical racket, having signed a multimillion-dollar endorsement deal with Head in 1993. He renewed his contract in 1999, and in November 2003 he signed a lifetime agreement with Head. He also endorses Penn tennis balls. On July 25, 2005, Agassi left Nike after 17 years and signed an endorsement deal with Adidas. A major reason for Agassi leaving Nike was because Nike refused to donate to Agassi's charities, and Adidas was more than happy to do so. On May 13, 2013, Agassi rejoined Nike.Agassi was sponsored by DuPont, Ebel, Mountain Dew in 1993, Mazda in 1997, Kia Motors in 2002, American Express and Deutsche Bank in 2003. In 1990, he appeared in a television commercial for Canon Inc., promoting the Canon EOS Rebel camera. Between 1999 and 2000, he signed a multimillion-dollar, multiyear endorsement deal with Schick and became the worldwide spokesman for the company. Agassi signed a multiyear contract with Twinlab and promoted the company's nutritional supplements. In mid-2003, he was named the spokesman of Aramis Life, a fragrance by Aramis, and signed a five-year deal with the company. In March 2004, he signed a ten-year agreement worth $1.5 million a year with 24 Hour Fitness, which will open five Andre Agassi fitness centers by year-end. Prior to the 2012 Australian Open, Agassi and Australian winemaker Jacobs Creek announced a three-year partnership and created the Open Film Series to "[share] personal stories about the life defining moments that shaped his character on and off the court." In 2007, watchmaker Longines named Agassi as their brand ambassador.Agassi and his mother appeared in a Got Milk? advertisement in 2002.Agassi has appeared in many advertisements and television commercials with Graf. They both endorsed Deutsche Telekom in 2002, Genworth Financial and Canon Inc. in 2004, LVMH in 2007, and Nintendo Wii and Wii Fit U and Longines in 2013.Personal lifeRelationships and familyIn the early 1990s, after dating Wendi Stewart, Agassi dated American singer and entertainer Barbra Streisand. He wrote about the relationship in his 2009 autobiography, "We agree that we're good for each other, and so what if she's twenty-eight years older? We're sympatico, and the public outcry only adds spice to our connection. It makes our friendship feel forbidden, taboo – another piece of my overall rebellion. Dating Barbra Streisand is like wearing Hot Lava."He was married to Brooke Shields from 1997 to 1999.He married Steffi Graf on October 22, 2001, at their Las Vegas home; the only witnesses were their mothers. They have two children: son Jaden Gil (born 2001) and daughter Jaz Elle (born 2003). Agassi has said that he and Graf are not pushing their children toward becoming tennis players. The Graf-Agassi family resides in Summerlin, a community in the Las Vegas Valley. Graf's mother and brother, Michael, with his four children, also live there.Long-time trainer Gil Reyes has been called one of Agassi's closest friends; some have described him as being a "father figure" to Agassi. In 2012, Agassi and Reyes introduced their own line of fitness equipment, BILT By Agassi and Reyes. In December 2008, Agassi's childhood friend and former business manager, Perry Rogers, sued Graf for $50,000 in management fees he claimed that she owed him.AutobiographyAgassi's autobiography, Open: An Autobiography, (written with assistance from J. R. Moehringer), was published in November 2009. In it, Agassi talks about his childhood and his unconventional Armenian father, who came to the United States from Iran where he was a professional boxer. Overly demanding and emotionally abusive to the whole family, his father groomed young Agassi for tennis greatness by building a tennis court in their backyard and sending Agassi to tennis boarding school under the supervision of Nick Bollettieri, who later coached and managed part of Agassi's professional career.There is also mention in the book of using and testing positive for methamphetamine in 1997. In response to this revelation, Roger Federer declared himself shocked and disappointed, while Marat Safin argued that Agassi should return his prize money and be stripped of his titles. In an interview with CBS, Agassi justified himself and asked for understanding, saying that "It was a period in my life where I needed help."Agassi said that he had always hated tennis during his career because of the constant pressure it exerted on him. He also said he wore a hairpiece earlier in his career and thought Pete Sampras was "robotic".The book reached No. 1 on the New York Times Best Seller list and received favorable reviews. It won the Autobiography category of the 2010 British Sports Book Awards. In 2018, the book was listed on Esquire as one of "The 30 Best Sports Books Ever Written", and was also recommended by self-help author Tim Ferriss who described it as "very candid, very amusing, and very instructional".In mediaIn 2017, Agassi appeared in the documentary film Love Means Zero, which highlighted the troubled relationship between his coach Nick Bollettieri and him.PoliticsAgassi has donated more than $100,000 to Democratic candidates, and $2,000 to Republicans. On September 1, 2010, when he appeared on daily WNYC public radio program The Brian Lehrer Show, he stated that he is registered as Independent.PhilanthropyAgassi founded the Andre Agassi Charitable Association in 1994, which assists Las Vegas' young people. He was awarded the ATP Arthur Ashe Humanitarian award in 1995 for his efforts to help disadvantaged youth. He has been cited as the most charitable and socially involved player in professional tennis. It has also been claimed that he may be the most charitable athlete of his generation.Agassi's charities help in assisting children reach their athletic potential. His Boys & Girls Club sees 2,000 children throughout the year and boasts a world-class junior tennis team. It also has a basketball program (the Agassi Stars) and a rigorous system that encourages a mix of academics and athletics.In 2001, Agassi opened the Andre Agassi College Preparatory Academy in Las Vegas, a tuition-free charter school for at-risk children in the area. He personally donated $35 million to the school. In 2009, the graduating class had a 100 percent graduation rate and expected a 100 percent college acceptance rate. Among other child-related programs that Agassi supports through his Andre Agassi Charitable Foundation is Clark County's only residential facility for abused and neglected children, Child Haven. In 1997, Agassi donated funding to Child Haven for a six-room classroom building now named the Agassi Center for Education. His foundation also provided $720,000 to assist in the building of the Andre Agassi Cottage for Medically Fragile Children. This 20-bed facility opened in December 2001, and accommodates developmentally delayed or handicapped children and children quarantined for infectious diseases.In 2007, along with several other athletes, Agassi founded the charity Athletes for Hope, which helps professional athletes get involved in charitable causes and aims to inspire all people to volunteer and support their communities. He created the Canyon-Agassi Charter School Facilities Fund, now known as the Turner-Agassi Charter School Facilities Fund. The Fund is an investment initiative for social change, focusing on the "nationwide effort to move charters from stopgap buildings into permanent campuses."In September 2013, the Andre Agassi Foundation for Education formed a partnership with V20 Foods to launch Box Budd!es, a line of kids' healthy snacks. All proceeds go to the Foundation.In February 2014, Agassi remodeled the vacant University of Phoenix building in Las Vegas as a new school, called the Doral Academy West through the Canyon-Agassi Charter School Facilities Fund. Doral Academy opened in August 2014. The Fund purchased a 4.6-acre plot in Henderson, Nevada to house the Somerset Academy of Las Vegas, which will relocate from its campus inside a church.Career statisticsSingles performance timelineGrand Slam finals (8 titles, 7 runners-up)By winning the 1999 French Open, Agassi completed a men's singles Career Grand Slam. He is the 5th of 8 male players in history (after Budge, Perry, Laver and Emerson, and before Federer, Nadal and Djokovic) to achieve this.Open Era records These records were attained in the Open Era of tennis and in ATP World Tour Masters 1000 series since 1990. Records in bold indicate peer-less achievements.LegacyConsidered by numerous sources to be one of the greatest tennis players of all time, Agassi has also been called one of the greatest service returners ever to play the game, and was described by the BBC upon his retirement as "perhaps the biggest worldwide star in the sport's history". As a result, he is credited for helping to revive the popularity of tennis during the 1990s.Professional awards ITF World Champion: 1999. ATP Player of the Year: 1999. ATP Most Improved Player: 1988, 1998Recognition In 1992, Agassi was named the BBC Overseas Sports Personality of the Year. In 2010, Sports Illustrated named Agassi the 7th greatest male player of all time. On July 9, 2011, Agassi was inducted into the International Tennis Hall of Fame at a ceremony in Newport, Rhode Island.Video Wimbledon 2000 Semi-final – Agassi vs. Rafter (2003) Starring: Andre Agassi, Patrick Rafter; Standing Room Only, DVD Release Date: August 16, 2005, Run Time: 213 minutes, . Charlie Rose with Andre Agassi (May 7, 2001) Charlie Rose, Inc., DVD Release Date: August 15, 2006, Run Time: 57 minutes. Wimbledon: The Record Breakers (2005) Starring: Andre Agassi, Boris Becker; Standing Room Only, DVD Release Date: August 16, 2005, Run Time: 52 minutes, .Video games Andre Agassi Tennis for the SNES, Sega Genesis, Sega Game Gear, Master System, and Mobile phone Agassi Tennis Generation for PS2 and GBA Agassi Tennis Generation 2002 for Windows Smash Court Pro Tournament for PS2 Top Spin 4 (On cover of game) for Xbox 360, PlayStation 3 and WiiSee also Agassi–Sampras rivalry All-time tennis records – men's singles List of Grand Slam Men's Singles champions Tennis male players statistics Tennis records of the Open Era – men's singlesExplanatory notesReferencesFurther readingExternal links Andre Agassi Ventures Farewell to Tennis Speech at the U.S. Open Agassi's Tennis Hall of Fame Induction for Steffi Graf 1970 birthsLiving people20th-century American businesspeople21st-century American businesspeopleAmerican autobiographersAmerican investorsAmerican male tennis playersAmerican people of Iranian descentAmerican people of Iranian-Assyrian descentAmerican sportspeople of Armenian descentAmerican real estate businesspeopleAmerican sportspeople in doping casesArmenian-American tennis playersAssyrian sportspeopleAustralian Open (tennis) championsDoping cases in tennisEthnic Armenian sportspeopleFrench Open championsGrand Slam (tennis) champions in men's singlesInternational Tennis Hall of Fame inducteesIranian Assyrian peopleIranian people of Armenian descentMedalists at the 1996 Summer OlympicsNevada DemocratsNovak Djokovic coachesOlympic gold medalists for the United States in tennisPhilanthropists from NevadaSportspeople from Las VegasSportspeople of Iranian descentSteffi GrafTennis people from NevadaTennis players at the 1996 Summer OlympicsUS Open (tennis) championsWimbledon championsWorld No. 1 tennis playersWriters from Las Vegas diff --git a/evaluation/ceval/mapping.json b/evaluation/ceval/mapping.json index b939d2db..42584aa9 100644 --- a/evaluation/ceval/mapping.json +++ b/evaluation/ceval/mapping.json @@ -207,4 +207,4 @@ "name": "兽医学", "category": "STEM" } -} \ No newline at end of file +} diff --git a/evaluation/cmmlu/mapping.json b/evaluation/cmmlu/mapping.json index 57329d01..312d038f 100644 --- a/evaluation/cmmlu/mapping.json +++ b/evaluation/cmmlu/mapping.json @@ -267,4 +267,4 @@ "name": "世界宗教", "category": "Humanities" } -} \ No newline at end of file +} diff --git a/evaluation/mmlu/mapping.json b/evaluation/mmlu/mapping.json index 113ff416..27bd7c2a 100644 --- a/evaluation/mmlu/mapping.json +++ b/evaluation/mmlu/mapping.json @@ -227,4 +227,4 @@ "name": "world religions", "category": "Humanities" } -} \ No newline at end of file +} diff --git a/evaluation/mmlu/mmlu.py b/evaluation/mmlu/mmlu.py index 1065fb31..e83fdab5 100644 --- a/evaluation/mmlu/mmlu.py +++ b/evaluation/mmlu/mmlu.py @@ -158,5 +158,4 @@ class MMLU(datasets.GeneratorBasedBuilder): df = pd.read_csv(filepath, header=None) df.columns = ["question", "A", "B", "C", "D", "answer"] - for i, instance in enumerate(df.to_dict(orient="records")): - yield i, instance + yield from enumerate(df.to_dict(orient="records")) diff --git a/examples/deepspeed/ds_z0_config.json b/examples/deepspeed/ds_z0_config.json index ed326676..46c5ea47 100644 --- a/examples/deepspeed/ds_z0_config.json +++ b/examples/deepspeed/ds_z0_config.json @@ -25,4 +25,4 @@ "contiguous_gradients": true, "round_robin_gradients": true } -} \ No newline at end of file +} diff --git a/examples/deepspeed/ds_z2_config.json b/examples/deepspeed/ds_z2_config.json index 0a1bd1d8..c2ffe80d 100644 --- a/examples/deepspeed/ds_z2_config.json +++ b/examples/deepspeed/ds_z2_config.json @@ -25,4 +25,4 @@ "contiguous_gradients": true, "round_robin_gradients": true } -} \ No newline at end of file +} diff --git a/examples/deepspeed/ds_z2_offload_config.json b/examples/deepspeed/ds_z2_offload_config.json index 7a398364..93f1519a 100644 --- a/examples/deepspeed/ds_z2_offload_config.json +++ b/examples/deepspeed/ds_z2_offload_config.json @@ -29,4 +29,4 @@ "contiguous_gradients": true, "round_robin_gradients": true } -} \ No newline at end of file +} diff --git a/examples/deepspeed/ds_z3_config.json b/examples/deepspeed/ds_z3_config.json index ccf9560e..6acbe520 100644 --- a/examples/deepspeed/ds_z3_config.json +++ b/examples/deepspeed/ds_z3_config.json @@ -27,4 +27,4 @@ "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true } -} \ No newline at end of file +} diff --git a/examples/deepspeed/ds_z3_offload_config.json b/examples/deepspeed/ds_z3_offload_config.json index 026aabbc..b92f96a9 100644 --- a/examples/deepspeed/ds_z3_offload_config.json +++ b/examples/deepspeed/ds_z3_offload_config.json @@ -35,4 +35,4 @@ "stage3_max_reuse_distance": 1e9, "stage3_gather_16bit_weights_on_model_save": true } -} \ No newline at end of file +} diff --git a/scripts/cal_flops.py b/scripts/cal_flops.py index 07afe723..2bcf697b 100644 --- a/scripts/cal_flops.py +++ b/scripts/cal_flops.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 Microsoft Corporation and the LlamaFactory team. # # This code is inspired by the Microsoft's DeepSpeed library. diff --git a/scripts/cal_lr.py b/scripts/cal_lr.py index 4262a4fe..5fe7d496 100644 --- a/scripts/cal_lr.py +++ b/scripts/cal_lr.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 imoneoi and the LlamaFactory team. # # This code is inspired by the imoneoi's OpenChat library. @@ -74,7 +73,7 @@ def calculate_lr( elif stage == "sft": data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, label_pad_token_id=IGNORE_INDEX) else: - raise NotImplementedError("Stage does not supported: {}.".format(stage)) + raise NotImplementedError(f"Stage does not supported: {stage}.") dataloader = DataLoader(trainset, batch_size, shuffle=False, collate_fn=data_collator, pin_memory=True) valid_tokens, total_tokens = 0, 0 diff --git a/scripts/cal_mfu.py b/scripts/cal_mfu.py index 36562e8a..edc6e234 100644 --- a/scripts/cal_mfu.py +++ b/scripts/cal_mfu.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -100,7 +99,7 @@ def compute_device_flops(world_size: int) -> float: elif "4090" in device_name: return 98 * 1e12 * world_size else: - raise NotImplementedError("Device not supported: {}.".format(device_name)) + raise NotImplementedError(f"Device not supported: {device_name}.") def calculate_mfu( @@ -140,10 +139,10 @@ def calculate_mfu( "bf16": True, } if deepspeed_stage in [2, 3]: - args["deepspeed"] = "examples/deepspeed/ds_z{}_config.json".format(deepspeed_stage) + args["deepspeed"] = f"examples/deepspeed/ds_z{deepspeed_stage}_config.json" run_exp(args) - with open(os.path.join("saves", "test_mfu", "all_results.json"), "r", encoding="utf-8") as f: + with open(os.path.join("saves", "test_mfu", "all_results.json"), encoding="utf-8") as f: result = json.load(f) if dist.is_initialized(): @@ -157,7 +156,7 @@ def calculate_mfu( * compute_model_flops(model_name_or_path, total_batch_size, seq_length) / compute_device_flops(world_size) ) - print("MFU: {:.2f}%".format(mfu_value * 100)) + print(f"MFU: {mfu_value * 100:.2f}%") if __name__ == "__main__": diff --git a/scripts/cal_ppl.py b/scripts/cal_ppl.py index 5e55ee5e..8d995e71 100644 --- a/scripts/cal_ppl.py +++ b/scripts/cal_ppl.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -100,7 +99,7 @@ def calculate_ppl( tokenizer=tokenizer, label_pad_token_id=IGNORE_INDEX, train_on_prompt=train_on_prompt ) else: - raise NotImplementedError("Stage does not supported: {}.".format(stage)) + raise NotImplementedError(f"Stage does not supported: {stage}.") dataloader = DataLoader(trainset, batch_size, shuffle=False, collate_fn=data_collator, pin_memory=True) criterion = torch.nn.CrossEntropyLoss(reduction="none") @@ -125,8 +124,8 @@ def calculate_ppl( with open(save_name, "w", encoding="utf-8") as f: json.dump(perplexities, f, indent=2) - print("Average perplexity is {:.2f}".format(total_ppl / len(perplexities))) - print("Perplexities have been saved at {}.".format(save_name)) + print(f"Average perplexity is {total_ppl / len(perplexities):.2f}") + print(f"Perplexities have been saved at {save_name}.") if __name__ == "__main__": diff --git a/scripts/length_cdf.py b/scripts/length_cdf.py index fbc69173..fb0df695 100644 --- a/scripts/length_cdf.py +++ b/scripts/length_cdf.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -61,7 +60,7 @@ def length_cdf( for length, count in length_tuples: count_accu += count prob_accu += count / total_num * 100 - print("{:d} ({:.2f}%) samples have length < {}.".format(count_accu, prob_accu, length + interval)) + print(f"{count_accu:d} ({prob_accu:.2f}%) samples have length < {length + interval}.") if __name__ == "__main__": diff --git a/scripts/llama_pro.py b/scripts/llama_pro.py index bd05feb2..b086583d 100644 --- a/scripts/llama_pro.py +++ b/scripts/llama_pro.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 Tencent Inc. and the LlamaFactory team. # # This code is inspired by the Tencent's LLaMA-Pro library. @@ -40,7 +39,7 @@ if TYPE_CHECKING: def change_name(name: str, old_index: int, new_index: int) -> str: - return name.replace(".{:d}.".format(old_index), ".{:d}.".format(new_index)) + return name.replace(f".{old_index:d}.", f".{new_index:d}.") def block_expansion( @@ -76,27 +75,27 @@ def block_expansion( state_dict = model.state_dict() if num_layers % num_expand != 0: - raise ValueError("`num_layers` {} should be divisible by `num_expand` {}.".format(num_layers, num_expand)) + raise ValueError(f"`num_layers` {num_layers} should be divisible by `num_expand` {num_expand}.") split = num_layers // num_expand layer_cnt = 0 output_state_dict = OrderedDict() for i in range(num_layers): for key, value in state_dict.items(): - if ".{:d}.".format(i) in key: + if f".{i:d}." in key: output_state_dict[change_name(key, i, layer_cnt)] = value - print("Add layer {} copied from layer {}".format(layer_cnt, i)) + print(f"Add layer {layer_cnt} copied from layer {i}") layer_cnt += 1 if (i + 1) % split == 0: for key, value in state_dict.items(): - if ".{:d}.".format(i) in key: + if f".{i:d}." in key: if "down_proj" in key or "o_proj" in key: output_state_dict[change_name(key, i, layer_cnt)] = torch.zeros_like(value) else: output_state_dict[change_name(key, i, layer_cnt)] = torch.clone(value) - print("Add layer {} expanded from layer {}".format(layer_cnt, i)) + print(f"Add layer {layer_cnt} expanded from layer {i}") layer_cnt += 1 for key, value in state_dict.items(): @@ -113,17 +112,17 @@ def block_expansion( torch.save(shard, os.path.join(output_dir, shard_file)) if index is None: - print("Model weights saved in {}".format(os.path.join(output_dir, weights_name))) + print(f"Model weights saved in {os.path.join(output_dir, weights_name)}") else: index_name = SAFE_WEIGHTS_INDEX_NAME if save_safetensors else WEIGHTS_INDEX_NAME with open(os.path.join(output_dir, index_name), "w", encoding="utf-8") as f: json.dump(index, f, indent=2, sort_keys=True) - print("Model weights saved in {}".format(output_dir)) + print(f"Model weights saved in {output_dir}") print("- Fine-tune this model with:") - print("model_name_or_path: {}".format(output_dir)) + print(f"model_name_or_path: {output_dir}") print("finetuning_type: freeze") - print("freeze_trainable_layers: {}".format(num_expand)) + print(f"freeze_trainable_layers: {num_expand}") print("use_llama_pro: true") diff --git a/scripts/llamafy_baichuan2.py b/scripts/llamafy_baichuan2.py index 95673859..077703f6 100644 --- a/scripts/llamafy_baichuan2.py +++ b/scripts/llamafy_baichuan2.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -63,16 +62,16 @@ def save_weight(input_dir: str, output_dir: str, shard_size: str, save_safetenso torch.save(shard, os.path.join(output_dir, shard_file)) if index is None: - print("Model weights saved in {}".format(os.path.join(output_dir, WEIGHTS_NAME))) + print(f"Model weights saved in {os.path.join(output_dir, WEIGHTS_NAME)}") else: index_name = SAFE_WEIGHTS_INDEX_NAME if save_safetensors else WEIGHTS_INDEX_NAME with open(os.path.join(output_dir, index_name), "w", encoding="utf-8") as f: json.dump(index, f, indent=2, sort_keys=True) - print("Model weights saved in {}".format(output_dir)) + print(f"Model weights saved in {output_dir}") def save_config(input_dir: str, output_dir: str): - with open(os.path.join(input_dir, CONFIG_NAME), "r", encoding="utf-8") as f: + with open(os.path.join(input_dir, CONFIG_NAME), encoding="utf-8") as f: llama2_config_dict: Dict[str, Any] = json.load(f) llama2_config_dict["architectures"] = ["LlamaForCausalLM"] @@ -82,7 +81,7 @@ def save_config(input_dir: str, output_dir: str): with open(os.path.join(output_dir, CONFIG_NAME), "w", encoding="utf-8") as f: json.dump(llama2_config_dict, f, indent=2) - print("Model config saved in {}".format(os.path.join(output_dir, CONFIG_NAME))) + print(f"Model config saved in {os.path.join(output_dir, CONFIG_NAME)}") def llamafy_baichuan2( diff --git a/scripts/llamafy_qwen.py b/scripts/llamafy_qwen.py index 785a2129..beabe4b1 100644 --- a/scripts/llamafy_qwen.py +++ b/scripts/llamafy_qwen.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -86,7 +85,7 @@ def save_weight(input_dir: str, output_dir: str, shard_size: str, save_safetenso elif "lm_head" in key: llama2_state_dict[key] = value else: - raise KeyError("Unable to process key {}".format(key)) + raise KeyError(f"Unable to process key {key}") weights_name = SAFE_WEIGHTS_NAME if save_safetensors else WEIGHTS_NAME shards, index = shard_checkpoint(llama2_state_dict, max_shard_size=shard_size, weights_name=weights_name) @@ -98,18 +97,18 @@ def save_weight(input_dir: str, output_dir: str, shard_size: str, save_safetenso torch.save(shard, os.path.join(output_dir, shard_file)) if index is None: - print("Model weights saved in {}".format(os.path.join(output_dir, weights_name))) + print(f"Model weights saved in {os.path.join(output_dir, weights_name)}") else: index_name = SAFE_WEIGHTS_INDEX_NAME if save_safetensors else WEIGHTS_INDEX_NAME with open(os.path.join(output_dir, index_name), "w", encoding="utf-8") as f: json.dump(index, f, indent=2, sort_keys=True) - print("Model weights saved in {}".format(output_dir)) + print(f"Model weights saved in {output_dir}") return str(torch_dtype).replace("torch.", "") def save_config(input_dir: str, output_dir: str, torch_dtype: str): - with open(os.path.join(input_dir, CONFIG_NAME), "r", encoding="utf-8") as f: + with open(os.path.join(input_dir, CONFIG_NAME), encoding="utf-8") as f: qwen_config_dict: Dict[str, Any] = json.load(f) llama2_config_dict: Dict[str, Any] = OrderedDict() @@ -135,7 +134,7 @@ def save_config(input_dir: str, output_dir: str, torch_dtype: str): with open(os.path.join(output_dir, CONFIG_NAME), "w", encoding="utf-8") as f: json.dump(llama2_config_dict, f, indent=2) - print("Model config saved in {}".format(os.path.join(output_dir, CONFIG_NAME))) + print(f"Model config saved in {os.path.join(output_dir, CONFIG_NAME)}") def llamafy_qwen( diff --git a/scripts/loftq_init.py b/scripts/loftq_init.py index ad976673..5e640843 100644 --- a/scripts/loftq_init.py +++ b/scripts/loftq_init.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 HuggingFace Inc. and the LlamaFactory team. # # This code is based on the HuggingFace's PEFT library. @@ -70,19 +69,19 @@ def quantize_loftq( setattr(peft_model.peft_config["default"], "base_model_name_or_path", os.path.abspath(output_dir)) setattr(peft_model.peft_config["default"], "init_lora_weights", True) # don't apply loftq again peft_model.save_pretrained(loftq_dir, safe_serialization=save_safetensors) - print("Adapter weights saved in {}".format(loftq_dir)) + print(f"Adapter weights saved in {loftq_dir}") # Save base model base_model: "PreTrainedModel" = peft_model.unload() base_model.save_pretrained(output_dir, safe_serialization=save_safetensors) tokenizer.save_pretrained(output_dir) - print("Model weights saved in {}".format(output_dir)) + print(f"Model weights saved in {output_dir}") print("- Fine-tune this model with:") - print("model_name_or_path: {}".format(output_dir)) - print("adapter_name_or_path: {}".format(loftq_dir)) + print(f"model_name_or_path: {output_dir}") + print(f"adapter_name_or_path: {loftq_dir}") print("finetuning_type: lora") - print("quantization_bit: {}".format(loftq_bits)) + print(f"quantization_bit: {loftq_bits}") if __name__ == "__main__": diff --git a/scripts/pissa_init.py b/scripts/pissa_init.py index f285e326..f7092f0e 100644 --- a/scripts/pissa_init.py +++ b/scripts/pissa_init.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 HuggingFace Inc. and the LlamaFactory team. # # This code is based on the HuggingFace's PEFT library. @@ -54,7 +53,7 @@ def quantize_pissa( lora_alpha=lora_alpha if lora_alpha is not None else lora_rank * 2, lora_dropout=lora_dropout, target_modules=lora_target, - init_lora_weights="pissa" if pissa_iter == -1 else "pissa_niter_{}".format(pissa_iter), + init_lora_weights="pissa" if pissa_iter == -1 else f"pissa_niter_{pissa_iter}", ) # Init PiSSA model @@ -65,17 +64,17 @@ def quantize_pissa( setattr(peft_model.peft_config["default"], "base_model_name_or_path", os.path.abspath(output_dir)) setattr(peft_model.peft_config["default"], "init_lora_weights", True) # don't apply pissa again peft_model.save_pretrained(pissa_dir, safe_serialization=save_safetensors) - print("Adapter weights saved in {}".format(pissa_dir)) + print(f"Adapter weights saved in {pissa_dir}") # Save base model base_model: "PreTrainedModel" = peft_model.unload() base_model.save_pretrained(output_dir, safe_serialization=save_safetensors) tokenizer.save_pretrained(output_dir) - print("Model weights saved in {}".format(output_dir)) + print(f"Model weights saved in {output_dir}") print("- Fine-tune this model with:") - print("model_name_or_path: {}".format(output_dir)) - print("adapter_name_or_path: {}".format(pissa_dir)) + print(f"model_name_or_path: {output_dir}") + print(f"adapter_name_or_path: {pissa_dir}") print("finetuning_type: lora") print("pissa_init: false") print("pissa_convert: true") diff --git a/scripts/test_toolcall.py b/scripts/test_toolcall.py index 6f6fd06c..04410db0 100644 --- a/scripts/test_toolcall.py +++ b/scripts/test_toolcall.py @@ -1,4 +1,3 @@ -# coding=utf-8 # Copyright 2024 the LlamaFactory team. # # Licensed under the Apache License, Version 2.0 (the "License"); diff --git a/setup.py b/setup.py index 90f6362d..2fd7832d 100644 --- a/setup.py +++ b/setup.py @@ -20,7 +20,7 @@ from setuptools import find_packages, setup def get_version() -> str: - with open(os.path.join("src", "llamafactory", "extras", "env.py"), "r", encoding="utf-8") as f: + with open(os.path.join("src", "llamafactory", "extras", "env.py"), encoding="utf-8") as f: file_content = f.read() pattern = r"{}\W*=\W*\"([^\"]+)\"".format("VERSION") (version,) = re.findall(pattern, file_content) @@ -28,7 +28,7 @@ def get_version() -> str: def get_requires() -> List[str]: - with open("requirements.txt", "r", encoding="utf-8") as f: + with open("requirements.txt", encoding="utf-8") as f: file_content = f.read() lines = [line.strip() for line in file_content.strip().split("\n") if not line.startswith("#")] return lines @@ -61,7 +61,7 @@ extra_require = { "qwen": ["transformers_stream_generator"], "modelscope": ["modelscope"], "openmind": ["openmind"], - "dev": ["ruff", "pytest"], + "dev": ["pre-commit", "ruff", "pytest"], } @@ -72,7 +72,7 @@ def main(): author="hiyouga", author_email="hiyouga" "@" "buaa.edu.cn", description="Easy-to-use LLM fine-tuning framework", - long_description=open("README.md", "r", encoding="utf-8").read(), + long_description=open("README.md", encoding="utf-8").read(), long_description_content_type="text/markdown", keywords=["LLaMA", "BLOOM", "Falcon", "LLM", "ChatGPT", "transformer", "pytorch", "deep learning"], license="Apache 2.0 License", diff --git a/src/api.py b/src/api.py index 0f925497..25a7c2e7 100644 --- a/src/api.py +++ b/src/api.py @@ -25,7 +25,7 @@ def main(): app = create_app(chat_model) api_host = os.environ.get("API_HOST", "0.0.0.0") api_port = int(os.environ.get("API_PORT", "8000")) - print("Visit http://localhost:{}/docs for API document.".format(api_port)) + print(f"Visit http://localhost:{api_port}/docs for API document.") uvicorn.run(app, host=api_host, port=api_port) diff --git a/src/llamafactory/api/app.py b/src/llamafactory/api/app.py index c9627e5a..a98438f3 100644 --- a/src/llamafactory/api/app.py +++ b/src/llamafactory/api/app.py @@ -130,5 +130,5 @@ def run_api() -> None: app = create_app(chat_model) api_host = os.environ.get("API_HOST", "0.0.0.0") api_port = int(os.environ.get("API_PORT", "8000")) - print("Visit http://localhost:{}/docs for API document.".format(api_port)) + print(f"Visit http://localhost:{api_port}/docs for API document.") uvicorn.run(app, host=api_host, port=api_port) diff --git a/src/llamafactory/api/chat.py b/src/llamafactory/api/chat.py index d0a41515..f20e588e 100644 --- a/src/llamafactory/api/chat.py +++ b/src/llamafactory/api/chat.py @@ -70,7 +70,7 @@ ROLE_MAPPING = { def _process_request( request: "ChatCompletionRequest", ) -> Tuple[List[Dict[str, str]], Optional[str], Optional[str], Optional["ImageInput"]]: - logger.info("==== request ====\n{}".format(json.dumps(dictify(request), indent=2, ensure_ascii=False))) + logger.info(f"==== request ====\n{json.dumps(dictify(request), indent=2, ensure_ascii=False)}") if len(request.messages) == 0: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid length") @@ -142,7 +142,7 @@ def _create_stream_chat_completion_chunk( async def create_chat_completion_response( request: "ChatCompletionRequest", chat_model: "ChatModel" ) -> "ChatCompletionResponse": - completion_id = "chatcmpl-{}".format(uuid.uuid4().hex) + completion_id = f"chatcmpl-{uuid.uuid4().hex}" input_messages, system, tools, image = _process_request(request) responses = await chat_model.achat( input_messages, @@ -169,7 +169,7 @@ async def create_chat_completion_response( tool_calls = [] for tool in result: function = Function(name=tool[0], arguments=tool[1]) - tool_calls.append(FunctionCall(id="call_{}".format(uuid.uuid4().hex), function=function)) + tool_calls.append(FunctionCall(id=f"call_{uuid.uuid4().hex}", function=function)) response_message = ChatCompletionMessage(role=Role.ASSISTANT, tool_calls=tool_calls) finish_reason = Finish.TOOL @@ -193,7 +193,7 @@ async def create_chat_completion_response( async def create_stream_chat_completion_response( request: "ChatCompletionRequest", chat_model: "ChatModel" ) -> AsyncGenerator[str, None]: - completion_id = "chatcmpl-{}".format(uuid.uuid4().hex) + completion_id = f"chatcmpl-{uuid.uuid4().hex}" input_messages, system, tools, image = _process_request(request) if tools: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Cannot stream function calls.") @@ -229,7 +229,7 @@ async def create_stream_chat_completion_response( async def create_score_evaluation_response( request: "ScoreEvaluationRequest", chat_model: "ChatModel" ) -> "ScoreEvaluationResponse": - score_id = "scoreval-{}".format(uuid.uuid4().hex) + score_id = f"scoreval-{uuid.uuid4().hex}" if len(request.messages) == 0: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid request") diff --git a/src/llamafactory/chat/chat_model.py b/src/llamafactory/chat/chat_model.py index 1e3aee57..4f0e1b83 100644 --- a/src/llamafactory/chat/chat_model.py +++ b/src/llamafactory/chat/chat_model.py @@ -53,7 +53,7 @@ class ChatModel: elif model_args.infer_backend == "vllm": self.engine: "BaseEngine" = VllmEngine(model_args, data_args, finetuning_args, generating_args) else: - raise NotImplementedError("Unknown backend: {}".format(model_args.infer_backend)) + raise NotImplementedError(f"Unknown backend: {model_args.infer_backend}") self._loop = asyncio.new_event_loop() self._thread = Thread(target=_start_background_loop, args=(self._loop,), daemon=True) diff --git a/src/llamafactory/chat/vllm_engine.py b/src/llamafactory/chat/vllm_engine.py index 55209fcc..2b5a32b4 100644 --- a/src/llamafactory/chat/vllm_engine.py +++ b/src/llamafactory/chat/vllm_engine.py @@ -105,7 +105,7 @@ class VllmEngine(BaseEngine): video: Optional["VideoInput"] = None, **input_kwargs, ) -> AsyncIterator["RequestOutput"]: - request_id = "chatcmpl-{}".format(uuid.uuid4().hex) + request_id = f"chatcmpl-{uuid.uuid4().hex}" if image is not None: if IMAGE_PLACEHOLDER not in messages[0]["content"]: messages[0]["content"] = IMAGE_PLACEHOLDER + messages[0]["content"] @@ -159,7 +159,7 @@ class VllmEngine(BaseEngine): if image is not None: # add image features if not isinstance(image, (str, ImageObject)): - raise ValueError("Expected image input is a path or PIL.Image, but got {}.".format(type(image))) + raise ValueError(f"Expected image input is a path or PIL.Image, but got {type(image)}.") if isinstance(image, str): image = Image.open(image).convert("RGB") diff --git a/src/llamafactory/cli.py b/src/llamafactory/cli.py index 8012d855..a39c3147 100644 --- a/src/llamafactory/cli.py +++ b/src/llamafactory/cli.py @@ -47,7 +47,7 @@ USAGE = ( WELCOME = ( "-" * 58 + "\n" - + "| Welcome to LLaMA Factory, version {}".format(VERSION) + + f"| Welcome to LLaMA Factory, version {VERSION}" + " " * (21 - len(VERSION)) + "|\n|" + " " * 56 @@ -90,7 +90,7 @@ def main(): if force_torchrun or get_device_count() > 1: master_addr = os.environ.get("MASTER_ADDR", "127.0.0.1") master_port = os.environ.get("MASTER_PORT", str(random.randint(20001, 29999))) - logger.info("Initializing distributed tasks at: {}:{}".format(master_addr, master_port)) + logger.info(f"Initializing distributed tasks at: {master_addr}:{master_port}") process = subprocess.run( ( "torchrun --nnodes {nnodes} --node_rank {node_rank} --nproc_per_node {nproc_per_node} " @@ -118,4 +118,4 @@ def main(): elif command == Command.HELP: print(USAGE) else: - raise NotImplementedError("Unknown command: {}.".format(command)) + raise NotImplementedError(f"Unknown command: {command}.") diff --git a/src/llamafactory/data/aligner.py b/src/llamafactory/data/aligner.py index f7f6d0ad..0e497ebc 100644 --- a/src/llamafactory/data/aligner.py +++ b/src/llamafactory/data/aligner.py @@ -161,7 +161,7 @@ def convert_sharegpt( broken_data = False for turn_idx, message in enumerate(messages): if message[dataset_attr.role_tag] not in accept_tags[turn_idx % 2]: - logger.warning("Invalid role tag in {}.".format(messages)) + logger.warning(f"Invalid role tag in {messages}.") broken_data = True aligned_messages.append( @@ -171,7 +171,7 @@ def convert_sharegpt( if (not dataset_attr.ranking and len(aligned_messages) % 2 != 0) or ( dataset_attr.ranking and len(aligned_messages) % 2 == 0 ): - logger.warning("Invalid message count in {}.".format(messages)) + logger.warning(f"Invalid message count in {messages}.") broken_data = True if dataset_attr.kto_tag and isinstance(example[dataset_attr.kto_tag], bool): # kto example @@ -192,7 +192,7 @@ def convert_sharegpt( chosen[dataset_attr.role_tag] not in accept_tags[-1] or rejected[dataset_attr.role_tag] not in accept_tags[-1] ): - logger.warning("Invalid role tag in {}.".format([chosen, rejected])) + logger.warning(f"Invalid role tag in {[chosen, rejected]}.") broken_data = True prompt = aligned_messages diff --git a/src/llamafactory/data/collator.py b/src/llamafactory/data/collator.py index 92d86cc7..bc8ab347 100644 --- a/src/llamafactory/data/collator.py +++ b/src/llamafactory/data/collator.py @@ -137,9 +137,9 @@ class PairwiseDataCollatorWithPadding(MultiModalDataCollatorForSeq2Seq): for key in ("chosen", "rejected"): for feature in features: target_feature = { - "input_ids": feature["{}_input_ids".format(key)], - "attention_mask": feature["{}_attention_mask".format(key)], - "labels": feature["{}_labels".format(key)], + "input_ids": feature[f"{key}_input_ids"], + "attention_mask": feature[f"{key}_attention_mask"], + "labels": feature[f"{key}_labels"], "images": feature["images"], "videos": feature["videos"], } diff --git a/src/llamafactory/data/data_utils.py b/src/llamafactory/data/data_utils.py index a58987eb..79a07df5 100644 --- a/src/llamafactory/data/data_utils.py +++ b/src/llamafactory/data/data_utils.py @@ -70,7 +70,7 @@ def merge_dataset( stopping_strategy="first_exhausted" if data_args.mix_strategy.endswith("under") else "all_exhausted", ) else: - raise ValueError("Unknown mixing strategy: {}.".format(data_args.mix_strategy)) + raise ValueError(f"Unknown mixing strategy: {data_args.mix_strategy}.") def split_dataset( diff --git a/src/llamafactory/data/formatter.py b/src/llamafactory/data/formatter.py index 99a4a8b4..ab86189c 100644 --- a/src/llamafactory/data/formatter.py +++ b/src/llamafactory/data/formatter.py @@ -83,14 +83,14 @@ class StringFormatter(Formatter): if isinstance(slot, str): for name, value in kwargs.items(): if not isinstance(value, str): - raise RuntimeError("Expected a string, got {}".format(value)) + raise RuntimeError(f"Expected a string, got {value}") slot = slot.replace("{{" + name + "}}", value, 1) elements.append(slot) elif isinstance(slot, (dict, set)): elements.append(slot) else: - raise RuntimeError("Input must be string, set[str] or dict[str, str], got {}".format(type(slot))) + raise RuntimeError(f"Input must be string, set[str] or dict[str, str], got {type(slot)}") return elements @@ -113,7 +113,7 @@ class FunctionFormatter(Formatter): functions.append((tool_call["name"], json.dumps(tool_call["arguments"], ensure_ascii=False))) except json.JSONDecodeError: - raise RuntimeError("Invalid JSON format in function message: {}".format(str([content]))) # flat string + raise RuntimeError(f"Invalid JSON format in function message: {str([content])}") # flat string elements = [] for name, arguments in functions: @@ -124,7 +124,7 @@ class FunctionFormatter(Formatter): elif isinstance(slot, (dict, set)): elements.append(slot) else: - raise RuntimeError("Input must be string, set[str] or dict[str, str], got {}".format(type(slot))) + raise RuntimeError(f"Input must be string, set[str] or dict[str, str], got {type(slot)}") return elements @@ -141,7 +141,7 @@ class ToolFormatter(Formatter): tools = json.loads(content) return [self.tool_utils.tool_formatter(tools) if len(tools) != 0 else ""] except json.JSONDecodeError: - raise RuntimeError("Invalid JSON format in tool description: {}".format(str([content]))) # flat string + raise RuntimeError(f"Invalid JSON format in tool description: {str([content])}") # flat string @override def extract(self, content: str) -> Union[str, List["FunctionCall"]]: diff --git a/src/llamafactory/data/loader.py b/src/llamafactory/data/loader.py index 95398e26..2ac13c94 100644 --- a/src/llamafactory/data/loader.py +++ b/src/llamafactory/data/loader.py @@ -51,7 +51,7 @@ def _load_single_dataset( r""" Loads a single dataset and aligns it to the standard format. """ - logger.info("Loading dataset {}...".format(dataset_attr)) + logger.info(f"Loading dataset {dataset_attr}...") data_path, data_name, data_dir, data_files = None, None, None, None if dataset_attr.load_from in ["hf_hub", "ms_hub", "om_hub"]: data_path = dataset_attr.dataset_name @@ -77,12 +77,12 @@ def _load_single_dataset( data_files.append(local_path) data_path = FILEEXT2TYPE.get(local_path.split(".")[-1], None) else: - raise ValueError("File {} not found.".format(local_path)) + raise ValueError(f"File {local_path} not found.") if data_path is None: raise ValueError("Allowed file types: {}.".format(",".join(FILEEXT2TYPE.keys()))) else: - raise NotImplementedError("Unknown load type: {}.".format(dataset_attr.load_from)) + raise NotImplementedError(f"Unknown load type: {dataset_attr.load_from}.") if dataset_attr.load_from == "ms_hub": require_version("modelscope>=1.11.0", "To fix: pip install modelscope>=1.11.0") @@ -145,7 +145,7 @@ def _load_single_dataset( assert len(indexes) == dataset_attr.num_samples, "Sample num mismatched." dataset = dataset.select(indexes) - logger.info("Sampled {} examples from dataset {}.".format(dataset_attr.num_samples, dataset_attr)) + logger.info(f"Sampled {dataset_attr.num_samples} examples from dataset {dataset_attr}.") if data_args.max_samples is not None: # truncate dataset max_samples = min(data_args.max_samples, len(dataset)) @@ -243,7 +243,7 @@ def get_dataset( if has_tokenized_data(data_args.tokenized_path): logger.warning("Loading dataset from disk will ignore other data arguments.") dataset_dict: "DatasetDict" = load_from_disk(data_args.tokenized_path) - logger.info("Loaded tokenized dataset from {}.".format(data_args.tokenized_path)) + logger.info(f"Loaded tokenized dataset from {data_args.tokenized_path}.") dataset_module: Dict[str, "Dataset"] = {} if "train" in dataset_dict: @@ -294,8 +294,8 @@ def get_dataset( if data_args.tokenized_path is not None: if training_args.should_save: dataset_dict.save_to_disk(data_args.tokenized_path) - logger.info("Tokenized dataset saved at {}.".format(data_args.tokenized_path)) - logger.info("Please restart the training with `tokenized_path: {}`.".format(data_args.tokenized_path)) + logger.info(f"Tokenized dataset saved at {data_args.tokenized_path}.") + logger.info(f"Please restart the training with `tokenized_path: {data_args.tokenized_path}`.") sys.exit(0) diff --git a/src/llamafactory/data/mm_plugin.py b/src/llamafactory/data/mm_plugin.py index 3684495b..a2a2b8cc 100644 --- a/src/llamafactory/data/mm_plugin.py +++ b/src/llamafactory/data/mm_plugin.py @@ -111,7 +111,7 @@ class BasePlugin: image = Image.open(image["path"]) if not isinstance(image, ImageObject): - raise ValueError("Expect input is a list of Images, but got {}.".format(type(image))) + raise ValueError(f"Expect input is a list of Images, but got {type(image)}.") results.append(self._preprocess_image(image, **kwargs)) @@ -253,7 +253,7 @@ class LlavaPlugin(BasePlugin): message["content"] = content.replace("{{image}}", self.image_token * image_seqlen) if len(images) != num_image_tokens: - raise ValueError("The number of images does not match the number of {} tokens".format(IMAGE_PLACEHOLDER)) + raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens") return messages @@ -302,7 +302,7 @@ class LlavaNextPlugin(BasePlugin): message["content"] = content.replace("{{image}}", self.image_token) if len(images) != num_image_tokens: - raise ValueError("The number of images does not match the number of {} tokens".format(IMAGE_PLACEHOLDER)) + raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens") return messages @override @@ -366,10 +366,10 @@ class LlavaNextVideoPlugin(BasePlugin): message["content"] = content.replace("{{video}}", self.video_token * video_seqlen) if len(images) != num_image_tokens: - raise ValueError("The number of images does not match the number of {} tokens".format(IMAGE_PLACEHOLDER)) + raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens") if len(videos) != num_video_tokens: - raise ValueError("The number of videos does not match the number of {} tokens".format(IMAGE_PLACEHOLDER)) + raise ValueError(f"The number of videos does not match the number of {IMAGE_PLACEHOLDER} tokens") return messages @@ -408,7 +408,7 @@ class PaliGemmaPlugin(BasePlugin): message["content"] = content.replace("{{image}}", "") if len(images) != num_image_tokens: - raise ValueError("The number of images does not match the number of {} tokens".format(IMAGE_PLACEHOLDER)) + raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens") return messages @@ -493,7 +493,7 @@ class Qwen2vlPlugin(BasePlugin): content = message["content"] while IMAGE_PLACEHOLDER in content: if num_image_tokens >= len(image_grid_thw): - raise ValueError("`len(images)` is less than the number of {} tokens.".format(IMAGE_PLACEHOLDER)) + raise ValueError(f"`len(images)` is less than the number of {IMAGE_PLACEHOLDER} tokens.") content = content.replace( IMAGE_PLACEHOLDER, @@ -506,7 +506,7 @@ class Qwen2vlPlugin(BasePlugin): while VIDEO_PLACEHOLDER in content: if num_video_tokens >= len(video_grid_thw): - raise ValueError("`len(videos)` is less than the number of {} tokens.".format(VIDEO_PLACEHOLDER)) + raise ValueError(f"`len(videos)` is less than the number of {VIDEO_PLACEHOLDER} tokens.") content = content.replace( VIDEO_PLACEHOLDER, @@ -520,10 +520,10 @@ class Qwen2vlPlugin(BasePlugin): message["content"] = content if len(images) != num_image_tokens: - raise ValueError("The number of images does not match the number of {} tokens".format(IMAGE_PLACEHOLDER)) + raise ValueError(f"The number of images does not match the number of {IMAGE_PLACEHOLDER} tokens") if len(videos) != num_video_tokens: - raise ValueError("The number of videos does not match the number of {} tokens".format(VIDEO_PLACEHOLDER)) + raise ValueError(f"The number of videos does not match the number of {VIDEO_PLACEHOLDER} tokens") return messages @@ -583,10 +583,10 @@ class VideoLlavaPlugin(BasePlugin): message["content"] = content.replace("{{video}}", self.video_token * video_seqlen) if len(images) != num_image_tokens: - raise ValueError("The number of images does not match the number of {} tokens".format(self.image_token)) + raise ValueError(f"The number of images does not match the number of {self.image_token} tokens") if len(videos) != num_video_tokens: - raise ValueError("The number of videos does not match the number of {} tokens".format(self.video_token)) + raise ValueError(f"The number of videos does not match the number of {self.video_token} tokens") return messages @@ -622,6 +622,6 @@ def get_mm_plugin( ) -> "BasePlugin": plugin_class = PLUGINS.get(name, None) if plugin_class is None: - raise ValueError("Multimodal plugin `{}` not found.".format(name)) + raise ValueError(f"Multimodal plugin `{name}` not found.") return plugin_class(image_token, video_token) diff --git a/src/llamafactory/data/parser.py b/src/llamafactory/data/parser.py index b9060425..709d0c90 100644 --- a/src/llamafactory/data/parser.py +++ b/src/llamafactory/data/parser.py @@ -87,11 +87,11 @@ def get_dataset_list(dataset_names: Optional[Sequence[str]], dataset_dir: str) - config_path = os.path.join(dataset_dir, DATA_CONFIG) try: - with open(config_path, "r") as f: + with open(config_path) as f: dataset_info = json.load(f) except Exception as err: if len(dataset_names) != 0: - raise ValueError("Cannot open {} due to {}.".format(config_path, str(err))) + raise ValueError(f"Cannot open {config_path} due to {str(err)}.") dataset_info = None @@ -109,7 +109,7 @@ def get_dataset_list(dataset_names: Optional[Sequence[str]], dataset_dir: str) - continue if name not in dataset_info: - raise ValueError("Undefined dataset {} in {}.".format(name, DATA_CONFIG)) + raise ValueError(f"Undefined dataset {name} in {DATA_CONFIG}.") has_hf_url = "hf_hub_url" in dataset_info[name] has_ms_url = "ms_hub_url" in dataset_info[name] diff --git a/src/llamafactory/data/processors/pairwise.py b/src/llamafactory/data/processors/pairwise.py index 05702fa3..9df00d1d 100644 --- a/src/llamafactory/data/processors/pairwise.py +++ b/src/llamafactory/data/processors/pairwise.py @@ -110,8 +110,8 @@ def print_pairwise_dataset_example(example: Dict[str, List[int]], tokenizer: "Pr print("chosen_input_ids:\n{}".format(example["chosen_input_ids"])) print("chosen_inputs:\n{}".format(tokenizer.decode(example["chosen_input_ids"], skip_special_tokens=False))) print("chosen_label_ids:\n{}".format(example["chosen_labels"])) - print("chosen_labels:\n{}".format(tokenizer.decode(valid_chosen_labels, skip_special_tokens=False))) + print(f"chosen_labels:\n{tokenizer.decode(valid_chosen_labels, skip_special_tokens=False)}") print("rejected_input_ids:\n{}".format(example["rejected_input_ids"])) print("rejected_inputs:\n{}".format(tokenizer.decode(example["rejected_input_ids"], skip_special_tokens=False))) print("rejected_label_ids:\n{}".format(example["rejected_labels"])) - print("rejected_labels:\n{}".format(tokenizer.decode(valid_rejected_labels, skip_special_tokens=False))) + print(f"rejected_labels:\n{tokenizer.decode(valid_rejected_labels, skip_special_tokens=False)}") diff --git a/src/llamafactory/data/processors/supervised.py b/src/llamafactory/data/processors/supervised.py index 66625640..2552429f 100644 --- a/src/llamafactory/data/processors/supervised.py +++ b/src/llamafactory/data/processors/supervised.py @@ -160,7 +160,7 @@ def preprocess_packed_supervised_dataset( ) length = len(input_ids) if length > data_args.cutoff_len: - logger.warning("Dropped lengthy example with length {} > {}.".format(length, data_args.cutoff_len)) + logger.warning(f"Dropped lengthy example with length {length} > {data_args.cutoff_len}.") else: lengths.append(length) length2indexes[length].append(valid_num) @@ -212,4 +212,4 @@ def print_supervised_dataset_example(example: Dict[str, List[int]], tokenizer: " print("input_ids:\n{}".format(example["input_ids"])) print("inputs:\n{}".format(tokenizer.decode(example["input_ids"], skip_special_tokens=False))) print("label_ids:\n{}".format(example["labels"])) - print("labels:\n{}".format(tokenizer.decode(valid_labels, skip_special_tokens=False))) + print(f"labels:\n{tokenizer.decode(valid_labels, skip_special_tokens=False)}") diff --git a/src/llamafactory/data/template.py b/src/llamafactory/data/template.py index bfa987d9..96738b33 100644 --- a/src/llamafactory/data/template.py +++ b/src/llamafactory/data/template.py @@ -147,7 +147,7 @@ class Template: elif "eos_token" in elem and tokenizer.eos_token_id is not None: token_ids += [tokenizer.eos_token_id] else: - raise ValueError("Input must be string, set[str] or dict[str, str], got {}".format(type(elem))) + raise ValueError(f"Input must be string, set[str] or dict[str, str], got {type(elem)}") return token_ids @@ -275,9 +275,9 @@ def _add_or_replace_eos_token(tokenizer: "PreTrainedTokenizer", eos_token: str) num_added_tokens = tokenizer.add_special_tokens({"eos_token": eos_token}) if is_added: - logger.info("Add eos token: {}".format(tokenizer.eos_token)) + logger.info(f"Add eos token: {tokenizer.eos_token}") else: - logger.info("Replace eos token: {}".format(tokenizer.eos_token)) + logger.info(f"Replace eos token: {tokenizer.eos_token}") if num_added_tokens > 0: logger.warning("New tokens have been added, make sure `resize_vocab` is True.") @@ -365,13 +365,13 @@ def get_template_and_fix_tokenizer(tokenizer: "PreTrainedTokenizer", data_args: else: template = TEMPLATES.get(data_args.template, None) if template is None: - raise ValueError("Template {} does not exist.".format(data_args.template)) + raise ValueError(f"Template {data_args.template} does not exist.") if data_args.train_on_prompt and template.efficient_eos: raise ValueError("Current template does not support `train_on_prompt`.") if data_args.tool_format is not None: - logger.info("Using tool format: {}.".format(data_args.tool_format)) + logger.info(f"Using tool format: {data_args.tool_format}.") eos_slots = [] if template.efficient_eos else [{"eos_token"}] template.format_function = FunctionFormatter(slots=eos_slots, tool_format=data_args.tool_format) template.format_tools = ToolFormatter(tool_format=data_args.tool_format) @@ -389,7 +389,7 @@ def get_template_and_fix_tokenizer(tokenizer: "PreTrainedTokenizer", data_args: if tokenizer.pad_token_id is None: tokenizer.pad_token = tokenizer.eos_token - logger.info("Add pad token: {}".format(tokenizer.pad_token)) + logger.info(f"Add pad token: {tokenizer.pad_token}") if stop_words: num_added_tokens = tokenizer.add_special_tokens( diff --git a/src/llamafactory/data/tool_utils.py b/src/llamafactory/data/tool_utils.py index 88027ba6..ca71d47d 100644 --- a/src/llamafactory/data/tool_utils.py +++ b/src/llamafactory/data/tool_utils.py @@ -177,6 +177,6 @@ TOOLS = { def get_tool_utils(name: str) -> "ToolUtils": tool_utils = TOOLS.get(name, None) if tool_utils is None: - raise ValueError("Tool utils `{}` not found.".format(name)) + raise ValueError(f"Tool utils `{name}` not found.") return tool_utils diff --git a/src/llamafactory/eval/evaluator.py b/src/llamafactory/eval/evaluator.py index d445c992..46bc2666 100644 --- a/src/llamafactory/eval/evaluator.py +++ b/src/llamafactory/eval/evaluator.py @@ -87,7 +87,7 @@ class Evaluator: token=self.model_args.hf_hub_token, ) - with open(mapping, "r", encoding="utf-8") as f: + with open(mapping, encoding="utf-8") as f: categorys: Dict[str, Dict[str, str]] = json.load(f) category_corrects = {subj: np.array([], dtype="bool") for subj in SUBJECTS} @@ -139,7 +139,7 @@ class Evaluator: def _save_results(self, category_corrects: Dict[str, "NDArray"], results: Dict[str, Dict[int, str]]) -> None: score_info = "\n".join( [ - "{:>15}: {:.2f}".format(category_name, 100 * np.mean(category_correct)) + f"{category_name:>15}: {100 * np.mean(category_correct):.2f}" for category_name, category_correct in category_corrects.items() if len(category_correct) ] diff --git a/src/llamafactory/eval/template.py b/src/llamafactory/eval/template.py index 7d524e7c..e6ab46a5 100644 --- a/src/llamafactory/eval/template.py +++ b/src/llamafactory/eval/template.py @@ -61,7 +61,7 @@ def _register_eval_template(name: str, system: str, choice: str, answer: str) -> def get_eval_template(name: str) -> "EvalTemplate": eval_template = eval_templates.get(name, None) - assert eval_template is not None, "Template {} does not exist.".format(name) + assert eval_template is not None, f"Template {name} does not exist." return eval_template diff --git a/src/llamafactory/extras/env.py b/src/llamafactory/extras/env.py index 68857c1a..528f3f70 100644 --- a/src/llamafactory/extras/env.py +++ b/src/llamafactory/extras/env.py @@ -72,4 +72,4 @@ def print_env() -> None: except Exception: pass - print("\n" + "\n".join(["- {}: {}".format(key, value) for key, value in info.items()]) + "\n") + print("\n" + "\n".join([f"- {key}: {value}" for key, value in info.items()]) + "\n") diff --git a/src/llamafactory/extras/logging.py b/src/llamafactory/extras/logging.py index 3a9515f6..2704a9a0 100644 --- a/src/llamafactory/extras/logging.py +++ b/src/llamafactory/extras/logging.py @@ -75,7 +75,7 @@ def _get_default_logging_level() -> "logging._Level": if env_level_str.upper() in logging._nameToLevel: return logging._nameToLevel[env_level_str.upper()] else: - raise ValueError("Unknown logging level: {}.".format(env_level_str)) + raise ValueError(f"Unknown logging level: {env_level_str}.") return _default_log_level diff --git a/src/llamafactory/extras/ploting.py b/src/llamafactory/extras/ploting.py index ba8964fb..aa03f721 100644 --- a/src/llamafactory/extras/ploting.py +++ b/src/llamafactory/extras/ploting.py @@ -75,7 +75,7 @@ def plot_loss(save_dictionary: str, keys: List[str] = ["loss"]) -> None: Plots loss curves and saves the image. """ plt.switch_backend("agg") - with open(os.path.join(save_dictionary, TRAINER_STATE_NAME), "r", encoding="utf-8") as f: + with open(os.path.join(save_dictionary, TRAINER_STATE_NAME), encoding="utf-8") as f: data = json.load(f) for key in keys: @@ -92,7 +92,7 @@ def plot_loss(save_dictionary: str, keys: List[str] = ["loss"]) -> None: plt.figure() plt.plot(steps, metrics, color="#1f77b4", alpha=0.4, label="original") plt.plot(steps, smooth(metrics), color="#1f77b4", label="smoothed") - plt.title("training {} of {}".format(key, save_dictionary)) + plt.title(f"training {key} of {save_dictionary}") plt.xlabel("step") plt.ylabel(key) plt.legend() diff --git a/src/llamafactory/hparams/parser.py b/src/llamafactory/hparams/parser.py index f62468a4..90bef820 100644 --- a/src/llamafactory/hparams/parser.py +++ b/src/llamafactory/hparams/parser.py @@ -67,8 +67,8 @@ def _parse_args(parser: "HfArgumentParser", args: Optional[Dict[str, Any]] = Non if unknown_args: print(parser.format_help()) - print("Got unknown args, potentially deprecated arguments: {}".format(unknown_args)) - raise ValueError("Some specified arguments are not used by the HfArgumentParser: {}".format(unknown_args)) + print(f"Got unknown args, potentially deprecated arguments: {unknown_args}") + raise ValueError(f"Some specified arguments are not used by the HfArgumentParser: {unknown_args}") return (*parsed_args,) @@ -323,7 +323,7 @@ def get_train_args(args: Optional[Dict[str, Any]] = None) -> _TRAIN_CLS: if last_checkpoint is not None: training_args.resume_from_checkpoint = last_checkpoint - logger.info("Resuming training from {}.".format(training_args.resume_from_checkpoint)) + logger.info(f"Resuming training from {training_args.resume_from_checkpoint}.") logger.info("Change `output_dir` or use `overwrite_output_dir` to avoid.") if ( diff --git a/src/llamafactory/model/adapter.py b/src/llamafactory/model/adapter.py index 25b0eab8..096bef11 100644 --- a/src/llamafactory/model/adapter.py +++ b/src/llamafactory/model/adapter.py @@ -182,7 +182,7 @@ def _setup_lora_tuning( model = model.merge_and_unload() if len(adapter_to_merge) > 0: - logger.info("Merged {} adapter(s).".format(len(adapter_to_merge))) + logger.info(f"Merged {len(adapter_to_merge)} adapter(s).") if adapter_to_resume is not None: # resume lora training if model_args.use_unsloth: @@ -239,8 +239,8 @@ def _setup_lora_tuning( logger.info("Using PiSSA initialization.") peft_kwargs["init_lora_weights"] = "pissa" else: - logger.info("Using PiSSA initialization with FSVD steps {}.".format(finetuning_args.pissa_iter)) - peft_kwargs["init_lora_weights"] = "pissa_niter_{}".format(finetuning_args.pissa_iter) + logger.info(f"Using PiSSA initialization with FSVD steps {finetuning_args.pissa_iter}.") + peft_kwargs["init_lora_weights"] = f"pissa_niter_{finetuning_args.pissa_iter}" lora_config = LoraConfig( task_type=TaskType.CAUSAL_LM, @@ -300,6 +300,6 @@ def init_adapter( config, model, model_args, finetuning_args, is_trainable, cast_trainable_params_to_fp32 ) else: - raise NotImplementedError("Unknown finetuning type: {}.".format(finetuning_args.finetuning_type)) + raise NotImplementedError(f"Unknown finetuning type: {finetuning_args.finetuning_type}.") return model diff --git a/src/llamafactory/model/loader.py b/src/llamafactory/model/loader.py index 78e2d234..5fdfd8c1 100644 --- a/src/llamafactory/model/loader.py +++ b/src/llamafactory/model/loader.py @@ -100,7 +100,7 @@ def load_tokenizer(model_args: "ModelArguments") -> "TokenizerModule": processor = AutoProcessor.from_pretrained(model_args.model_name_or_path, **init_kwargs) patch_processor(processor, config, tokenizer, model_args) except Exception as e: - logger.warning("Processor was not found: {}.".format(e)) + logger.warning(f"Processor was not found: {e}.") processor = None # Avoid load tokenizer, see: @@ -180,7 +180,7 @@ def load_model( vhead_params = load_valuehead_params(vhead_path, model_args) if vhead_params is not None: model.load_state_dict(vhead_params, strict=False) - logger.info("Loaded valuehead from checkpoint: {}".format(vhead_path)) + logger.info(f"Loaded valuehead from checkpoint: {vhead_path}") if not is_trainable: model.requires_grad_(False) @@ -198,7 +198,7 @@ def load_model( trainable_params, all_param, 100 * trainable_params / all_param ) else: - param_stats = "all params: {:,}".format(all_param) + param_stats = f"all params: {all_param:,}" logger.info(param_stats) diff --git a/src/llamafactory/model/model_utils/attention.py b/src/llamafactory/model/model_utils/attention.py index 7667b069..0ac28115 100644 --- a/src/llamafactory/model/model_utils/attention.py +++ b/src/llamafactory/model/model_utils/attention.py @@ -65,7 +65,7 @@ def configure_attn_implementation( requested_attn_implementation = "flash_attention_2" else: - raise NotImplementedError("Unknown attention type: {}".format(model_args.flash_attn)) + raise NotImplementedError(f"Unknown attention type: {model_args.flash_attn}") if getattr(config, "model_type", None) == "internlm2": # special case for custom models setattr(config, "attn_implementation", requested_attn_implementation) diff --git a/src/llamafactory/model/model_utils/checkpointing.py b/src/llamafactory/model/model_utils/checkpointing.py index 412b4779..88769ae9 100644 --- a/src/llamafactory/model/model_utils/checkpointing.py +++ b/src/llamafactory/model/model_utils/checkpointing.py @@ -111,7 +111,7 @@ def _gradient_checkpointing_enable( from torch.utils.checkpoint import checkpoint if not self.supports_gradient_checkpointing: - raise ValueError("{} does not support gradient checkpointing.".format(self.__class__.__name__)) + raise ValueError(f"{self.__class__.__name__} does not support gradient checkpointing.") if gradient_checkpointing_kwargs is None: gradient_checkpointing_kwargs = {"use_reentrant": True} diff --git a/src/llamafactory/model/model_utils/embedding.py b/src/llamafactory/model/model_utils/embedding.py index 3ff79828..77cad3bf 100644 --- a/src/llamafactory/model/model_utils/embedding.py +++ b/src/llamafactory/model/model_utils/embedding.py @@ -69,4 +69,4 @@ def resize_embedding_layer(model: "PreTrainedModel", tokenizer: "PreTrainedToken _noisy_mean_initialization(model.get_input_embeddings().weight.data, num_new_tokens) _noisy_mean_initialization(model.get_output_embeddings().weight.data, num_new_tokens) - logger.info("Resized token embeddings from {} to {}.".format(current_embedding_size, new_embedding_size)) + logger.info(f"Resized token embeddings from {current_embedding_size} to {new_embedding_size}.") diff --git a/src/llamafactory/model/model_utils/misc.py b/src/llamafactory/model/model_utils/misc.py index 4883fa23..05fe55ea 100644 --- a/src/llamafactory/model/model_utils/misc.py +++ b/src/llamafactory/model/model_utils/misc.py @@ -67,12 +67,12 @@ def find_expanded_modules(model: "PreTrainedModel", target_modules: List[str], n if num_layers % num_layer_trainable != 0: raise ValueError( - "`num_layers` {} should be divisible by `num_layer_trainable` {}.".format(num_layers, num_layer_trainable) + f"`num_layers` {num_layers} should be divisible by `num_layer_trainable` {num_layer_trainable}." ) stride = num_layers // num_layer_trainable trainable_layer_ids = range(stride - 1, num_layers + stride - 1, stride) - trainable_layers = [".{:d}.".format(idx) for idx in trainable_layer_ids] + trainable_layers = [f".{idx:d}." for idx in trainable_layer_ids] module_names = [] for name, _ in model.named_modules(): if any(target_module in name for target_module in target_modules) and any( diff --git a/src/llamafactory/model/model_utils/quantization.py b/src/llamafactory/model/model_utils/quantization.py index 451abee0..441d9bb8 100644 --- a/src/llamafactory/model/model_utils/quantization.py +++ b/src/llamafactory/model/model_utils/quantization.py @@ -130,7 +130,7 @@ def configure_quantization( quantization_config["bits"] = 2 quant_bits = quantization_config.get("bits", "?") - logger.info("Loading {}-bit {}-quantized model.".format(quant_bits, quant_method.upper())) + logger.info(f"Loading {quant_bits}-bit {quant_method.upper()}-quantized model.") elif model_args.export_quantization_bit is not None: # auto-gptq if model_args.export_quantization_bit not in [8, 4, 3, 2]: @@ -149,7 +149,7 @@ def configure_quantization( ) init_kwargs["device_map"] = "auto" init_kwargs["max_memory"] = get_max_memory() - logger.info("Quantizing model to {} bit with AutoGPTQ.".format(model_args.export_quantization_bit)) + logger.info(f"Quantizing model to {model_args.export_quantization_bit} bit with AutoGPTQ.") elif model_args.quantization_bit is not None: # on-the-fly if model_args.quantization_method == QuantizationMethod.BITS_AND_BYTES.value: @@ -179,7 +179,7 @@ def configure_quantization( else: init_kwargs["device_map"] = {"": get_current_device()} # change auto device map for inference - logger.info("Quantizing model to {} bit with bitsandbytes.".format(model_args.quantization_bit)) + logger.info(f"Quantizing model to {model_args.quantization_bit} bit with bitsandbytes.") elif model_args.quantization_method == QuantizationMethod.HQQ.value: if model_args.quantization_bit not in [8, 6, 5, 4, 3, 2, 1]: raise ValueError("HQQ only accepts 1/2/3/4/5/6/8-bit quantization.") @@ -191,7 +191,7 @@ def configure_quantization( init_kwargs["quantization_config"] = HqqConfig( nbits=model_args.quantization_bit, quant_zero=False, quant_scale=False, axis=0 ) # use ATEN kernel (axis=0) for performance - logger.info("Quantizing model to {} bit with HQQ.".format(model_args.quantization_bit)) + logger.info(f"Quantizing model to {model_args.quantization_bit} bit with HQQ.") elif model_args.quantization_method == QuantizationMethod.EETQ.value: if model_args.quantization_bit != 8: raise ValueError("EETQ only accepts 8-bit quantization.") @@ -201,4 +201,4 @@ def configure_quantization( require_version("eetq", "To fix: pip install eetq") init_kwargs["quantization_config"] = EetqConfig() - logger.info("Quantizing model to {} bit with EETQ.".format(model_args.quantization_bit)) + logger.info(f"Quantizing model to {model_args.quantization_bit} bit with EETQ.") diff --git a/src/llamafactory/model/model_utils/rope.py b/src/llamafactory/model/model_utils/rope.py index 4373ee19..add6af68 100644 --- a/src/llamafactory/model/model_utils/rope.py +++ b/src/llamafactory/model/model_utils/rope.py @@ -48,9 +48,7 @@ def configure_rope(config: "PretrainedConfig", model_args: "ModelArguments", is_ current_max_length = getattr(config, "max_position_embeddings", None) if current_max_length and model_args.model_max_length > current_max_length: - logger.info( - "Enlarge max model length from {} to {}.".format(current_max_length, model_args.model_max_length) - ) + logger.info(f"Enlarge max model length from {current_max_length} to {model_args.model_max_length}.") setattr(config, "max_position_embeddings", model_args.model_max_length) scaling_factor = float(math.ceil(model_args.model_max_length / current_max_length)) else: @@ -60,6 +58,4 @@ def configure_rope(config: "PretrainedConfig", model_args: "ModelArguments", is_ scaling_factor = 2.0 setattr(config, "rope_scaling", {"type": model_args.rope_scaling, "factor": scaling_factor}) - logger.info( - "Using {} scaling strategy and setting scaling factor to {}".format(model_args.rope_scaling, scaling_factor) - ) + logger.info(f"Using {model_args.rope_scaling} scaling strategy and setting scaling factor to {scaling_factor}") diff --git a/src/llamafactory/model/model_utils/valuehead.py b/src/llamafactory/model/model_utils/valuehead.py index 9ab3d45a..93282493 100644 --- a/src/llamafactory/model/model_utils/valuehead.py +++ b/src/llamafactory/model/model_utils/valuehead.py @@ -54,7 +54,7 @@ def load_valuehead_params(path_or_repo_id: str, model_args: "ModelArguments") -> except Exception as err: err_text = str(err) - logger.info("Provided path ({}) does not contain value head weights: {}.".format(path_or_repo_id, err_text)) + logger.info(f"Provided path ({path_or_repo_id}) does not contain value head weights: {err_text}.") logger.info("Ignore the above message if you are not resuming the training of a value head model.") return None diff --git a/src/llamafactory/model/model_utils/visual.py b/src/llamafactory/model/model_utils/visual.py index c2aeb0dd..ac95eead 100644 --- a/src/llamafactory/model/model_utils/visual.py +++ b/src/llamafactory/model/model_utils/visual.py @@ -99,7 +99,7 @@ def autocast_projector_dtype(model: "PreTrainedModel", model_args: "ModelArgumen else: return - logger.info("Casting multimodal projector outputs in {}.".format(model_args.compute_dtype)) + logger.info(f"Casting multimodal projector outputs in {model_args.compute_dtype}.") mm_projector.register_forward_hook(_mm_projector_forward_post_hook) diff --git a/src/llamafactory/train/callbacks.py b/src/llamafactory/train/callbacks.py index 105acadb..5a80d81a 100644 --- a/src/llamafactory/train/callbacks.py +++ b/src/llamafactory/train/callbacks.py @@ -92,7 +92,7 @@ def fix_valuehead_checkpoint( else: torch.save(v_head_state_dict, os.path.join(output_dir, V_HEAD_WEIGHTS_NAME)) - logger.info("Value head model saved at: {}".format(output_dir)) + logger.info(f"Value head model saved at: {output_dir}") class FixValueHeadModelCallback(TrainerCallback): @@ -106,7 +106,7 @@ class FixValueHeadModelCallback(TrainerCallback): Event called after a checkpoint save. """ if args.should_save: - output_dir = os.path.join(args.output_dir, "{}-{}".format(PREFIX_CHECKPOINT_DIR, state.global_step)) + output_dir = os.path.join(args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}") fix_valuehead_checkpoint( model=kwargs.pop("model"), output_dir=output_dir, safe_serialization=args.save_safetensors ) @@ -123,7 +123,7 @@ class SaveProcessorCallback(TrainerCallback): @override def on_save(self, args: "TrainingArguments", state: "TrainerState", control: "TrainerControl", **kwargs): if args.should_save: - output_dir = os.path.join(args.output_dir, "{}-{}".format(PREFIX_CHECKPOINT_DIR, state.global_step)) + output_dir = os.path.join(args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}") getattr(self.processor, "image_processor").save_pretrained(output_dir) @override @@ -145,7 +145,7 @@ class PissaConvertCallback(TrainerCallback): if args.should_save: model = kwargs.pop("model") pissa_init_dir = os.path.join(args.output_dir, "pissa_init") - logger.info("Initial PiSSA adapter will be saved at: {}.".format(pissa_init_dir)) + logger.info(f"Initial PiSSA adapter will be saved at: {pissa_init_dir}.") if isinstance(model, PeftModel): init_lora_weights = getattr(model.peft_config["default"], "init_lora_weights") setattr(model.peft_config["default"], "init_lora_weights", True) @@ -159,7 +159,7 @@ class PissaConvertCallback(TrainerCallback): pissa_init_dir = os.path.join(args.output_dir, "pissa_init") pissa_backup_dir = os.path.join(args.output_dir, "pissa_backup") pissa_convert_dir = os.path.join(args.output_dir, "pissa_converted") - logger.info("Converted PiSSA adapter will be saved at: {}.".format(pissa_convert_dir)) + logger.info(f"Converted PiSSA adapter will be saved at: {pissa_convert_dir}.") # 1. save a pissa backup with init_lora_weights: True # 2. save a converted lora with init_lora_weights: pissa # 3. load the pissa backup with init_lora_weights: True diff --git a/src/llamafactory/train/dpo/trainer.py b/src/llamafactory/train/dpo/trainer.py index 2a0e7705..39eff9b7 100644 --- a/src/llamafactory/train/dpo/trainer.py +++ b/src/llamafactory/train/dpo/trainer.py @@ -156,7 +156,7 @@ class CustomDPOTrainer(DPOTrainer): elif self.loss_type == "simpo": losses = self.simpo_loss(policy_chosen_logps, policy_rejected_logps) else: - raise NotImplementedError("Unknown loss type: {}.".format(self.loss_type)) + raise NotImplementedError(f"Unknown loss type: {self.loss_type}.") chosen_rewards = self.beta * policy_chosen_logps.to(self.accelerator.device).detach() rejected_rewards = self.beta * policy_rejected_logps.to(self.accelerator.device).detach() @@ -245,16 +245,16 @@ class CustomDPOTrainer(DPOTrainer): reward_accuracies = (chosen_rewards > rejected_rewards).float() prefix = "eval_" if train_eval == "eval" else "" - metrics["{}rewards/chosen".format(prefix)] = chosen_rewards.mean().cpu() - metrics["{}rewards/rejected".format(prefix)] = rejected_rewards.mean().cpu() - metrics["{}rewards/accuracies".format(prefix)] = reward_accuracies.mean().cpu() - metrics["{}rewards/margins".format(prefix)] = (chosen_rewards - rejected_rewards).mean().cpu() - metrics["{}logps/rejected".format(prefix)] = policy_rejected_logps.detach().mean().cpu() - metrics["{}logps/chosen".format(prefix)] = policy_chosen_logps.detach().mean().cpu() - metrics["{}logits/rejected".format(prefix)] = policy_rejected_logits.detach().mean().cpu() - metrics["{}logits/chosen".format(prefix)] = policy_chosen_logits.detach().mean().cpu() + metrics[f"{prefix}rewards/chosen"] = chosen_rewards.mean().cpu() + metrics[f"{prefix}rewards/rejected"] = rejected_rewards.mean().cpu() + metrics[f"{prefix}rewards/accuracies"] = reward_accuracies.mean().cpu() + metrics[f"{prefix}rewards/margins"] = (chosen_rewards - rejected_rewards).mean().cpu() + metrics[f"{prefix}logps/rejected"] = policy_rejected_logps.detach().mean().cpu() + metrics[f"{prefix}logps/chosen"] = policy_chosen_logps.detach().mean().cpu() + metrics[f"{prefix}logits/rejected"] = policy_rejected_logits.detach().mean().cpu() + metrics[f"{prefix}logits/chosen"] = policy_chosen_logits.detach().mean().cpu() if self.loss_type == "orpo": - metrics["{}sft_loss".format(prefix)] = sft_loss.detach().mean().cpu() - metrics["{}odds_ratio_loss".format(prefix)] = ((losses - sft_loss) / self.beta).detach().mean().cpu() + metrics[f"{prefix}sft_loss"] = sft_loss.detach().mean().cpu() + metrics[f"{prefix}odds_ratio_loss"] = ((losses - sft_loss) / self.beta).detach().mean().cpu() return losses.mean(), metrics diff --git a/src/llamafactory/train/kto/trainer.py b/src/llamafactory/train/kto/trainer.py index f547c5aa..6c0e6254 100644 --- a/src/llamafactory/train/kto/trainer.py +++ b/src/llamafactory/train/kto/trainer.py @@ -129,11 +129,11 @@ class CustomKTOTrainer(KTOTrainer): """ batch = {k: v.detach().clone() for k, v in batch.items()} # avoid error model_inputs = { - "input_ids": batch["{}input_ids".format(prefix)], - "attention_mask": batch["{}attention_mask".format(prefix)], + "input_ids": batch[f"{prefix}input_ids"], + "attention_mask": batch[f"{prefix}attention_mask"], } - if "{}token_type_ids".format(prefix) in batch: - model_inputs["token_type_ids"] = batch["{}token_type_ids".format(prefix)] + if f"{prefix}token_type_ids" in batch: + model_inputs["token_type_ids"] = batch[f"{prefix}token_type_ids"] if "pixel_values" in batch: model_inputs["pixel_values"] = batch["pixel_values"] @@ -142,7 +142,7 @@ class CustomKTOTrainer(KTOTrainer): model_inputs["image_grid_thw"] = batch["image_grid_thw"] logits = model(**model_inputs, return_dict=True, use_cache=False).logits.to(torch.float32) - logps, valid_length = get_batch_logps(logits=logits, labels=batch["{}labels".format(prefix)]) + logps, valid_length = get_batch_logps(logits=logits, labels=batch[f"{prefix}labels"]) return logps, logps / valid_length @override diff --git a/src/llamafactory/train/ppo/ppo_utils.py b/src/llamafactory/train/ppo/ppo_utils.py index 27031a45..11ce25a9 100644 --- a/src/llamafactory/train/ppo/ppo_utils.py +++ b/src/llamafactory/train/ppo/ppo_utils.py @@ -62,8 +62,8 @@ def replace_model(model: "AutoModelForCausalLMWithValueHead", target: Literal["d setattr(model, "default_head_bias", v_head_layer.bias.data.detach().clone()) device = v_head_layer.weight.device - v_head_layer.weight.data = model.get_buffer("{}_head_weight".format(target)).detach().clone().to(device) - v_head_layer.bias.data = model.get_buffer("{}_head_bias".format(target)).detach().clone().to(device) + v_head_layer.weight.data = model.get_buffer(f"{target}_head_weight").detach().clone().to(device) + v_head_layer.bias.data = model.get_buffer(f"{target}_head_bias").detach().clone().to(device) def dump_layernorm(model: "PreTrainedModel") -> Dict[str, "torch.Tensor"]: diff --git a/src/llamafactory/train/ppo/trainer.py b/src/llamafactory/train/ppo/trainer.py index a75a9aa0..d1510c47 100644 --- a/src/llamafactory/train/ppo/trainer.py +++ b/src/llamafactory/train/ppo/trainer.py @@ -218,18 +218,18 @@ class CustomPPOTrainer(PPOTrainer, Trainer): if self.is_world_process_zero(): logger.info("***** Running training *****") - logger.info(" Num examples = {:,}".format(num_examples)) - logger.info(" Num Epochs = {:,}".format(num_train_epochs)) - logger.info(" Instantaneous batch size per device = {:,}".format(self.args.per_device_train_batch_size)) + logger.info(f" Num examples = {num_examples:,}") + logger.info(f" Num Epochs = {num_train_epochs:,}") + logger.info(f" Instantaneous batch size per device = {self.args.per_device_train_batch_size:,}") logger.info( " Total train batch size (w. parallel, buffer, distributed & accumulation) = {:,}".format( total_train_batch_size ) ) - logger.info(" Gradient Accumulation steps = {:,}".format(self.args.gradient_accumulation_steps)) - logger.info(" Num optimization epochs per batch = {:,}".format(self.finetuning_args.ppo_epochs)) - logger.info(" Total training steps = {:,}".format(max_steps)) - logger.info(" Number of trainable parameters = {:,}".format(count_parameters(self.model)[0])) + logger.info(f" Gradient Accumulation steps = {self.args.gradient_accumulation_steps:,}") + logger.info(f" Num optimization epochs per batch = {self.finetuning_args.ppo_epochs:,}") + logger.info(f" Total training steps = {max_steps:,}") + logger.info(f" Number of trainable parameters = {count_parameters(self.model)[0]:,}") dataiter = iter(self.dataloader) loss_meter = AverageMeter() @@ -290,7 +290,7 @@ class CustomPPOTrainer(PPOTrainer, Trainer): if (step + 1) % self.args.save_steps == 0: # save checkpoint self.save_model( - os.path.join(self.args.output_dir, "{}-{}".format(PREFIX_CHECKPOINT_DIR, self.state.global_step)) + os.path.join(self.args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{self.state.global_step}") ) self.callback_handler.on_save(self.args, self.state, self.control) diff --git a/src/llamafactory/train/trainer_utils.py b/src/llamafactory/train/trainer_utils.py index bc97e205..2d077398 100644 --- a/src/llamafactory/train/trainer_utils.py +++ b/src/llamafactory/train/trainer_utils.py @@ -116,7 +116,7 @@ def create_ref_model( ref_model = load_model( tokenizer, ref_model_args, ref_finetuning_args, is_trainable=False, add_valuehead=add_valuehead ) - logger.info("Created reference model from {}".format(finetuning_args.ref_model)) + logger.info(f"Created reference model from {finetuning_args.ref_model}") else: if finetuning_args.finetuning_type == "lora": ref_model = None @@ -140,7 +140,7 @@ def create_reward_model( """ if finetuning_args.reward_model_type == "api": assert finetuning_args.reward_model.startswith("http"), "Please provide full url." - logger.info("Use reward server {}".format(finetuning_args.reward_model)) + logger.info(f"Use reward server {finetuning_args.reward_model}") return finetuning_args.reward_model elif finetuning_args.reward_model_type == "lora": model.pretrained_model.load_adapter(finetuning_args.reward_model, "reward") @@ -157,7 +157,7 @@ def create_reward_model( model.register_buffer( "default_head_bias", torch.zeros_like(vhead_params["v_head.summary.bias"]), persistent=False ) - logger.info("Loaded adapter weights of reward model from {}".format(finetuning_args.reward_model)) + logger.info(f"Loaded adapter weights of reward model from {finetuning_args.reward_model}") return None else: reward_model_args = ModelArguments.copyfrom( @@ -171,7 +171,7 @@ def create_reward_model( reward_model = load_model( tokenizer, reward_model_args, reward_finetuning_args, is_trainable=False, add_valuehead=True ) - logger.info("Loaded full weights of reward model from {}".format(finetuning_args.reward_model)) + logger.info(f"Loaded full weights of reward model from {finetuning_args.reward_model}") logger.warning("Please ensure the ppo model and reward model share SAME tokenizer and vocabulary.") return reward_model @@ -231,7 +231,7 @@ def _create_galore_optimizer( elif training_args.optim == "adafactor": optim_class = GaLoreAdafactor else: - raise NotImplementedError("Unknow optim: {}".format(training_args.optim)) + raise NotImplementedError(f"Unknow optim: {training_args.optim}") if finetuning_args.galore_layerwise: if training_args.gradient_accumulation_steps != 1: @@ -305,7 +305,7 @@ def _create_loraplus_optimizer( dict(params=param_dict["embedding"], lr=embedding_lr, weight_decay=training_args.weight_decay), ] optimizer = optim_class(param_groups, **optim_kwargs) - logger.info("Using LoRA+ optimizer with loraplus lr ratio {:.2f}.".format(finetuning_args.loraplus_lr_ratio)) + logger.info(f"Using LoRA+ optimizer with loraplus lr ratio {finetuning_args.loraplus_lr_ratio:.2f}.") return optimizer diff --git a/src/llamafactory/train/tuner.py b/src/llamafactory/train/tuner.py index 1fd202aa..e5901973 100644 --- a/src/llamafactory/train/tuner.py +++ b/src/llamafactory/train/tuner.py @@ -57,7 +57,7 @@ def run_exp(args: Optional[Dict[str, Any]] = None, callbacks: List["TrainerCallb elif finetuning_args.stage == "kto": run_kto(model_args, data_args, training_args, finetuning_args, callbacks) else: - raise ValueError("Unknown task: {}.".format(finetuning_args.stage)) + raise ValueError(f"Unknown task: {finetuning_args.stage}.") def export_model(args: Optional[Dict[str, Any]] = None) -> None: @@ -91,18 +91,18 @@ def export_model(args: Optional[Dict[str, Any]] = None) -> None: setattr(model.config, "torch_dtype", output_dtype) model = model.to(output_dtype) - logger.info("Convert model dtype to: {}.".format(output_dtype)) + logger.info(f"Convert model dtype to: {output_dtype}.") model.save_pretrained( save_directory=model_args.export_dir, - max_shard_size="{}GB".format(model_args.export_size), + max_shard_size=f"{model_args.export_size}GB", safe_serialization=(not model_args.export_legacy_format), ) if model_args.export_hub_model_id is not None: model.push_to_hub( model_args.export_hub_model_id, token=model_args.hf_hub_token, - max_shard_size="{}GB".format(model_args.export_size), + max_shard_size=f"{model_args.export_size}GB", safe_serialization=(not model_args.export_legacy_format), ) @@ -117,13 +117,13 @@ def export_model(args: Optional[Dict[str, Any]] = None) -> None: os.path.join(vhead_path, V_HEAD_SAFE_WEIGHTS_NAME), os.path.join(model_args.export_dir, V_HEAD_SAFE_WEIGHTS_NAME), ) - logger.info("Copied valuehead to {}.".format(model_args.export_dir)) + logger.info(f"Copied valuehead to {model_args.export_dir}.") elif os.path.exists(os.path.join(vhead_path, V_HEAD_WEIGHTS_NAME)): shutil.copy( os.path.join(vhead_path, V_HEAD_WEIGHTS_NAME), os.path.join(model_args.export_dir, V_HEAD_WEIGHTS_NAME), ) - logger.info("Copied valuehead to {}.".format(model_args.export_dir)) + logger.info(f"Copied valuehead to {model_args.export_dir}.") try: tokenizer.padding_side = "left" # restore padding side @@ -140,4 +140,4 @@ def export_model(args: Optional[Dict[str, Any]] = None) -> None: ) except Exception as e: - logger.warning("Cannot save tokenizer, please copy the files manually: {}.".format(e)) + logger.warning(f"Cannot save tokenizer, please copy the files manually: {e}.") diff --git a/src/llamafactory/webui/common.py b/src/llamafactory/webui/common.py index b28626bc..5ae0d5fa 100644 --- a/src/llamafactory/webui/common.py +++ b/src/llamafactory/webui/common.py @@ -75,7 +75,7 @@ def load_config() -> Dict[str, Any]: Loads user config if exists. """ try: - with open(get_config_path(), "r", encoding="utf-8") as f: + with open(get_config_path(), encoding="utf-8") as f: return safe_load(f) except Exception: return {"lang": None, "last_model": None, "path_dict": {}, "cache_dir": None} @@ -172,14 +172,14 @@ def load_dataset_info(dataset_dir: str) -> Dict[str, Dict[str, Any]]: Loads dataset_info.json. """ if dataset_dir == "ONLINE" or dataset_dir.startswith("REMOTE:"): - logger.info("dataset_dir is {}, using online dataset.".format(dataset_dir)) + logger.info(f"dataset_dir is {dataset_dir}, using online dataset.") return {} try: - with open(os.path.join(dataset_dir, DATA_CONFIG), "r", encoding="utf-8") as f: + with open(os.path.join(dataset_dir, DATA_CONFIG), encoding="utf-8") as f: return json.load(f) except Exception as err: - logger.warning("Cannot open {} due to {}.".format(os.path.join(dataset_dir, DATA_CONFIG), str(err))) + logger.warning(f"Cannot open {os.path.join(dataset_dir, DATA_CONFIG)} due to {str(err)}.") return {} diff --git a/src/llamafactory/webui/components/data.py b/src/llamafactory/webui/components/data.py index 88e500cf..cc0428fe 100644 --- a/src/llamafactory/webui/components/data.py +++ b/src/llamafactory/webui/components/data.py @@ -41,7 +41,7 @@ def next_page(page_index: int, total_num: int) -> int: def can_preview(dataset_dir: str, dataset: list) -> "gr.Button": try: - with open(os.path.join(dataset_dir, DATA_CONFIG), "r", encoding="utf-8") as f: + with open(os.path.join(dataset_dir, DATA_CONFIG), encoding="utf-8") as f: dataset_info = json.load(f) except Exception: return gr.Button(interactive=False) @@ -57,7 +57,7 @@ def can_preview(dataset_dir: str, dataset: list) -> "gr.Button": def _load_data_file(file_path: str) -> List[Any]: - with open(file_path, "r", encoding="utf-8") as f: + with open(file_path, encoding="utf-8") as f: if file_path.endswith(".json"): return json.load(f) elif file_path.endswith(".jsonl"): @@ -67,7 +67,7 @@ def _load_data_file(file_path: str) -> List[Any]: def get_preview(dataset_dir: str, dataset: list, page_index: int) -> Tuple[int, list, "gr.Column"]: - with open(os.path.join(dataset_dir, DATA_CONFIG), "r", encoding="utf-8") as f: + with open(os.path.join(dataset_dir, DATA_CONFIG), encoding="utf-8") as f: dataset_info = json.load(f) data_path = os.path.join(dataset_dir, dataset_info[dataset[0]]["file_name"]) diff --git a/src/llamafactory/webui/engine.py b/src/llamafactory/webui/engine.py index a41e6974..deb9dee1 100644 --- a/src/llamafactory/webui/engine.py +++ b/src/llamafactory/webui/engine.py @@ -56,9 +56,9 @@ class Engine: if not self.pure_chat: current_time = get_time() init_dict["train.current_time"] = {"value": current_time} - init_dict["train.output_dir"] = {"value": "train_{}".format(current_time)} - init_dict["train.config_path"] = {"value": "{}.yaml".format(current_time)} - init_dict["eval.output_dir"] = {"value": "eval_{}".format(current_time)} + init_dict["train.output_dir"] = {"value": f"train_{current_time}"} + init_dict["train.config_path"] = {"value": f"{current_time}.yaml"} + init_dict["eval.output_dir"] = {"value": f"eval_{current_time}"} init_dict["infer.mm_box"] = {"visible": False} if user_config.get("last_model", None): diff --git a/src/llamafactory/webui/manager.py b/src/llamafactory/webui/manager.py index 61c2f35a..c34d8e54 100644 --- a/src/llamafactory/webui/manager.py +++ b/src/llamafactory/webui/manager.py @@ -29,7 +29,7 @@ class Manager: Adds elements to manager. """ for elem_name, elem in elem_dict.items(): - elem_id = "{}.{}".format(tab_name, elem_name) + elem_id = f"{tab_name}.{elem_name}" self._id_to_elem[elem_id] = elem self._elem_to_id[elem] = elem_id diff --git a/src/llamafactory/webui/runner.py b/src/llamafactory/webui/runner.py index 55d15b41..41de62fb 100644 --- a/src/llamafactory/webui/runner.py +++ b/src/llamafactory/webui/runner.py @@ -231,7 +231,7 @@ class Runner: if get("train.ds_stage") != "none": ds_stage = get("train.ds_stage") ds_offload = "offload_" if get("train.ds_offload") else "" - args["deepspeed"] = os.path.join(DEFAULT_CACHE_DIR, "ds_z{}_{}config.json".format(ds_stage, ds_offload)) + args["deepspeed"] = os.path.join(DEFAULT_CACHE_DIR, f"ds_z{ds_stage}_{ds_offload}config.json") return args @@ -313,7 +313,7 @@ class Runner: if args.get("deepspeed", None) is not None: env["FORCE_TORCHRUN"] = "1" - self.trainer = Popen("llamafactory-cli train {}".format(save_cmd(args)), env=env, shell=True) + self.trainer = Popen(f"llamafactory-cli train {save_cmd(args)}", env=env, shell=True) yield from self.monitor() def _form_config_dict(self, data: Dict["Component", Any]) -> Dict[str, Any]: diff --git a/src/llamafactory/webui/utils.py b/src/llamafactory/webui/utils.py index c52c0887..b014e192 100644 --- a/src/llamafactory/webui/utils.py +++ b/src/llamafactory/webui/utils.py @@ -111,14 +111,14 @@ def gen_cmd(args: Dict[str, Any]) -> str: """ cmd_lines = ["llamafactory-cli train "] for k, v in clean_cmd(args).items(): - cmd_lines.append(" --{} {} ".format(k, str(v))) + cmd_lines.append(f" --{k} {str(v)} ") if os.name == "nt": cmd_text = "`\n".join(cmd_lines) else: cmd_text = "\\\n".join(cmd_lines) - cmd_text = "```bash\n{}\n```".format(cmd_text) + cmd_text = f"```bash\n{cmd_text}\n```" return cmd_text @@ -139,9 +139,9 @@ def get_eval_results(path: os.PathLike) -> str: r""" Gets scores after evaluation. """ - with open(path, "r", encoding="utf-8") as f: + with open(path, encoding="utf-8") as f: result = json.dumps(json.load(f), indent=4) - return "```json\n{}\n```\n".format(result) + return f"```json\n{result}\n```\n" def get_time() -> str: @@ -161,13 +161,13 @@ def get_trainer_info(output_path: os.PathLike, do_train: bool) -> Tuple[str, "gr running_log_path = os.path.join(output_path, RUNNING_LOG) if os.path.isfile(running_log_path): - with open(running_log_path, "r", encoding="utf-8") as f: + with open(running_log_path, encoding="utf-8") as f: running_log = f.read() trainer_log_path = os.path.join(output_path, TRAINER_LOG) if os.path.isfile(trainer_log_path): trainer_log: List[Dict[str, Any]] = [] - with open(trainer_log_path, "r", encoding="utf-8") as f: + with open(trainer_log_path, encoding="utf-8") as f: for line in f: trainer_log.append(json.loads(line)) @@ -193,7 +193,7 @@ def load_args(config_path: str) -> Optional[Dict[str, Any]]: Loads saved arguments. """ try: - with open(config_path, "r", encoding="utf-8") as f: + with open(config_path, encoding="utf-8") as f: return safe_load(f) except Exception: return None @@ -211,7 +211,7 @@ def list_config_paths(current_time: str) -> "gr.Dropdown": r""" Lists all the saved configuration files. """ - config_files = ["{}.yaml".format(current_time)] + config_files = [f"{current_time}.yaml"] if os.path.isdir(DEFAULT_CONFIG_DIR): for file_name in os.listdir(DEFAULT_CONFIG_DIR): if file_name.endswith(".yaml") and file_name not in config_files: @@ -224,7 +224,7 @@ def list_output_dirs(model_name: Optional[str], finetuning_type: str, current_ti r""" Lists all the directories that can resume from. """ - output_dirs = ["train_{}".format(current_time)] + output_dirs = [f"train_{current_time}"] if model_name: save_dir = get_save_dir(model_name, finetuning_type) if save_dir and os.path.isdir(save_dir): diff --git a/tests/e2e/test_train.py b/tests/e2e/test_train.py index b997bc9b..c5b14413 100644 --- a/tests/e2e/test_train.py +++ b/tests/e2e/test_train.py @@ -61,7 +61,7 @@ OS_NAME = os.environ.get("OS_NAME", "") ], ) def test_run_exp(stage: str, dataset: str): - output_dir = "train_{}".format(stage) + output_dir = f"train_{stage}" run_exp({"stage": stage, "dataset": dataset, "output_dir": output_dir, **TRAIN_ARGS}) assert os.path.exists(output_dir)