Transformers documentation

Tóm tắt

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Tóm tắt

Summarization tạo ra một phiên bản ngắn hơn của một tài liệu hoặc bài báo, nắm bắt tất cả các thông tin quan trọng. Cùng với dịch thuật, đây là một ví dụ khác về tác vụ có thể được xây dựng dưới dạng tác vụ sequence-to-sequence. Summarization có thể là:

  • Extractive: trích xuất thông tin liên quan nhất từ một tài liệu.
  • Abstractive: tạo ra văn bản mới nắm bắt được thông tin liên quan nhất.

Hướng dẫn này sẽ cho bạn thấy cách:

  1. Tinh chỉnh T5 trên tập con hóa đơn bang California của bộ dữ liệu BillSum để tóm tắt trừu tượng.
  2. Sử dụng mô hình đã tinh chỉnh của bạn để suy luận.

Để xem tất cả các kiến trúc và checkpoint tương thích với tác vụ này, chúng tôi khuyến nghị bạn kiểm tra trang tác vụ

Trước khi bắt đầu, hãy đảm bảo bạn đã cài đặt tất cả các thư viện cần thiết:

pip install transformers datasets evaluate rouge_score

Chúng tôi khuyến khích bạn đăng nhập vào tài khoản Hugging Face của mình để có thể tải lên và chia sẻ mô hình của bạn với cộng đồng. Khi được yêu cầu, hãy nhập token của bạn để đăng nhập:

>>> from huggingface_hub import notebook_login

>>> notebook_login()

Tải bộ dữ liệu BillSum

Bắt đầu bằng cách tải tập con hóa đơn của bang California nhỏ hơn từ tập dữ liệu BillSum của thư viện 🤗 Datasets:

>>> from datasets import load_dataset

>>> billsum = load_dataset("FiscalNote/billsum", split="ca_test")

Chia bộ dữ liệu thành tập huấn luyện và tập kiểm tra bằng phương thức train_test_split:

>>> billsum = billsum.train_test_split(test_size=0.2)

Sau đó, hãy xem một ví dụ:

