|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | +import random |
| 4 | +from collections import defaultdict |
| 5 | +from functools import partial |
| 6 | +from typing import Any |
| 7 | + |
| 8 | +import aiometer |
| 9 | +from datasets import Dataset as HFDataset |
| 10 | +from datasets import concatenate_datasets |
| 11 | + |
| 12 | +from autointent import Dataset |
| 13 | +from autointent.custom_types import Split |
| 14 | +from autointent.generation import Generator |
| 15 | +from autointent.generation.chat_templates._evolution_templates_schemas import Message, Role |
| 16 | +from autointent.schemas import Sample |
| 17 | + |
| 18 | +from .critic_human_like import CriticHumanLike |
| 19 | + |
| 20 | +logger = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class HumanUtteranceGenerator: |
| 24 | + """Generator of human-like utterances. |
| 25 | +
|
| 26 | + This class rewrites given user utterances to make them sound more natural and human-like, |
| 27 | + while preserving their original intent. The generation process is iterative and attempts |
| 28 | + to bypass a critic that identifies machine-generated text. |
| 29 | +
|
| 30 | + .. warning:: This method is experimental and can yield inferior data quality. |
| 31 | +
|
| 32 | + """ |
| 33 | + |
| 34 | + def __init__( |
| 35 | + self, |
| 36 | + generator: Generator, |
| 37 | + critic: CriticHumanLike, |
| 38 | + async_mode: bool = False, |
| 39 | + max_at_once: int = 5, |
| 40 | + max_per_second: int = 10, |
| 41 | + ) -> None: |
| 42 | + """Initialize the HumanUtteranceGeneratoror. |
| 43 | +
|
| 44 | + Args: |
| 45 | + generator: Wrapper for the LLM API used to generate utterances. |
| 46 | + critic: Critic to determine whether the generated utterance sounds human-like. |
| 47 | + async_mode: Whether to use asynchronous mode for generation. |
| 48 | + max_at_once: Maximum number of concurrent async tasks. |
| 49 | + max_per_second: Maximum number of tasks per second. |
| 50 | + """ |
| 51 | + self.generator = generator |
| 52 | + self.critic = critic |
| 53 | + self.async_mode = async_mode |
| 54 | + self.max_at_once = max_at_once |
| 55 | + self.max_per_second = max_per_second |
| 56 | + |
| 57 | + def augment( |
| 58 | + self, dataset: Dataset, split_name: str = Split.TRAIN, update_split: bool = True, n_final_per_class: int = 5 |
| 59 | + ) -> list[Sample]: |
| 60 | + """Generate human-like utterances for each intent by iteratively refining machine-generated candidates. |
| 61 | +
|
| 62 | + Args: |
| 63 | + dataset: The dataset to augment. |
| 64 | + split_name: The name of the split to augment (e.g., 'train'). |
| 65 | + update_split: Whether to update the dataset split with the new utterances. |
| 66 | + n_final_per_class: Number of successful utterances to generate per intent. |
| 67 | +
|
| 68 | + Returns: |
| 69 | + list[Sample]: List of newly generated samples. |
| 70 | + """ |
| 71 | + if self.async_mode: |
| 72 | + return asyncio.run( |
| 73 | + self.augment_async( |
| 74 | + dataset=dataset, |
| 75 | + split_name=split_name, |
| 76 | + update_split=update_split, |
| 77 | + n_final_per_class=n_final_per_class, |
| 78 | + ) |
| 79 | + ) |
| 80 | + original_split = dataset[split_name] |
| 81 | + id_to_name = {intent.id: intent.name for intent in dataset.intents} |
| 82 | + new_samples = [] |
| 83 | + |
| 84 | + class_to_samples = defaultdict(list) |
| 85 | + for sample in original_split: |
| 86 | + class_to_samples[sample["label"]].append(sample["utterance"]) |
| 87 | + |
| 88 | + for intent_id, intent_name in id_to_name.items(): |
| 89 | + if intent_name is None: |
| 90 | + logger.warning("Intent with id %s has no name! Skipping it...", intent_id) |
| 91 | + continue |
| 92 | + generated_count = 0 |
| 93 | + attempt = 0 |
| 94 | + |
| 95 | + seed_utterances = class_to_samples.get(intent_id, []) |
| 96 | + if not seed_utterances: |
| 97 | + continue |
| 98 | + |
| 99 | + while generated_count < n_final_per_class and attempt < n_final_per_class * 3: |
| 100 | + attempt += 1 |
| 101 | + n_seeds = min(3, len(seed_utterances)) |
| 102 | + seed_examples = random.sample(seed_utterances, k=n_seeds) |
| 103 | + rejected: list[str] = [] |
| 104 | + |
| 105 | + for _ in range(3): |
| 106 | + prompt = self._build_adversarial_prompt(intent_name, seed_examples, rejected) |
| 107 | + generated = self.generator.get_chat_completion([prompt]).strip() |
| 108 | + if self.critic.is_human(generated, intent_name): |
| 109 | + new_samples.append({Dataset.label_feature: intent_id, Dataset.utterance_feature: generated}) |
| 110 | + generated_count += 1 |
| 111 | + break |
| 112 | + rejected.append(generated) |
| 113 | + if update_split: |
| 114 | + generated_split = HFDataset.from_list(new_samples) |
| 115 | + dataset[split_name] = concatenate_datasets([original_split, generated_split]) |
| 116 | + |
| 117 | + return [Sample(**sample) for sample in new_samples] |
| 118 | + |
| 119 | + async def augment_async( |
| 120 | + self, dataset: Dataset, split_name: str = Split.TRAIN, update_split: bool = True, n_final_per_class: int = 5 |
| 121 | + ) -> list[Sample]: |
| 122 | + original_split = dataset[split_name] |
| 123 | + id_to_name = {intent.id: intent.name for intent in dataset.intents} |
| 124 | + new_samples = [] |
| 125 | + |
| 126 | + class_to_samples = defaultdict(list) |
| 127 | + for sample in original_split: |
| 128 | + class_to_samples[sample["label"]].append(sample["utterance"]) |
| 129 | + |
| 130 | + async def generate_one(intent_id: str, intent_name: str) -> list[dict[str, Any]]: |
| 131 | + generated: list[dict[str, Any]] = [] |
| 132 | + attempts = 0 |
| 133 | + seed_utterances = class_to_samples[intent_id] |
| 134 | + while len(generated) < n_final_per_class and attempts < n_final_per_class * 3: |
| 135 | + attempts += 1 |
| 136 | + seed_examples = random.sample(seed_utterances, k=min(3, len(seed_utterances))) |
| 137 | + rejected: list[str] = [] |
| 138 | + |
| 139 | + for _ in range(3): |
| 140 | + prompt = self._build_adversarial_prompt(intent_name, seed_examples, rejected) |
| 141 | + utterance = (await self.generator.get_chat_completion_async([prompt])).strip() |
| 142 | + if await self.critic.is_human_async(utterance, intent_name): |
| 143 | + generated.append({Dataset.label_feature: int(intent_id), Dataset.utterance_feature: utterance}) |
| 144 | + break |
| 145 | + rejected.append(utterance) |
| 146 | + return generated |
| 147 | + |
| 148 | + tasks = [ |
| 149 | + partial(generate_one, str(intent_id), intent_name) |
| 150 | + for intent_id, intent_name in id_to_name.items() |
| 151 | + if class_to_samples.get(intent_id) and intent_name is not None |
| 152 | + ] |
| 153 | + |
| 154 | + results = await aiometer.run_all( |
| 155 | + tasks, |
| 156 | + max_at_once=self.max_at_once, |
| 157 | + max_per_second=self.max_per_second, |
| 158 | + ) |
| 159 | + |
| 160 | + for result in results: |
| 161 | + new_samples.extend(result) |
| 162 | + if update_split: |
| 163 | + generated_split = HFDataset.from_list(new_samples) |
| 164 | + dataset[split_name] = concatenate_datasets([original_split, generated_split]) |
| 165 | + |
| 166 | + return [Sample(**sample) for sample in new_samples] |
| 167 | + |
| 168 | + def _build_adversarial_prompt(self, intent_name: str, seed_examples: list[str], rejected: list[str]) -> Message: |
| 169 | + """Build a few-shot prompt. |
| 170 | +
|
| 171 | + Build a few-shot prompt to guide the generator to create a new human-like utterance |
| 172 | + from scratch based on the intent name and example utterances. |
| 173 | +
|
| 174 | + Args: |
| 175 | + intent_name: The intent of the utterance. |
| 176 | + seed_examples: List of 1-3 example utterances for the intent. |
| 177 | + rejected: List of previously rejected generations. |
| 178 | +
|
| 179 | + Returns: |
| 180 | + Message: A formatted prompt instructing the generator to produce a new natural-sounding utterance.. |
| 181 | + """ |
| 182 | + rejected_block = "\n".join(f"- {r}" for r in rejected) if rejected else "None" |
| 183 | + examples_block = "\n".join(f'- "{ex}"' for ex in seed_examples) |
| 184 | + content = ( |
| 185 | + f"Your task is to generate a new user utterance that fits the intent '{intent_name}'.\n\n" |
| 186 | + "Here are some examples of utterances for this intent:\n" |
| 187 | + f"{examples_block}\n\n" |
| 188 | + "Preserving its original intent: " |
| 189 | + f"'{intent_name}'.\n\n" |
| 190 | + f"The following previous attempts were classified as machine-generated and rejected:\n{rejected_block}\n\n" |
| 191 | + "Try to write something that would pass as written by a real human. Output a single version only.\n" |
| 192 | + "IMPORTANT: You must modify the original utterance." |
| 193 | + ) |
| 194 | + return Message(role=Role.USER, content=content) |
0 commit comments