Spaces:
Runtime error
Runtime error
Commit ·
5dcfc82
1
Parent(s): a7fd3ba
Enrich augmentation with different QA variants. Ensure Vnmese output, add graceful fallback
Browse filesFiles changed (5)
- app.py+2-1
- utils/augment.py+49
- utils/processor.py+120-10
- utils/rag.py+24-5
- vi/processing.py+44-4
407 unmodified lines408409410411412413414407 unmodified linessample_limit=params.sample_limit,seed=params.seed,progress_cb=lambda p, msg=None: set_state(progress=p, message=msg or STATE["message"]),translator=translator)else:# Standard SFT processing mode407 unmodified lines408409410411412413414415407 unmodified linessample_limit=params.sample_limit,seed=params.seed,progress_cb=lambda p, msg=None: set_state(progress=p, message=msg or STATE["message"]),translator=translator,paraphraser=paraphraser)else:# Standard SFT processing mode
117 unmodified lines118119120117 unmodified linesif random.random() >= ratio:return Truereturn paraphraser.consistency_check(user, out)117 unmodified lines118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169117 unmodified linesif random.random() >= ratio:return Truereturn paraphraser.consistency_check(user, out)def is_invalid_response(text: str) -> bool:"""Check if model response is invalid (Fail, Invalid, etc.)"""if not text or not isinstance(text, str):return Truetext_lower = text.lower().strip()invalid_patterns = ["fail", "invalid", "i couldn't", "i can't", "i cannot", "unable to","sorry", "error", "not available", "no answer", "insufficient","don't know", "do not know", "not sure", "cannot determine","unable to provide", "not possible", "not applicable", "n/a"]# Check if response is too short or matches invalid patternsif len(text_lower) < 3:return Truefor pattern in invalid_patterns:if pattern in text_lower:return Truereturn Falsedef clean_invalid_response(text: str, fallback: str = "") -> str:"""Clean invalid responses by returning fallback or empty string"""if is_invalid_response(text):return fallbackreturn textdef retry_invalid_response(text: str, paraphraser, max_retries: int = 3) -> str:"""Retry generating valid response for invalid text, max 3 retries"""if not is_invalid_response(text):return textfor attempt in range(max_retries):try:# Try paraphrasing with different difficulty levelsdifficulty = "easy" if attempt == 0 else "hard" if attempt == 1 else "easy"retry_text = paraphraser.paraphrase(text, difficulty=difficulty)if retry_text and not is_invalid_response(retry_text):return retry_textexcept Exception as e:logger.warning(f"Retry attempt {attempt + 1} failed: {e}")continue# If all retries failed, return empty string to indicate dropreturn ""
112 unmodified lines1131141151161171187 unmodified lines12612712812913013156 unmodified lines1881891901911921931 unmodified line19519619719819920020120220320420520640 unmodified lines24724824925025125225325425525625744 unmodified lines30230330430530630730830931031183 unmodified lines395396397398399400401402403404405406112 unmodified linesvariants.append((u3, o3, applied))return variantsdef _apply_aug(instr: str, user: str, out: str, source: str, opts: Dict, paraphraser, stats: Dict):# Base cleanup & caps (returns cleaned strings)user = A.base_cleanup(user, opts.get("max_chars", 5000), opts.get("deidentify", True))7 unmodified lines# Stack list of entries that has been applied augmentation and stylingsapplied = []# Style standardizing the answerif opts.get("style_standardize", True):out = A.style_standardize_answer(out)56 unmodified linestry:instr, user, out, applied = _apply_aug(instr, user, out, source, opts, paraphraser, stats)# 1) ALWAYS write the original (cleaned/style-standardised only)# Optional consistency spot-check (cheap)if not A.consistency_ok(user, out, opts.get("consistency_check_ratio", 0.0), paraphraser):1 unmodified line# keep the sample but tag itapplied.append("consistency_flag")# 2) If expansion is enabled, add augmented copies_commit_row(writer, source, rid, "medical_dialogue", instr, user, out, opts, stats, ["base"] + applied, dedupe_seen=dedupe_seen, translator=translator)# Add augmented copies if expandif opts.get("expand", True):for (u_aug, o_aug, aug_tags) in _build_variants(user, out, paraphraser, opts, stats):rid_aug = f"{rid}-aug{random.randint(1000,9999)}"_commit_row(writer, source, rid_aug, "medical_dialogue", instr, u_aug, o_aug, opts, stats, aug_tags, dedupe_seen=dedupe_seen, translator=translator)# Increment count only on success40 unmodified linesrid = str(k)instr, user, out, applied = _apply_aug(instr, user, out, "pubmedqa_l", opts, paraphraser, stats)_commit_row(writer, "pubmedqa_l", rid, "biomedical_qa", instr, user, out, opts, stats, applied,extra_meta={"year": v.get("YEAR"), "meshes": v.get("MESHES"), "labels": v.get("LABELS")}, dedupe_seen=dedupe_seen, translator=translator)if opts.get("expand", True):for (u_aug, o_aug, aug_tags) in _build_variants(user, out, paraphraser, opts, stats):rid_aug = f"{rid}-aug{random.randint(1000,9999)}"_commit_row(writer, "pubmedqa_l", rid_aug, "biomedical_qa",instr, u_aug, o_aug, opts, stats, aug_tags, dedupe_seen=dedupe_seen, translator=translator)44 unmodified linesout = guess.strip()instr, user, out, applied = _apply_aug(instr, user, out, "pubmedqa_u", opts, paraphraser, stats)_commit_row(writer, "pubmedqa_u", str(k), "biomedical_qa_unlabeled", instr, user, out, opts, stats, applied, dedupe_seen=dedupe_seen, translator=translator)if opts.get("expand", True):for (u_aug, o_aug, aug_tags) in _build_variants(user, out, paraphraser, opts, stats):rid_aug = f"{rid}-aug{random.randint(1000,9999)}"_commit_row(writer, "pubmedqa_u", rid_aug, "biomedical_qa",instr, u_aug, o_aug, opts, stats, aug_tags, dedupe_seen=dedupe_seen, translator=translator)83 unmodified lines# Process the iteminstr, user, out, applied = _apply_aug(instr, user, out, "pubmedqa_map", opts, paraphraser, stats)_commit_row(writer, "pubmedqa_map", rid, "biomedical_qa", instr, user, out, opts, stats, applied, dedupe_seen=dedupe_seen, translator=translator)# Handle expansion if enabledif opts.get("expand", True):for (u_aug, o_aug, aug_tags) in _build_variants(user, out, paraphraser, opts, stats):rid_aug = f"{rid}-aug{random.randint(1000,9999)}"_commit_row(writer, "pubmedqa_map", rid_aug, "biomedical_qa",instr, u_aug, o_aug, opts, stats, aug_tags, dedupe_seen=dedupe_seen, translator=translator)112 unmodified lines1131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881897 unmodified lines19719819920020120220320420520620720820956 unmodified lines2662672682692702712722732742752761 unmodified line27827928028128228328428528628728828929029129240 unmodified lines33333433533633733833934034134234334434534634734834935035144 unmodified lines39639739839940040140240340440540640740840941041141241383 unmodified lines497498499500501502503504505506507508509510511512513514515516112 unmodified linesvariants.append((u3, o3, applied))return variantsdef _build_enriched_variants(user: str, out: str, paraphraser, opts: Dict, stats: Dict, translator=None):"""Build multiple paraphrased variants for SFT enrichment (2-3 answers per question, 2-3 questions per answer)"""variants = []# Generate 2-3 different answers for the same questionanswer_variants = []for i in range(3):if i == 0:# Original answeranswer_variants.append((out, ["original_answer"]))else:# Paraphrased answers with different difficultiesdifficulty = "easy" if i == 1 else "hard"try:paraphrased_out = paraphraser.paraphrase(out, difficulty=difficulty)if paraphrased_out and not A.is_invalid_response(paraphrased_out):if opts.get("style_standardize", True):paraphrased_out = A.style_standardize_answer(paraphrased_out)paraphrased_out = A.ensure_terminal_punct(paraphrased_out)answer_variants.append((paraphrased_out, [f"paraphrase_answer_{difficulty}"]))stats["paraphrased_output"] += 1except Exception as e:logger.warning(f"Failed to paraphrase answer variant {i}: {e}")continue# Generate 2-3 different questions for the same answerquestion_variants = []for i in range(3):if i == 0:# Original questionquestion_variants.append((user, ["original_question"]))else:# Paraphrased questions with different difficultiesdifficulty = "easy" if i == 1 else "hard"try:paraphrased_user = paraphraser.paraphrase(user, difficulty=difficulty)if paraphrased_user and not A.is_invalid_response(paraphrased_user):paraphrased_user = A.ensure_terminal_punct(paraphrased_user)question_variants.append((paraphrased_user, [f"paraphrase_question_{difficulty}"]))stats["paraphrased_input"] += 1except Exception as e:logger.warning(f"Failed to paraphrase question variant {i}: {e}")continue# Create combinations: each question variant with each answer variantfor q_user, q_tags in question_variants:for a_out, a_tags in answer_variants:combined_tags = q_tags + a_tagsvariants.append((q_user, a_out, combined_tags))# Add Vietnamese variants if translator is availableif translator and translator.is_loaded():vi_variants = []for q_user, a_out, tags in variants[:3]: # Limit to first 3 to avoid too many variantstry:# Translate question and answervi_q = translator.translate_text(q_user)vi_a = translator.translate_text(a_out)if vi_q and vi_a and not A.is_invalid_response(vi_q) and not A.is_invalid_response(vi_a):vi_tags = tags + ["vietnamese_translated"]vi_variants.append((vi_q, vi_a, vi_tags))stats["vietnamese_variants"] = stats.get("vietnamese_variants", 0) + 1except Exception as e:logger.warning(f"Failed to create Vietnamese variant: {e}")continuevariants.extend(vi_variants)return variantsdef _apply_aug(instr: str, user: str, out: str, source: str, opts: Dict, paraphraser, stats: Dict):# Base cleanup & caps (returns cleaned strings)user = A.base_cleanup(user, opts.get("max_chars", 5000), opts.get("deidentify", True))7 unmodified lines# Stack list of entries that has been applied augmentation and stylingsapplied = []# Clean invalid responses with retry logicif A.is_invalid_response(out):out = A.retry_invalid_response(out, paraphraser, max_retries=3)if not out: # If retry failed, return empty to indicate dropreturn instr, user, "", appliedapplied.append("invalid_response_retried")# Style standardizing the answerif opts.get("style_standardize", True):out = A.style_standardize_answer(out)56 unmodified linestry:instr, user, out, applied = _apply_aug(instr, user, out, source, opts, paraphraser, stats)# Skip if retry failed (empty output)if not out:stats["dropped_invalid"] = stats.get("dropped_invalid", 0) + 1continue# 1) ALWAYS write the original (cleaned/style-standardised only)# Optional consistency spot-check (cheap)if not A.consistency_ok(user, out, opts.get("consistency_check_ratio", 0.0), paraphraser):1 unmodified line# keep the sample but tag itapplied.append("consistency_flag")# 2) If expansion is enabled, add enriched variants for SFT_commit_row(writer, source, rid, "medical_dialogue", instr, user, out, opts, stats, ["base"] + applied, dedupe_seen=dedupe_seen, translator=translator)# Add enriched variants if expand is enabledif opts.get("expand", True):# Use enriched variants for SFT (multiple Q&A combinations)enriched_variants = _build_enriched_variants(user, out, paraphraser, opts, stats, translator)for (u_aug, o_aug, aug_tags) in enriched_variants:rid_aug = f"{rid}-enriched{random.randint(1000,9999)}"_commit_row(writer, source, rid_aug, "medical_dialogue", instr, u_aug, o_aug, opts, stats, aug_tags, dedupe_seen=dedupe_seen, translator=translator)# Increment count only on success40 unmodified linesrid = str(k)instr, user, out, applied = _apply_aug(instr, user, out, "pubmedqa_l", opts, paraphraser, stats)# Skip if retry failed (empty output)if not out:stats["dropped_invalid"] = stats.get("dropped_invalid", 0) + 1continue_commit_row(writer, "pubmedqa_l", rid, "biomedical_qa", instr, user, out, opts, stats, applied,extra_meta={"year": v.get("YEAR"), "meshes": v.get("MESHES"), "labels": v.get("LABELS")}, dedupe_seen=dedupe_seen, translator=translator)if opts.get("expand", True):# Use enriched variants for SFT (multiple Q&A combinations)enriched_variants = _build_enriched_variants(user, out, paraphraser, opts, stats, translator)for (u_aug, o_aug, aug_tags) in enriched_variants:rid_aug = f"{rid}-enriched{random.randint(1000,9999)}"_commit_row(writer, "pubmedqa_l", rid_aug, "biomedical_qa",instr, u_aug, o_aug, opts, stats, aug_tags, dedupe_seen=dedupe_seen, translator=translator)44 unmodified linesout = guess.strip()instr, user, out, applied = _apply_aug(instr, user, out, "pubmedqa_u", opts, paraphraser, stats)# Skip if retry failed (empty output)if not out:stats["dropped_invalid"] = stats.get("dropped_invalid", 0) + 1continue_commit_row(writer, "pubmedqa_u", str(k), "biomedical_qa_unlabeled", instr, user, out, opts, stats, applied, dedupe_seen=dedupe_seen, translator=translator)if opts.get("expand", True):# Use enriched variants for SFT (multiple Q&A combinations)enriched_variants = _build_enriched_variants(user, out, paraphraser, opts, stats, translator)for (u_aug, o_aug, aug_tags) in enriched_variants:rid_aug = f"{rid}-enriched{random.randint(1000,9999)}"_commit_row(writer, "pubmedqa_u", rid_aug, "biomedical_qa",instr, u_aug, o_aug, opts, stats, aug_tags, dedupe_seen=dedupe_seen, translator=translator)83 unmodified lines# Process the iteminstr, user, out, applied = _apply_aug(instr, user, out, "pubmedqa_map", opts, paraphraser, stats)# Skip if retry failed (empty output)if not out:stats["dropped_invalid"] = stats.get("dropped_invalid", 0) + 1continue_commit_row(writer, "pubmedqa_map", rid, "biomedical_qa", instr, user, out, opts, stats, applied, dedupe_seen=dedupe_seen, translator=translator)# Handle expansion if enabledif opts.get("expand", True):# Use enriched variants for SFT (multiple Q&A combinations)enriched_variants = _build_enriched_variants(user, out, paraphraser, opts, stats, translator)for (u_aug, o_aug, aug_tags) in enriched_variants:rid_aug = f"{rid}-enriched{random.randint(1000,9999)}"_commit_row(writer, "pubmedqa_map", rid_aug, "biomedical_qa",instr, u_aug, o_aug, opts, stats, aug_tags, dedupe_seen=dedupe_seen, translator=translator)
6 unmodified lines78910111213176 unmodified lines19019119219319419550 unmodified lines24624724824925025137 unmodified lines2892902912922932942952962979 unmodified lines3073083093103113123136 unmodified linesfrom utils.schema import sft_row, rag_rowfrom utils.llm import NvidiaClient, KeyRotatorfrom vi.processing import should_translate# Loggerlogger = logging.getLogger("rag_processor")176 unmodified lines# Convert to QCA formatquestion, context, answer = self.convert_to_qca_format(instr, user, out)if not question or not answer:continue50 unmodified linescontext = self.clean_conversational_content(context)answer = self.clean_conversational_content(answer)# Generate context if missingif not context:context = self.generate_context_from_qa(question, answer)37 unmodified lines# Apply Vietnamese translation if requested (translate Q/A/C fields directly)if should_translate(opts.get("vietnamese_translation", False) if opts else False, translator):try:if translator:row = translator.translate_dict(row, ["question", "answer", "context"])row["vi_translated"] = Trueexcept Exception as e:logger.error(f"Failed to translate RAG row: {e}")9 unmodified linessample_limit: Optional[int],seed: int,progress_cb: Optional[Callable[[float, str], None]],translator=None) -> Tuple[int, Dict]:"""Main entry point for RAG processing"""random.seed(seed)6 unmodified lines7891011121314176 unmodified lines19119219319419519619719819920020120220320420550 unmodified lines25625725825926026126226326426526626726826927037 unmodified lines3083093103113123133143159 unmodified lines3253263273283293303313326 unmodified linesfrom utils.schema import sft_row, rag_rowfrom utils.llm import NvidiaClient, KeyRotatorfrom vi.processing import should_translate, translate_rag_rowfrom utils import augment as A# Loggerlogger = logging.getLogger("rag_processor")176 unmodified lines# Convert to QCA formatquestion, context, answer = self.convert_to_qca_format(instr, user, out)# Clean invalid responses with retry logicif A.is_invalid_response(answer):if paraphraser:answer = A.retry_invalid_response(answer, paraphraser, max_retries=3)else:answer = A.clean_invalid_response(answer, "")if not answer: # If retry failed, skip this samplecontinueif not question or not answer:continue50 unmodified linescontext = self.clean_conversational_content(context)answer = self.clean_conversational_content(answer)# Clean invalid responses with retry logicif A.is_invalid_response(answer):if paraphraser:answer = A.retry_invalid_response(answer, paraphraser, max_retries=3)else:answer = A.clean_invalid_response(answer, "")if not answer: # If retry failed, skip this samplecontinue# Generate context if missingif not context:context = self.generate_context_from_qa(question, answer)37 unmodified lines# Apply Vietnamese translation if requested (translate Q/A/C fields directly)if should_translate(opts.get("vietnamese_translation", False) if opts else False, translator):try:row = translate_rag_row(row, translator, ["question", "answer", "context"])row["vi_translated"] = Trueexcept Exception as e:logger.error(f"Failed to translate RAG row: {e}")9 unmodified linessample_limit: Optional[int],seed: int,progress_cb: Optional[Callable[[float, str], None]],translator=None,paraphraser=None) -> Tuple[int, Dict]:"""Main entry point for RAG processing"""random.seed(seed)
30 unmodified lines31323334353616 unmodified lines5354555657585960616222 unmodified lines8586878889909192939430 unmodified linest = " ".join(filtered)return tdef translate_sft_row(row: Dict[str, Any], translator, text_fields: List[str] = None) -> Dict[str, Any]:"""Translate specific text fields in an SFT row from English to Vietnamese.16 unmodified linestry:translated_row = translator.translate_dict(row, text_fields)# Sanitize translated fieldsfor f in text_fields:if f in translated_row.get("sft", {}):translated_row["sft"][f] = _vi_sanitize_text(translated_row["sft"][f])logger.debug(f"Translated SFT row with fields: {text_fields}")return translated_rowexcept Exception as e:22 unmodified linestry:translated_row = translator.translate_dict(row, text_fields)# Sanitize translated fieldsfor f in text_fields:if f in translated_row:translated_row[f] = _vi_sanitize_text(translated_row[f])logger.debug(f"Translated RAG row with fields: {text_fields}")return translated_rowexcept Exception as e:30 unmodified lines3132333435363738394041424344454647484950515253545556575859606162636416 unmodified lines8182838485868788899091929394959622 unmodified lines11912012112212312412512612712812913013113213313430 unmodified linest = " ".join(filtered)return tdef _validate_vi_translation(original: str, translated: str) -> bool:"""Validate Vietnamese translation quality"""if not translated or not isinstance(translated, str):return False# Check if translation is too short or too different in lengthif len(translated.strip()) < 3:return False# Check if translation contains too much English (should be mostly Vietnamese)import reenglish_chars = len(re.findall(r'[a-zA-Z]', translated))total_chars = len(re.sub(r'\s', '', translated))if total_chars > 0 and english_chars / total_chars > 0.7:return False# Check for common translation failure patternsfailure_patterns = ["translation", "error", "failed", "unable", "cannot","not available", "not found", "invalid", "error"]translated_lower = translated.lower()for pattern in failure_patterns:if pattern in translated_lower:return Falsereturn Truedef translate_sft_row(row: Dict[str, Any], translator, text_fields: List[str] = None) -> Dict[str, Any]:"""Translate specific text fields in an SFT row from English to Vietnamese.16 unmodified linestry:translated_row = translator.translate_dict(row, text_fields)# Validate and sanitize translated fieldsfor f in text_fields:if f in translated_row.get("sft", {}):original = row.get("sft", {}).get(f, "")translated = translated_row["sft"][f]if _validate_vi_translation(original, translated):translated_row["sft"][f] = _vi_sanitize_text(translated)else:logger.warning(f"Invalid Vietnamese translation for field {f}, keeping original")translated_row["sft"][f] = originallogger.debug(f"Translated SFT row with fields: {text_fields}")return translated_rowexcept Exception as e:22 unmodified linestry:translated_row = translator.translate_dict(row, text_fields)# Validate and sanitize translated fieldsfor f in text_fields:if f in translated_row:original = row.get(f, "")translated = translated_row[f]if _validate_vi_translation(original, translated):translated_row[f] = _vi_sanitize_text(translated)else:logger.warning(f"Invalid Vietnamese translation for field {f}, keeping original")translated_row[f] = originallogger.debug(f"Translated RAG row with fields: {text_fields}")return translated_rowexcept Exception as e:
app.py+2-1
utils/augment.py+49
utils/processor.py+120-10
utils/rag.py+24-5
vi/processing.py+44-4