>>> billsum["train"][0]
{'summary': 'Existing law authorizes state agencies to enter into contracts for the acquisition of goods or services upon approval by the Department of General Services. Existing law sets forth various requirements and prohibitions for those contracts, including, but not limited to, a prohibition on entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between spouses and domestic partners or same-sex and different-sex couples in the provision of benefits. Existing law provides that a contract entered into in violation of those requirements and prohibitions is void and authorizes the state or any person acting on behalf of the state to bring a civil action seeking a determination that a contract is in violation and therefore void. Under existing law, a willful violation of those requirements and prohibitions is a misdemeanor.\nThis bill would also prohibit a state agency from entering into contracts for the acquisition of goods or services of $100,000 or more with a contractor that discriminates between employees on the basis of gender identity in the provision of benefits, as specified. By expanding the scope of a crime, this bill would impose a state-mandated local program.\nThe California Constitution requires the state to reimburse local agencies and school districts for certain costs mandated by the state. Statutory provisions establish procedures for making that reimbursement.\nThis bill would provide that no reimbursement is required by this act for a specified reason.',
 'text': 'The people of the State of California do enact as follows:\n\n\nSECTION 1.\nSection 10295.35 is added to the Public Contract Code, to read:\n10295.35.\n(a) (1) Notwithstanding any other law, a state agency shall not enter into any contract for the acquisition of goods or services in the amount of one hundred thousand dollars ($100,000) or more with a contractor that, in the provision of benefits, discriminates between employees on the basis of an employee’s or dependent’s actual or perceived gender identity, including, but not limited to, the employee’s or dependent’s identification as transgender.\n(2) For purposes of this section, “contract” includes contracts with a cumulative amount of one hundred thousand dollars ($100,000) or more per contractor in each fiscal year.\n(3) For purposes of this section, an employee health plan is discriminatory if the plan is not consistent with Section 1365.5 of the Health and Safety Code and Section 10140 of the Insurance Code.\n(4) The requirements of this section shall apply only to those portions of a contractor’s operations that occur under any of the following conditions:\n(A) Within the state.\n(B) On real property outside the state if the property is owned by the state or if the state has a right to occupy the property, and if the contractor’s presence at that location is connected to a contract with the state.\n(C) Elsewhere in the United States where work related to a state contract is being performed.\n(b) Contractors shall treat as confidential, to the maximum extent allowed by law or by the requirement of the contractor’s insurance provider, any request by an employee or applicant for employment benefits or any documentation of eligibility for benefits submitted by an employee or applicant for employment.\n(c) After taking all reasonable measures to find a contractor that complies with this section, as determined by the state agency, the requirements of this section may be waived under any of the following circumstances:\n(1) There is only one prospective contractor willing to enter into a specific contract with the state agency.\n(2) The contract is necessary to respond to an emergency, as determined by the state agency, that endangers the public health, welfare, or safety, or the contract is necessary for the provision of essential services, and no entity that complies with the requirements of this section capable of responding to the emergency is immediately available.\n(3) The requirements of this section violate, or are inconsistent with, the terms or conditions of a grant, subvention, or agreement, if the agency has made a good faith attempt to change the terms or conditions of any grant, subvention, or agreement to authorize application of this section.\n(4) The contractor is providing wholesale or bulk water, power, or natural gas, the conveyance or transmission of the same, or ancillary services, as required for ensuring reliable services in accordance with good utility practice, if the purchase of the same cannot practically be accomplished through the standard competitive bidding procedures and the contractor is not providing direct retail services to end users.\n(d) (1) A contractor shall not be deemed to discriminate in the provision of benefits if the contractor, in providing the benefits, pays the actual costs incurred in obtaining the benefit.\n(2) If a contractor is unable to provide a certain benefit, despite taking reasonable measures to do so, the contractor shall not be deemed to discriminate in the provision of benefits.\n(e) (1) Every contract subject to this chapter shall contain a statement by which the contractor certifies that the contractor is in compliance with this section.\n(2) The department or other contracting agency shall enforce this section pursuant to its existing enforcement powers.\n(3) (A) If a contractor falsely certifies that it is in compliance with this section, the contract with that contractor shall be subject to Article 9 (commencing with Section 10420), unless, within a time period specified by the department or other contracting agency, the contractor provides to the department or agency proof that it has complied, or is in the process of complying, with this section.\n(B) The application of the remedies or penalties contained in Article 9 (commencing with Section 10420) to a contract subject to this chapter shall not preclude the application of any existing remedies otherwise available to the department or other contracting agency under its existing enforcement powers.\n(f) Nothing in this section is intended to regulate the contracting practices of any local jurisdiction.\n(g) This section shall be construed so as not to conflict with applicable federal laws, rules, or regulations. In the event that a court or agency of competent jurisdiction holds that federal law, rule, or regulation invalidates any clause, sentence, paragraph, or section of this code or the application thereof to any person or circumstances, it is the intent of the state that the court or agency sever that clause, sentence, paragraph, or section so that the remainder of this section shall remain in effect.\nSEC. 2.\nSection 10295.35 of the Public Contract Code shall not be construed to create any new enforcement authority or responsibility in the Department of General Services or any other contracting agency.\nSEC. 3.\nNo reimbursement is required by this act pursuant to Section 6 of Article XIII\u2009B of the California Constitution because the only costs that may be incurred by a local agency or school district will be incurred because this act creates a new crime or infraction, eliminates a crime or infraction, or changes the penalty for a crime or infraction, within the meaning of Section 17556 of the Government Code, or changes the definition of a crime within the meaning of Section 6 of Article XIII\u2009B of the California Constitution.',
 'title': 'An act to add Section 10295.35 to the Public Contract Code, relating to public contracts.'}

Có hai trường mà bạn sẽ muốn sử dụng:

  • text: nội dung của hóa đơn, đây sẽ là đầu vào cho mô hình.
  • summary: một phiên bản rút gọn của text, sẽ là mục tiêu của mô hình.

