You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

AutoML-NLP.md 13 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. # AutoML - NLP
  2. ### Requirements
  3. This example requires GPU. Install the [automl,hf] option:
  4. ```python
  5. pip install "flaml[automl,hf]"
  6. ```
  7. ### A simple sequence classification example
  8. ```python
  9. from flaml import AutoML
  10. from datasets import load_dataset
  11. train_dataset = load_dataset("glue", "mrpc", split="train").to_pandas()
  12. dev_dataset = load_dataset("glue", "mrpc", split="validation").to_pandas()
  13. test_dataset = load_dataset("glue", "mrpc", split="test").to_pandas()
  14. custom_sent_keys = ["sentence1", "sentence2"]
  15. label_key = "label"
  16. X_train, y_train = train_dataset[custom_sent_keys], train_dataset[label_key]
  17. X_val, y_val = dev_dataset[custom_sent_keys], dev_dataset[label_key]
  18. X_test = test_dataset[custom_sent_keys]
  19. automl = AutoML()
  20. automl_settings = {
  21. "time_budget": 100,
  22. "task": "seq-classification",
  23. "fit_kwargs_by_estimator": {
  24. "transformer":
  25. {
  26. "output_dir": "data/output/" # if model_path is not set, the default model is facebook/muppet-roberta-base: https://huggingface.co/facebook/muppet-roberta-base
  27. }
  28. }, # setting the huggingface arguments: output directory
  29. "gpu_per_trial": 1, # set to 0 if no GPU is available
  30. }
  31. automl.fit(X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val, **automl_settings)
  32. automl.predict(X_test)
  33. ```
  34. Notice that after you run `automl.fit`, the intermediate checkpoints are saved under the specified output_dir `data/output`. You can use the following code to clean these outputs if they consume a large storage space:
  35. ```python
  36. if os.path.exists("data/output/"):
  37. shutil.rmtree("data/output/")
  38. ```
  39. #### Sample output
  40. ```
  41. [flaml.automl: 12-06 08:21:39] {1943} INFO - task = seq-classification
  42. [flaml.automl: 12-06 08:21:39] {1945} INFO - Data split method: stratified
  43. [flaml.automl: 12-06 08:21:39] {1949} INFO - Evaluation method: holdout
  44. [flaml.automl: 12-06 08:21:39] {2019} INFO - Minimizing error metric: 1-accuracy
  45. [flaml.automl: 12-06 08:21:39] {2071} INFO - List of ML learners in AutoML Run: ['transformer']
  46. [flaml.automl: 12-06 08:21:39] {2311} INFO - iteration 0, current learner transformer
  47. {'data/output/train_2021-12-06_08-21-53/train_8947b1b2_1_n=1e-06,s=9223372036854775807,e=1e-05,s=-1,s=0.45765,e=32,d=42,o=0.0,y=0.0_2021-12-06_08-21-53/checkpoint-53': 53}
  48. [flaml.automl: 12-06 08:22:56] {2424} INFO - Estimated sufficient time budget=766860s. Estimated necessary time budget=767s.
  49. [flaml.automl: 12-06 08:22:56] {2499} INFO - at 76.7s, estimator transformer's best error=0.1740, best estimator transformer's best error=0.1740
  50. [flaml.automl: 12-06 08:22:56] {2606} INFO - selected model: <flaml.nlp.huggingface.trainer.TrainerForAuto object at 0x7f49ea8414f0>
  51. [flaml.automl: 12-06 08:22:56] {2100} INFO - fit succeeded
  52. [flaml.automl: 12-06 08:22:56] {2101} INFO - Time taken to find the best model: 76.69802761077881
  53. [flaml.automl: 12-06 08:22:56] {2112} WARNING - Time taken to find the best model is 77% of the provided time budget and not all estimators' hyperparameter search converged. Consider increasing the time budget.
  54. ```
  55. ### A simple sequence regression example
  56. ```python
  57. from flaml import AutoML
  58. from datasets import load_dataset
  59. train_dataset = (
  60. load_dataset("glue", "stsb", split="train").to_pandas()
  61. )
  62. dev_dataset = (
  63. load_dataset("glue", "stsb", split="train").to_pandas()
  64. )
  65. custom_sent_keys = ["sentence1", "sentence2"]
  66. label_key = "label"
  67. X_train = train_dataset[custom_sent_keys]
  68. y_train = train_dataset[label_key]
  69. X_val = dev_dataset[custom_sent_keys]
  70. y_val = dev_dataset[label_key]
  71. automl = AutoML()
  72. automl_settings = {
  73. "gpu_per_trial": 0,
  74. "time_budget": 20,
  75. "task": "seq-regression",
  76. "metric": "rmse",
  77. }
  78. automl_settings["fit_kwargs_by_estimator"] = { # setting the huggingface arguments
  79. "transformer": {
  80. "model_path": "google/electra-small-discriminator", # if model_path is not set, the default model is facebook/muppet-roberta-base: https://huggingface.co/facebook/muppet-roberta-base
  81. "output_dir": "data/output/", # setting the output directory
  82. "fp16": False,
  83. } # setting whether to use FP16
  84. }
  85. automl.fit(
  86. X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val, **automl_settings
  87. )
  88. ```
  89. #### Sample output
  90. ```
  91. [flaml.automl: 12-20 11:47:28] {1965} INFO - task = seq-regression
  92. [flaml.automl: 12-20 11:47:28] {1967} INFO - Data split method: uniform
  93. [flaml.automl: 12-20 11:47:28] {1971} INFO - Evaluation method: holdout
  94. [flaml.automl: 12-20 11:47:28] {2063} INFO - Minimizing error metric: rmse
  95. [flaml.automl: 12-20 11:47:28] {2115} INFO - List of ML learners in AutoML Run: ['transformer']
  96. [flaml.automl: 12-20 11:47:28] {2355} INFO - iteration 0, current learner transformer
  97. ```
  98. ### A simple summarization example
  99. ```python
  100. from flaml import AutoML
  101. from datasets import load_dataset
  102. train_dataset = (
  103. load_dataset("xsum", split="train").to_pandas()
  104. )
  105. dev_dataset = (
  106. load_dataset("xsum", split="validation").to_pandas()
  107. )
  108. custom_sent_keys = ["document"]
  109. label_key = "summary"
  110. X_train = train_dataset[custom_sent_keys]
  111. y_train = train_dataset[label_key]
  112. X_val = dev_dataset[custom_sent_keys]
  113. y_val = dev_dataset[label_key]
  114. automl = AutoML()
  115. automl_settings = {
  116. "gpu_per_trial": 1,
  117. "time_budget": 20,
  118. "task": "summarization",
  119. "metric": "rouge1",
  120. }
  121. automl_settings["fit_kwargs_by_estimator"] = { # setting the huggingface arguments
  122. "transformer": {
  123. "model_path": "t5-small", # if model_path is not set, the default model is t5-small: https://huggingface.co/t5-small
  124. "output_dir": "data/output/", # setting the output directory
  125. "fp16": False,
  126. } # setting whether to use FP16
  127. }
  128. automl.fit(
  129. X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val, **automl_settings
  130. )
  131. ```
  132. #### Sample Output
  133. ```
  134. [flaml.automl: 12-20 11:44:03] {1965} INFO - task = summarization
  135. [flaml.automl: 12-20 11:44:03] {1967} INFO - Data split method: uniform
  136. [flaml.automl: 12-20 11:44:03] {1971} INFO - Evaluation method: holdout
  137. [flaml.automl: 12-20 11:44:03] {2063} INFO - Minimizing error metric: -rouge
  138. [flaml.automl: 12-20 11:44:03] {2115} INFO - List of ML learners in AutoML Run: ['transformer']
  139. [flaml.automl: 12-20 11:44:03] {2355} INFO - iteration 0, current learner transformer
  140. loading configuration file https://huggingface.co/t5-small/resolve/main/config.json from cache at /home/xliu127/.cache/huggingface/transformers/fe501e8fd6425b8ec93df37767fcce78ce626e34cc5edc859c662350cf712e41.406701565c0afd9899544c1cb8b93185a76f00b31e5ce7f6e18bbaef02241985
  141. Model config T5Config {
  142. "_name_or_path": "t5-small",
  143. "architectures": [
  144. "T5WithLMHeadModel"
  145. ],
  146. "d_ff": 2048,
  147. "d_kv": 64,
  148. "d_model": 512,
  149. "decoder_start_token_id": 0,
  150. "dropout_rate": 0.1,
  151. "eos_token_id": 1,
  152. "feed_forward_proj": "relu",
  153. "initializer_factor": 1.0,
  154. "is_encoder_decoder": true,
  155. "layer_norm_epsilon": 1e-06,
  156. "model_type": "t5",
  157. "n_positions": 512,
  158. "num_decoder_layers": 6,
  159. "num_heads": 8,
  160. "num_layers": 6,
  161. "output_past": true,
  162. "pad_token_id": 0,
  163. "relative_attention_num_buckets": 32,
  164. "task_specific_params": {
  165. "summarization": {
  166. "early_stopping": true,
  167. "length_penalty": 2.0,
  168. "max_length": 200,
  169. "min_length": 30,
  170. "no_repeat_ngram_size": 3,
  171. "num_beams": 4,
  172. "prefix": "summarize: "
  173. },
  174. "translation_en_to_de": {
  175. "early_stopping": true,
  176. "max_length": 300,
  177. "num_beams": 4,
  178. "prefix": "translate English to German: "
  179. },
  180. "translation_en_to_fr": {
  181. "early_stopping": true,
  182. "max_length": 300,
  183. "num_beams": 4,
  184. "prefix": "translate English to French: "
  185. },
  186. "translation_en_to_ro": {
  187. "early_stopping": true,
  188. "max_length": 300,
  189. "num_beams": 4,
  190. "prefix": "translate English to Romanian: "
  191. }
  192. },
  193. "transformers_version": "4.14.1",
  194. "use_cache": true,
  195. "vocab_size": 32128
  196. }
  197. ```
  198. ### A simple token classification example
  199. There are two ways to define the label for a token classification task. The first is to define the token labels:
  200. ```python
  201. from flaml import AutoML
  202. import pandas as pd
  203. train_dataset = {
  204. "id": ["0", "1"],
  205. "ner_tags": [
  206. ["B-ORG", "O", "B-MISC", "O", "O", "O", "B-MISC", "O", "O"],
  207. ["B-PER", "I-PER"],
  208. ],
  209. "tokens": [
  210. [
  211. "EU", "rejects", "German", "call", "to", "boycott", "British", "lamb", ".",
  212. ],
  213. ["Peter", "Blackburn"],
  214. ],
  215. }
  216. dev_dataset = {
  217. "id": ["0"],
  218. "ner_tags": [
  219. ["O"],
  220. ],
  221. "tokens": [
  222. ["1996-08-22"]
  223. ],
  224. }
  225. test_dataset = {
  226. "id": ["0"],
  227. "ner_tags": [
  228. ["O"],
  229. ],
  230. "tokens": [
  231. ['.']
  232. ],
  233. }
  234. custom_sent_keys = ["tokens"]
  235. label_key = "ner_tags"
  236. train_dataset = pd.DataFrame(train_dataset)
  237. dev_dataset = pd.DataFrame(dev_dataset)
  238. test_dataset = pd.DataFrame(test_dataset)
  239. X_train, y_train = train_dataset[custom_sent_keys], train_dataset[label_key]
  240. X_val, y_val = dev_dataset[custom_sent_keys], dev_dataset[label_key]
  241. X_test = test_dataset[custom_sent_keys]
  242. automl = AutoML()
  243. automl_settings = {
  244. "time_budget": 10,
  245. "task": "token-classification",
  246. "fit_kwargs_by_estimator": {
  247. "transformer":
  248. {
  249. "output_dir": "data/output/"
  250. # if model_path is not set, the default model is facebook/muppet-roberta-base: https://huggingface.co/facebook/muppet-roberta-base
  251. }
  252. }, # setting the huggingface arguments: output directory
  253. "gpu_per_trial": 1, # set to 0 if no GPU is available
  254. "metric": "seqeval:overall_f1"
  255. }
  256. automl.fit(X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val, **automl_settings)
  257. automl.predict(X_test)
  258. ```
  259. The second is to define the id labels + a token [label list](https://microsoft.github.io/FLAML/docs/reference/nlp/huggingface/training_args):
  260. ```python
  261. from flaml import AutoML
  262. import pandas as pd
  263. train_dataset = {
  264. "id": ["0", "1"],
  265. "ner_tags": [
  266. [3, 0, 7, 0, 0, 0, 7, 0, 0],
  267. [1, 2],
  268. ],
  269. "tokens": [
  270. [
  271. "EU", "rejects", "German", "call", "to", "boycott", "British", "lamb", ".",
  272. ],
  273. ["Peter", "Blackburn"],
  274. ],
  275. }
  276. dev_dataset = {
  277. "id": ["0"],
  278. "ner_tags": [
  279. [0],
  280. ],
  281. "tokens": [
  282. ["1996-08-22"]
  283. ],
  284. }
  285. test_dataset = {
  286. "id": ["0"],
  287. "ner_tags": [
  288. [0],
  289. ],
  290. "tokens": [
  291. ['.']
  292. ],
  293. }
  294. custom_sent_keys = ["tokens"]
  295. label_key = "ner_tags"
  296. train_dataset = pd.DataFrame(train_dataset)
  297. dev_dataset = pd.DataFrame(dev_dataset)
  298. test_dataset = pd.DataFrame(test_dataset)
  299. X_train, y_train = train_dataset[custom_sent_keys], train_dataset[label_key]
  300. X_val, y_val = dev_dataset[custom_sent_keys], dev_dataset[label_key]
  301. X_test = test_dataset[custom_sent_keys]
  302. automl = AutoML()
  303. automl_settings = {
  304. "time_budget": 10,
  305. "task": "token-classification",
  306. "fit_kwargs_by_estimator": {
  307. "transformer":
  308. {
  309. "output_dir": "data/output/",
  310. # if model_path is not set, the default model is facebook/muppet-roberta-base: https://huggingface.co/facebook/muppet-roberta-base
  311. "label_list": [ "O","B-PER", "I-PER", "B-ORG", "I-ORG", "B-LOC", "I-LOC", "B-MISC", "I-MISC" ]
  312. }
  313. }, # setting the huggingface arguments: output directory
  314. "gpu_per_trial": 1, # set to 0 if no GPU is available
  315. "metric": "seqeval:overall_f1"
  316. }
  317. automl.fit(X_train=X_train, y_train=y_train, X_val=X_val, y_val=y_val, **automl_settings)
  318. automl.predict(X_test)
  319. ```
  320. #### Sample Output
  321. ```
  322. [flaml.automl: 06-30 03:10:02] {2423} INFO - task = token-classification
  323. [flaml.automl: 06-30 03:10:02] {2425} INFO - Data split method: stratified
  324. [flaml.automl: 06-30 03:10:02] {2428} INFO - Evaluation method: holdout
  325. [flaml.automl: 06-30 03:10:02] {2497} INFO - Minimizing error metric: seqeval:overall_f1
  326. [flaml.automl: 06-30 03:10:02] {2637} INFO - List of ML learners in AutoML Run: ['transformer']
  327. [flaml.automl: 06-30 03:10:02] {2929} INFO - iteration 0, current learner transformer
  328. ```
  329. For tasks that are not currently supported, use `flaml.tune` for [customized tuning](Tune-HuggingFace).
  330. ### Link to Jupyter notebook
  331. To run more examples, especially examples using Ray Tune, please go to:
  332. [Link to notebook](https://github.com/microsoft/FLAML/blob/main/notebook/automl_nlp.ipynb) | [Open in colab](https://colab.research.google.com/github/microsoft/FLAML/blob/main/notebook/automl_nlp.ipynb)