Tiền xử lý

Bước tiếp theo là nạp một T5 tokenizer để xử lý text và summary:

>>> from transformers import AutoTokenizer

>>> checkpoint = "google-t5/t5-small"
>>> tokenizer = AutoTokenizer.from_pretrained(checkpoint)

Hàm tiền xử lý mà bạn muốn tạo cần phải:

  1. Thêm prompt vào đầu đầu vào để T5 biết đây là tác vụ tóm tắt. Một số mô hình có khả năng thực hiện nhiều tác vụ NLP khác nhau yêu cầu phải có prompt cho từng tác vụ cụ thể.
  2. Sử dụng đối số từ khóa text_target khi mã hóa nhãn.
  3. Cắt ngắn các chuỗi để không dài hơn độ dài tối đa được đặt bởi tham số max_length.
>>> prefix = "summarize: "


>>> def preprocess_function(examples):
...     inputs = [prefix + doc for doc in examples["text"]]
...     model_inputs = tokenizer(inputs, max_length=1024, truncation=True)

...     labels = tokenizer(text_target=examples["summary"], max_length=128, truncation=True)

...     model_inputs["labels"] = labels["input_ids"]
...     return model_inputs

Để áp dụng hàm tiền xử lý lên toàn bộ bộ dữ liệu, hãy sử dụng phương thức map của 🤗 Datasets. Bạn có thể tăng tốc hàm map bằng cách đặt batched=True để xử lý nhiều phần tử của bộ dữ liệu cùng lúc:

>>> tokenized_billsum = billsum.map(preprocess_function, batched=True)

Bây giờ hãy tạo một batch các ví dụ bằng cách sử dụng DataCollatorForSeq2Seq. Việc đệm động các câu đến độ dài dài nhất trong một batch trong quá trình collation sẽ hiệu quả hơn so với việc đệm toàn bộ dataset đến độ dài tối đa.

>>> from transformers import DataCollatorForSeq2Seq

>>> data_collator = DataCollatorForSeq2Seq(tokenizer=tokenizer, model=checkpoint)

Đánh giá

Việc đưa một chỉ số vào trong quá trình huấn luyện thường hữu ích để đánh giá hiệu suất của mô hình. Bạn có thể nhanh chóng tải một phương pháp đánh giá bằng thư viện 🤗 Evaluate. Đối với tác vụ này, hãy tải chỉ số ROUGE (xem quick tour của 🤗 Evaluate để tìm hiểu thêm về cách tải và tính toán một chỉ số):

>>> import evaluate

>>> rouge = evaluate.load("rouge")

Sau đó, tạo một hàm truyền các dự đoán và nhãn của bạn vào compute để tính toán chỉ số ROUGE:

>>> import numpy as np


>>> def compute_metrics(eval_pred):
...     predictions, labels = eval_pred
...     decoded_preds = tokenizer.batch_decode(predictions, skip_special_tokens=True)
...     labels = np.where(labels != -100, labels, tokenizer.pad_token_id)
...     decoded_labels = tokenizer.batch_decode(labels, skip_special_tokens=True)

...     result = rouge.compute(predictions=decoded_preds, references=decoded_labels, use_stemmer=True)

...     prediction_lens = [np.count_nonzero(pred != tokenizer.pad_token_id) for pred in predictions]
...     result["gen_len"] = np.mean(prediction_lens)

...     return {k: round(v, 4) for k, v in result.items()}

Hàm compute_metrics của bạn đã sẵn sàng, và bạn sẽ quay lại với nó khi thiết lập quá trình huấn luyện.

Huấn luyện

Nếu bạn chưa quen với việc tinh chỉnh mô hình bằng Trainer, hãy xem hướng dẫn cơ bản tại đây!

Bạn đã sẵn sàng để bắt đầu huấn luyện mô hình của mình! Tải T5 bằng AutoModelForSeq2SeqLM:

>>> from transformers import AutoModelForSeq2SeqLM, Seq2SeqTrainingArguments, Seq2SeqTrainer

>>> model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)

Tới bước này, chỉ còn ba bước nữa:

  1. Định nghĩa các siêu tham số huấn luyện của bạn trong Seq2SeqTrainingArguments. Tham số bắt buộc duy nhất là output_dir, chỉ định nơi lưu trữ mô hình của bạn. Bạn sẽ đẩy mô hình này lên Hub bằng cách đặt push_to_hub=True (bạn cần đăng nhập vào Hugging Face để tải lên mô hình). Vào cuối mỗi epoch, Trainer sẽ đánh giá chỉ số ROUGE và lưu checkpoint huấn luyện.
  2. Truyền các đối số huấn luyện vào Seq2SeqTrainer cùng với model, dataset, tokenizer, data collator và hàm compute_metrics.
  3. Gọi train() để tinh chỉnh mô hình của bạn.
>>> training_args = Seq2SeqTrainingArguments(
...     output_dir="my_awesome_billsum_model",
...     eval_strategy="epoch",
...     learning_rate=2e-5,
...     per_device_train_batch_size=16,
...     per_device_eval_batch_size=16,
...     weight_decay=0.01,
...     save_total_limit=3,
...     num_train_epochs=4,
...     predict_with_generate=True,
...     fp16=True, #change to bf16=True for XPU
...     push_to_hub=True,
... )

>>> trainer = Seq2SeqTrainer(
...     model=model,
...     args=training_args,
...     train_dataset=tokenized_billsum["train"],
...     eval_dataset=tokenized_billsum["test"],
...     processing_class=tokenizer,
...     data_collator=data_collator,
...     compute_metrics=compute_metrics,
... )

>>> trainer.train()

Khi quá trình huấn luyện hoàn tất, hãy chia sẻ mô hình của bạn lên Hub bằng phương thức push_to_hub() để mọi người có thể sử dụng mô hình của bạn:

>>> trainer.push_to_hub()

Để xem một ví dụ chi tiết hơn về cách tinh chỉnh mô hình cho tác vụ tóm tắt, hãy xem notebook PyTorch tương ứng.

Suy luận

Tuyệt, giờ đây bạn đã tinh chỉnh một mô hình, bạn có thể sử dụng nó để suy luận!

Hãy nghĩ ra một đoạn văn bản mà bạn muốn tóm tắt. Với T5, bạn cần thêm tiền tố cho đầu vào tùy thuộc vào tác vụ bạn đang thực hiện. Đối với tóm tắt, bạn nên thêm tiền tố cho đầu vào như minh họa bên dưới:

>>> text = "summarize: The Inflation Reduction Act lowers prescription drug costs, health care costs, and energy costs. It's the most aggressive action on tackling the climate crisis in American history, which will lift up American workers and create good-paying, union jobs across the country. It'll lower the deficit and ask the ultra-wealthy and corporations to pay their fair share. And no one making under $400,000 per year will pay a penny more in taxes."

Chia token văn bản và trả về input_ids dưới dạng tensor PyTorch:

>>> from transformers import AutoTokenizer

>>> tokenizer = AutoTokenizer.from_pretrained("username/my_awesome_billsum_model")
>>> inputs = tokenizer(text, return_tensors="pt").input_ids

Sử dụng phương thức generate() để tạo bản tóm tắt. Để biết thêm chi tiết về các chiến lược tạo văn bản khác nhau và các tham số để kiểm soát quá trình tạo, hãy xem API Text Generation.

>>> from transformers import AutoModelForSeq2SeqLM

>>> model = AutoModelForSeq2SeqLM.from_pretrained("username/my_awesome_billsum_model")
>>> outputs = model.generate(inputs, max_new_tokens=100, do_sample=False)

Giải mã các id token đã tạo thành văn bản:

>>> tokenizer.decode(outputs[0], skip_special_tokens=True)
'the inflation reduction act lowers prescription drug costs, health care costs, and energy costs. it's the most aggressive action on tackling the climate crisis in american history. it will ask the ultra-wealthy and corporations to pay their fair share.'
Update on GitHub