Text Generation
PEFT
Safetensors
Chinese
qwen3
lora
dialogue-act-planning
psychological-counseling
conversational
Instructions to use UEC-InabaLab/CounselTraj with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use UEC-InabaLab/CounselTraj with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-8B") model = PeftModel.from_pretrained(base_model, "UEC-InabaLab/CounselTraj") - Notebooks
- Google Colab
- Kaggle
Release CounselTraj DA trajectory planner (Qwen3-8B LoRA)
Browse files- .gitattributes +1 -0
- README.md +124 -0
- SHA256SUMS +17 -0
- adapter_config.json +42 -0
- adapter_model.safetensors +3 -0
- added_tokens.json +28 -0
- chat_template.jinja +89 -0
- da_stats.json +0 -0
- examples/input.jsonl +1 -0
- examples/trajectory.json +49 -0
- merges.txt +0 -0
- model_details.json +21 -0
- plan_trajectory.py +929 -0
- requirements.txt +7 -0
- special_tokens_map.json +31 -0
- tokenizer.json +3 -0
- tokenizer_config.json +239 -0
- validation.json +22 -0
- vocab.json +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language:
|
| 3 |
+
- zh
|
| 4 |
+
base_model: Qwen/Qwen3-8B
|
| 5 |
+
base_model_relation: finetune
|
| 6 |
+
library_name: peft
|
| 7 |
+
pipeline_tag: text-generation
|
| 8 |
+
tags:
|
| 9 |
+
- qwen3
|
| 10 |
+
- lora
|
| 11 |
+
- dialogue-act-planning
|
| 12 |
+
- psychological-counseling
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# CounselTraj-DA
|
| 16 |
+
|
| 17 |
+
CounselTraj-DA is the dialogue-act trajectory planning model used in CounselTraj.
|
| 18 |
+
Given a brief counseling dialogue, the planner produces an ordered trajectory
|
| 19 |
+
of role-tagged acts such as `counselor:[OpenQuestion]` and
|
| 20 |
+
`client:[SelfDisclosure]` for subsequent dialogue synthesis.
|
| 21 |
+
|
| 22 |
+
This repository contains a **LoRA adapter for
|
| 23 |
+
[Qwen/Qwen3-8B](https://huggingface.co/Qwen/Qwen3-8B)**, together with its tokenizer,
|
| 24 |
+
the trajectory planning script, and aggregate dialogue-act priors. Loading the
|
| 25 |
+
adapter also requires the Qwen3-8B base model. Its base model is distributed under
|
| 26 |
+
Apache-2.0.
|
| 27 |
+
|
| 28 |
+
Project and dataset: [UEC-InabaLab/CounselTraj](https://github.com/UEC-InabaLab/CounselTraj).
|
| 29 |
+
|
| 30 |
+
## Model details
|
| 31 |
+
|
| 32 |
+
| Item | Value |
|
| 33 |
+
| --- | --- |
|
| 34 |
+
| Base model | Qwen/Qwen3-8B |
|
| 35 |
+
| Adapter | LoRA, rank 8, alpha 16, dropout 0.05 |
|
| 36 |
+
| Target modules | q_proj, k_proj, v_proj, o_proj, gate_proj, up_proj, down_proj |
|
| 37 |
+
| Adapter parameters | 21,823,488 |
|
| 38 |
+
| Selected checkpoint | checkpoint-145, epoch 5 |
|
| 39 |
+
| Selection criterion | Lowest recorded validation loss, 1.1678476334 |
|
| 40 |
+
| Learning rate / warmup ratio | 0.0002 / 0.03 |
|
| 41 |
+
| Planner | Content-conditioned v4 constrained decoding |
|
| 42 |
+
| Default trajectory length budget | 64–92 dialogue acts |
|
| 43 |
+
|
| 44 |
+
The released adapter is byte-identical to both the selected checkpoint and the
|
| 45 |
+
saved final model. Training uses dialogue-act annotations of counseling
|
| 46 |
+
dialogues; the bundled stage, transition, and global priors were aggregated from
|
| 47 |
+
1,010 annotated dialogues.
|
| 48 |
+
|
| 49 |
+
## Generate a trajectory
|
| 50 |
+
|
| 51 |
+
Authenticate with a Hugging Face account that has access to this private model:
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
pip install huggingface_hub
|
| 55 |
+
hf auth login
|
| 56 |
+
python -c 'from huggingface_hub import snapshot_download; snapshot_download("UEC-InabaLab/CounselTraj-DA", local_dir="CounselTraj-DA")'
|
| 57 |
+
cd CounselTraj-DA
|
| 58 |
+
pip install -r requirements.txt
|
| 59 |
+
python plan_trajectory.py --input-file examples/input.jsonl --limit 1
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
The default inference path uses CUDA and bitsandbytes NF4 quantization. On a
|
| 63 |
+
supported device with enough memory, `--no-4bit` loads the base model without
|
| 64 |
+
4-bit quantization.
|
| 65 |
+
|
| 66 |
+
Input is UTF-8 JSONL with an `input` string containing the brief dialogue. Optional
|
| 67 |
+
fields include `id`, `topic`, `topic_zh`, `source_dataset`, and `source_id`. The
|
| 68 |
+
bundled example is a newly written synthetic illustration. The output JSONL
|
| 69 |
+
contains the planned role-tagged trajectory in `output`, along with its length
|
| 70 |
+
and tag counts.
|
| 71 |
+
The original planner can append closing acts beyond its target length budget;
|
| 72 |
+
count the acts in `output` when an exact realized length is needed.
|
| 73 |
+
|
| 74 |
+
The planner combines adapter likelihoods with stage, transition, and global
|
| 75 |
+
priors, content and phase scores, a repetition penalty, and a diversity bonus.
|
| 76 |
+
Use `plan_trajectory.py` to run this decoding procedure. Loading the adapter alone
|
| 77 |
+
provides the language-model component of the planner.
|
| 78 |
+
|
| 79 |
+
## Load the adapter in Python
|
| 80 |
+
|
| 81 |
+
```python
|
| 82 |
+
import torch
|
| 83 |
+
from peft import PeftModel
|
| 84 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 85 |
+
|
| 86 |
+
repo_id = "UEC-InabaLab/CounselTraj-DA"
|
| 87 |
+
tokenizer = AutoTokenizer.from_pretrained(repo_id)
|
| 88 |
+
base = AutoModelForCausalLM.from_pretrained(
|
| 89 |
+
"Qwen/Qwen3-8B",
|
| 90 |
+
quantization_config=BitsAndBytesConfig(
|
| 91 |
+
load_in_4bit=True,
|
| 92 |
+
bnb_4bit_quant_type="nf4",
|
| 93 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 94 |
+
),
|
| 95 |
+
device_map="auto",
|
| 96 |
+
)
|
| 97 |
+
model = PeftModel.from_pretrained(base, repo_id)
|
| 98 |
+
model.eval()
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
## Files
|
| 102 |
+
|
| 103 |
+
- `adapter_model.safetensors` and `adapter_config.json`: selected LoRA weights and configuration.
|
| 104 |
+
- Tokenizer files: the saved tokenizer accompanying the adapter.
|
| 105 |
+
- `plan_trajectory.py`: v4 planning algorithm, with portable local defaults.
|
| 106 |
+
- `da_stats.json`: aggregate planning priors.
|
| 107 |
+
- `examples/input.jsonl`: synthetic input example.
|
| 108 |
+
- `model_details.json`: checkpoint selection and release details.
|
| 109 |
+
- `validation.json`: release checks and a synthetic GPU inference check.
|
| 110 |
+
- `SHA256SUMS`: file integrity checksums.
|
| 111 |
+
|
| 112 |
+
The planner generates research planning labels. Its trajectories have not been
|
| 113 |
+
validated as clinical treatment plans.
|
| 114 |
+
|
| 115 |
+
## Citation
|
| 116 |
+
|
| 117 |
+
```bibtex
|
| 118 |
+
@inproceedings{qi-inaba-2027-counseltraj,
|
| 119 |
+
title = "{CounselTraj}: Synthesizing Process-Aware Psychological Counseling Dialogues via Dialogue-Act Trajectory Planning",
|
| 120 |
+
author = "Qi, Zhiyang and Inaba, Michimasa",
|
| 121 |
+
booktitle = "Proceedings of the 20th Conference of the European Chapter of the Association for Computational Linguistics",
|
| 122 |
+
year = "2027",
|
| 123 |
+
}
|
| 124 |
+
```
|
SHA256SUMS
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
4d49a320e87134128d77d68f82488a96b128fb1a3a9db54ea9f3f44cd289da7c README.md
|
| 2 |
+
d14558619c5941e26716db37de14547c202bffe9d0bffc2492bd9ea788bad2a3 adapter_config.json
|
| 3 |
+
f9cf6a1654d91c341678d2464098bc26c27bc58404cd57bc0a6f227d50bb6631 adapter_model.safetensors
|
| 4 |
+
c0284b582e14987fbd3d5a2cb2bd139084371ed9acbae488829a1c900833c680 added_tokens.json
|
| 5 |
+
a55ee1b1660128b7098723e0abcd92caa0788061051c62d51cbe87d9cf1974d8 chat_template.jinja
|
| 6 |
+
ebd1a1d94e94060f88466d87d10997daab72d235f6eb13140316ce67ca6c7a60 da_stats.json
|
| 7 |
+
b8955b4ed2477148b5a1b9803c4873f2bc9888498fed51e9a2d79cef8d4897b8 examples/input.jsonl
|
| 8 |
+
a8d98faa859e942ec71f7008abea92a21cfd7fcc3c3b26b4f02137945c502a16 examples/trajectory.json
|
| 9 |
+
8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5 merges.txt
|
| 10 |
+
20d36d69bd1473b1c010ba32247050c062ca2f65a52f9ef21771e7866a65115a model_details.json
|
| 11 |
+
07572dcf424b508c333839a33dee36263cca5af8c40826b265ae2841e60abbbc plan_trajectory.py
|
| 12 |
+
5e8cce717f3c608b4496d812ff0bda2fe0419c337032a7ddd81c9869407227ed requirements.txt
|
| 13 |
+
76862e765266b85aa9459767e33cbaf13970f327a0e88d1c65846c2ddd3a1ecd special_tokens_map.json
|
| 14 |
+
aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4 tokenizer.json
|
| 15 |
+
443bfa629eb16387a12edbf92a76f6a6f10b2af3b53d87ba1550adfcf45f7fa0 tokenizer_config.json
|
| 16 |
+
def429f754ee9a032e5657f09b212d8bae46c7c439f9d929b9d8f7e8f58fbec6 validation.json
|
| 17 |
+
ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910 vocab.json
|
adapter_config.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"alpha_pattern": {},
|
| 3 |
+
"auto_mapping": null,
|
| 4 |
+
"base_model_name_or_path": "Qwen/Qwen3-8B",
|
| 5 |
+
"bias": "none",
|
| 6 |
+
"corda_config": null,
|
| 7 |
+
"eva_config": null,
|
| 8 |
+
"exclude_modules": null,
|
| 9 |
+
"fan_in_fan_out": false,
|
| 10 |
+
"inference_mode": true,
|
| 11 |
+
"init_lora_weights": true,
|
| 12 |
+
"layer_replication": null,
|
| 13 |
+
"layers_pattern": null,
|
| 14 |
+
"layers_to_transform": null,
|
| 15 |
+
"loftq_config": {},
|
| 16 |
+
"lora_alpha": 16,
|
| 17 |
+
"lora_bias": false,
|
| 18 |
+
"lora_dropout": 0.05,
|
| 19 |
+
"megatron_config": null,
|
| 20 |
+
"megatron_core": "megatron.core",
|
| 21 |
+
"modules_to_save": null,
|
| 22 |
+
"peft_type": "LORA",
|
| 23 |
+
"qalora_group_size": 16,
|
| 24 |
+
"r": 8,
|
| 25 |
+
"rank_pattern": {},
|
| 26 |
+
"revision": null,
|
| 27 |
+
"target_modules": [
|
| 28 |
+
"v_proj",
|
| 29 |
+
"o_proj",
|
| 30 |
+
"q_proj",
|
| 31 |
+
"down_proj",
|
| 32 |
+
"up_proj",
|
| 33 |
+
"gate_proj",
|
| 34 |
+
"k_proj"
|
| 35 |
+
],
|
| 36 |
+
"target_parameters": null,
|
| 37 |
+
"task_type": "CAUSAL_LM",
|
| 38 |
+
"trainable_token_indices": null,
|
| 39 |
+
"use_dora": false,
|
| 40 |
+
"use_qalora": false,
|
| 41 |
+
"use_rslora": false
|
| 42 |
+
}
|
adapter_model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f9cf6a1654d91c341678d2464098bc26c27bc58404cd57bc0a6f227d50bb6631
|
| 3 |
+
size 87360584
|
added_tokens.json
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"</think>": 151668,
|
| 3 |
+
"</tool_call>": 151658,
|
| 4 |
+
"</tool_response>": 151666,
|
| 5 |
+
"<think>": 151667,
|
| 6 |
+
"<tool_call>": 151657,
|
| 7 |
+
"<tool_response>": 151665,
|
| 8 |
+
"<|box_end|>": 151649,
|
| 9 |
+
"<|box_start|>": 151648,
|
| 10 |
+
"<|endoftext|>": 151643,
|
| 11 |
+
"<|file_sep|>": 151664,
|
| 12 |
+
"<|fim_middle|>": 151660,
|
| 13 |
+
"<|fim_pad|>": 151662,
|
| 14 |
+
"<|fim_prefix|>": 151659,
|
| 15 |
+
"<|fim_suffix|>": 151661,
|
| 16 |
+
"<|im_end|>": 151645,
|
| 17 |
+
"<|im_start|>": 151644,
|
| 18 |
+
"<|image_pad|>": 151655,
|
| 19 |
+
"<|object_ref_end|>": 151647,
|
| 20 |
+
"<|object_ref_start|>": 151646,
|
| 21 |
+
"<|quad_end|>": 151651,
|
| 22 |
+
"<|quad_start|>": 151650,
|
| 23 |
+
"<|repo_name|>": 151663,
|
| 24 |
+
"<|video_pad|>": 151656,
|
| 25 |
+
"<|vision_end|>": 151653,
|
| 26 |
+
"<|vision_pad|>": 151654,
|
| 27 |
+
"<|vision_start|>": 151652
|
| 28 |
+
}
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- if tools %}
|
| 2 |
+
{{- '<|im_start|>system\n' }}
|
| 3 |
+
{%- if messages[0].role == 'system' %}
|
| 4 |
+
{{- messages[0].content + '\n\n' }}
|
| 5 |
+
{%- endif %}
|
| 6 |
+
{{- "# Tools\n\nYou may call one or more functions to assist with the user query.\n\nYou are provided with function signatures within <tools></tools> XML tags:\n<tools>" }}
|
| 7 |
+
{%- for tool in tools %}
|
| 8 |
+
{{- "\n" }}
|
| 9 |
+
{{- tool | tojson }}
|
| 10 |
+
{%- endfor %}
|
| 11 |
+
{{- "\n</tools>\n\nFor each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n<tool_call>\n{\"name\": <function-name>, \"arguments\": <args-json-object>}\n</tool_call><|im_end|>\n" }}
|
| 12 |
+
{%- else %}
|
| 13 |
+
{%- if messages[0].role == 'system' %}
|
| 14 |
+
{{- '<|im_start|>system\n' + messages[0].content + '<|im_end|>\n' }}
|
| 15 |
+
{%- endif %}
|
| 16 |
+
{%- endif %}
|
| 17 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
| 18 |
+
{%- for message in messages[::-1] %}
|
| 19 |
+
{%- set index = (messages|length - 1) - loop.index0 %}
|
| 20 |
+
{%- if ns.multi_step_tool and message.role == "user" and message.content is string and not(message.content.startswith('<tool_response>') and message.content.endswith('</tool_response>')) %}
|
| 21 |
+
{%- set ns.multi_step_tool = false %}
|
| 22 |
+
{%- set ns.last_query_index = index %}
|
| 23 |
+
{%- endif %}
|
| 24 |
+
{%- endfor %}
|
| 25 |
+
{%- for message in messages %}
|
| 26 |
+
{%- if message.content is string %}
|
| 27 |
+
{%- set content = message.content %}
|
| 28 |
+
{%- else %}
|
| 29 |
+
{%- set content = '' %}
|
| 30 |
+
{%- endif %}
|
| 31 |
+
{%- if (message.role == "user") or (message.role == "system" and not loop.first) %}
|
| 32 |
+
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
|
| 33 |
+
{%- elif message.role == "assistant" %}
|
| 34 |
+
{%- set reasoning_content = '' %}
|
| 35 |
+
{%- if message.reasoning_content is string %}
|
| 36 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 37 |
+
{%- else %}
|
| 38 |
+
{%- if '</think>' in content %}
|
| 39 |
+
{%- set reasoning_content = content.split('</think>')[0].rstrip('\n').split('<think>')[-1].lstrip('\n') %}
|
| 40 |
+
{%- set content = content.split('</think>')[-1].lstrip('\n') %}
|
| 41 |
+
{%- endif %}
|
| 42 |
+
{%- endif %}
|
| 43 |
+
{%- if loop.index0 > ns.last_query_index %}
|
| 44 |
+
{%- if loop.last or (not loop.last and reasoning_content) %}
|
| 45 |
+
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content.strip('\n') + '\n</think>\n\n' + content.lstrip('\n') }}
|
| 46 |
+
{%- else %}
|
| 47 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 48 |
+
{%- endif %}
|
| 49 |
+
{%- else %}
|
| 50 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 51 |
+
{%- endif %}
|
| 52 |
+
{%- if message.tool_calls %}
|
| 53 |
+
{%- for tool_call in message.tool_calls %}
|
| 54 |
+
{%- if (loop.first and content) or (not loop.first) %}
|
| 55 |
+
{{- '\n' }}
|
| 56 |
+
{%- endif %}
|
| 57 |
+
{%- if tool_call.function %}
|
| 58 |
+
{%- set tool_call = tool_call.function %}
|
| 59 |
+
{%- endif %}
|
| 60 |
+
{{- '<tool_call>\n{"name": "' }}
|
| 61 |
+
{{- tool_call.name }}
|
| 62 |
+
{{- '", "arguments": ' }}
|
| 63 |
+
{%- if tool_call.arguments is string %}
|
| 64 |
+
{{- tool_call.arguments }}
|
| 65 |
+
{%- else %}
|
| 66 |
+
{{- tool_call.arguments | tojson }}
|
| 67 |
+
{%- endif %}
|
| 68 |
+
{{- '}\n</tool_call>' }}
|
| 69 |
+
{%- endfor %}
|
| 70 |
+
{%- endif %}
|
| 71 |
+
{{- '<|im_end|>\n' }}
|
| 72 |
+
{%- elif message.role == "tool" %}
|
| 73 |
+
{%- if loop.first or (messages[loop.index0 - 1].role != "tool") %}
|
| 74 |
+
{{- '<|im_start|>user' }}
|
| 75 |
+
{%- endif %}
|
| 76 |
+
{{- '\n<tool_response>\n' }}
|
| 77 |
+
{{- content }}
|
| 78 |
+
{{- '\n</tool_response>' }}
|
| 79 |
+
{%- if loop.last or (messages[loop.index0 + 1].role != "tool") %}
|
| 80 |
+
{{- '<|im_end|>\n' }}
|
| 81 |
+
{%- endif %}
|
| 82 |
+
{%- endif %}
|
| 83 |
+
{%- endfor %}
|
| 84 |
+
{%- if add_generation_prompt %}
|
| 85 |
+
{{- '<|im_start|>assistant\n' }}
|
| 86 |
+
{%- if enable_thinking is defined and enable_thinking is false %}
|
| 87 |
+
{{- '<think>\n\n</think>\n\n' }}
|
| 88 |
+
{%- endif %}
|
| 89 |
+
{%- endif %}
|
da_stats.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
examples/input.jsonl
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"id": "synthetic-example-001", "source_dataset": "synthetic_example", "source_id": "example-001", "topic": "emotion_anxiety", "topic_zh": "情绪焦虑", "input": "client:最近快考试了,我总担心考不好,晚上也睡不着。\ncounselor:听起来考试的压力让你一直很紧张。\nclient:是的,我想知道怎么让自己放松一点。"}
|
examples/trajectory.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"index": 0,
|
| 3 |
+
"id": "synthetic-example-001",
|
| 4 |
+
"source_dataset": "synthetic_example",
|
| 5 |
+
"source_id": "example-001",
|
| 6 |
+
"topic": "emotion_anxiety",
|
| 7 |
+
"topic_zh": "情绪焦虑",
|
| 8 |
+
"turn_count": null,
|
| 9 |
+
"input": "client:最近快考试了,我总担心考不好,晚上也睡不着。\ncounselor:听起来考试的压力让你一直很紧张。\nclient:是的,我想知道怎么让自己放松一点。",
|
| 10 |
+
"features": {
|
| 11 |
+
"emotion": 2,
|
| 12 |
+
"request": 0,
|
| 13 |
+
"detail": 2,
|
| 14 |
+
"hesitation": 0,
|
| 15 |
+
"positive": 0,
|
| 16 |
+
"relation": 0,
|
| 17 |
+
"career": 0,
|
| 18 |
+
"crisis": 0,
|
| 19 |
+
"knowledge": 0,
|
| 20 |
+
"topic": "emotion_anxiety",
|
| 21 |
+
"topic_zh": "情绪焦虑",
|
| 22 |
+
"turn_count": 0,
|
| 23 |
+
"chars": 82
|
| 24 |
+
},
|
| 25 |
+
"topic_group": "emotion",
|
| 26 |
+
"target_len": 8,
|
| 27 |
+
"output": "counselor:[Greeting] client:[Greeting] counselor:[OpenQuestion] client:[SelfDisclosure] counselor:[Affirm] client:[DetailedDescription] counselor:[Affirm] client:[Thanking] counselor:[Greeting]",
|
| 28 |
+
"tag_counts": {
|
| 29 |
+
"Greeting": 3,
|
| 30 |
+
"OpenQuestion": 1,
|
| 31 |
+
"SelfDisclosure": 1,
|
| 32 |
+
"Affirm": 2,
|
| 33 |
+
"DetailedDescription": 1,
|
| 34 |
+
"Thanking": 1
|
| 35 |
+
},
|
| 36 |
+
"role_tag_counts": {
|
| 37 |
+
"client": {
|
| 38 |
+
"Greeting": 1,
|
| 39 |
+
"SelfDisclosure": 1,
|
| 40 |
+
"DetailedDescription": 1,
|
| 41 |
+
"Thanking": 1
|
| 42 |
+
},
|
| 43 |
+
"counselor": {
|
| 44 |
+
"Greeting": 2,
|
| 45 |
+
"OpenQuestion": 1,
|
| 46 |
+
"Affirm": 2
|
| 47 |
+
}
|
| 48 |
+
}
|
| 49 |
+
}
|
merges.txt
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model_details.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"base_model": "Qwen/Qwen3-8B",
|
| 3 |
+
"adapter_type": "LoRA",
|
| 4 |
+
"selected_checkpoint": "checkpoint-145",
|
| 5 |
+
"epoch": 5.0,
|
| 6 |
+
"global_step": 145,
|
| 7 |
+
"validation_loss": 1.1678476333618164,
|
| 8 |
+
"adapter_parameters": 21823488,
|
| 9 |
+
"rank": 8,
|
| 10 |
+
"alpha": 16,
|
| 11 |
+
"dropout": 0.05,
|
| 12 |
+
"learning_rate": 0.0002,
|
| 13 |
+
"warmup_ratio": 0.03,
|
| 14 |
+
"training_epochs": 5,
|
| 15 |
+
"planner_version": "v4",
|
| 16 |
+
"prior_dialogues": 1010,
|
| 17 |
+
"script_changes": [
|
| 18 |
+
"Resolve adapter, prior and example paths relative to this release.",
|
| 19 |
+
"Set dialogue_chars default to 900, matching the saved production configuration."
|
| 20 |
+
]
|
| 21 |
+
}
|
plan_trajectory.py
ADDED
|
@@ -0,0 +1,929 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import json
|
| 3 |
+
import math
|
| 4 |
+
import os
|
| 5 |
+
import random
|
| 6 |
+
from collections import Counter, defaultdict
|
| 7 |
+
from datetime import datetime
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import torch
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
from peft import PeftModel
|
| 13 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
BASE_MODEL_ID = "Qwen/Qwen3-8B"
|
| 17 |
+
RELEASE_ROOT = Path(__file__).resolve().parent
|
| 18 |
+
CHECKPOINT_DIR = str(RELEASE_ROOT)
|
| 19 |
+
INPUT_FILE = str(RELEASE_ROOT / "examples" / "input.jsonl")
|
| 20 |
+
ANNOTATED_DIR = ""
|
| 21 |
+
OUTPUT_DIR = "./outputs"
|
| 22 |
+
STATS_FILE = str(RELEASE_ROOT / "da_stats.json")
|
| 23 |
+
|
| 24 |
+
CLIENT_TAGS = [
|
| 25 |
+
"Greeting",
|
| 26 |
+
"SimpleAnswer",
|
| 27 |
+
"DetailedDescription",
|
| 28 |
+
"SelfDisclosure",
|
| 29 |
+
"Backchannel",
|
| 30 |
+
"Agreement",
|
| 31 |
+
"PositiveEmotion",
|
| 32 |
+
"Hesitation",
|
| 33 |
+
"Question",
|
| 34 |
+
"Request",
|
| 35 |
+
"Thanking",
|
| 36 |
+
"UnderstandingCheck",
|
| 37 |
+
"Other",
|
| 38 |
+
]
|
| 39 |
+
|
| 40 |
+
COUNSELOR_TAGS = [
|
| 41 |
+
"Greeting",
|
| 42 |
+
"OpenQuestion",
|
| 43 |
+
"ClosedQuestion",
|
| 44 |
+
"Paraphrase",
|
| 45 |
+
"Reflection",
|
| 46 |
+
"Affirm",
|
| 47 |
+
"Backchannel",
|
| 48 |
+
"Suggest",
|
| 49 |
+
"Inform",
|
| 50 |
+
"Thanking",
|
| 51 |
+
"Other",
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
TAG_DEFINITIONS = {
|
| 55 |
+
"client": {
|
| 56 |
+
"Greeting": "opening or closing greeting",
|
| 57 |
+
"SimpleAnswer": "brief answer without elaboration",
|
| 58 |
+
"DetailedDescription": "detailed event, context, or background",
|
| 59 |
+
"SelfDisclosure": "inner feeling, thought, vulnerability, distress",
|
| 60 |
+
"Backchannel": "very short listening response",
|
| 61 |
+
"Agreement": "agreement with counselor's view",
|
| 62 |
+
"PositiveEmotion": "hope, relief, confidence, positive change",
|
| 63 |
+
"Hesitation": "uncertainty, difficulty speaking, ambivalence",
|
| 64 |
+
"Question": "general question",
|
| 65 |
+
"Request": "request for advice or help",
|
| 66 |
+
"Thanking": "thanks",
|
| 67 |
+
"UnderstandingCheck": "checking or restating understanding",
|
| 68 |
+
"Other": "other reasonable client act",
|
| 69 |
+
},
|
| 70 |
+
"counselor": {
|
| 71 |
+
"Greeting": "opening or closing greeting",
|
| 72 |
+
"OpenQuestion": "open-ended exploration question",
|
| 73 |
+
"ClosedQuestion": "yes/no or short factual question",
|
| 74 |
+
"Paraphrase": "restating facts without adding emotion",
|
| 75 |
+
"Reflection": "reflecting emotion or inner state",
|
| 76 |
+
"Affirm": "support, validation, encouragement",
|
| 77 |
+
"Backchannel": "short listening response",
|
| 78 |
+
"Suggest": "gentle advice or action option",
|
| 79 |
+
"Inform": "information, explanation, psychoeducation",
|
| 80 |
+
"Thanking": "thanks for sharing",
|
| 81 |
+
"Other": "other reasonable counselor act",
|
| 82 |
+
},
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
EMOTION_WORDS = [
|
| 86 |
+
"焦虑", "抑郁", "难受", "痛苦", "害怕", "恐惧", "担心", "压力", "崩溃",
|
| 87 |
+
"无助", "内疚", "自责", "迷茫", "纠结", "烦", "累", "失眠", "伤心",
|
| 88 |
+
"生气", "愤怒", "委屈", "孤独", "失败", "糟糕", "绝望",
|
| 89 |
+
]
|
| 90 |
+
REQUEST_WORDS = ["怎么办", "建议", "帮助", "求助", "请问", "该怎么", "如何", "怎么做", "有什么办法"]
|
| 91 |
+
DETAIL_WORDS = ["因为", "后来", "然后", "之前", "最近", "一直", "每次", "当时", "现在", "经历"]
|
| 92 |
+
HESITATION_WORDS = ["不知道", "不确定", "犹豫", "纠结", "可能", "也许", "说不清", "不敢"]
|
| 93 |
+
POSITIVE_WORDS = ["谢谢", "感谢", "有希望", "好一点", "轻松", "明白", "愿意", "试试", "加油"]
|
| 94 |
+
RELATION_WORDS = ["妈妈", "爸爸", "父母", "男朋友", "女朋友", "老公", "老婆", "朋友", "同学", "老师", "孩子", "家人"]
|
| 95 |
+
CAREER_WORDS = ["工作", "职业", "上班", "辞职", "转行", "考研", "学习", "成绩", "学校", "专业"]
|
| 96 |
+
CRISIS_WORDS = [
|
| 97 |
+
"自杀", "自残", "轻生", "跳河", "跳楼", "割腕", "活不下去", "不想活",
|
| 98 |
+
"死了算了", "结束生命", "想死", "寻死", "伤害自己", "解脱",
|
| 99 |
+
]
|
| 100 |
+
KNOWLEDGE_WORDS = [
|
| 101 |
+
"认知行为疗法", "疗法", "流派", "咨询师", "心理咨询", "心理治疗", "是不是",
|
| 102 |
+
"什么是", "区别", "原理", "理论", "方法", "技术", "诊断", "症状",
|
| 103 |
+
]
|
| 104 |
+
|
| 105 |
+
EPS = 1e-8
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def load_json(path):
|
| 109 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 110 |
+
return json.load(f)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def save_json(path, data):
|
| 114 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 115 |
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def read_jsonl(path, limit=None, offset=0, spread=False):
|
| 119 |
+
if spread and limit:
|
| 120 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 121 |
+
total = sum(1 for line in f if line.strip())
|
| 122 |
+
if limit >= total:
|
| 123 |
+
wanted = set(range(total))
|
| 124 |
+
else:
|
| 125 |
+
wanted = {round(i * (total - 1) / (limit - 1)) for i in range(limit)}
|
| 126 |
+
rows = []
|
| 127 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 128 |
+
for line_no, line in enumerate(f):
|
| 129 |
+
if line_no in wanted and line.strip():
|
| 130 |
+
obj = json.loads(line)
|
| 131 |
+
obj["_global_index"] = line_no
|
| 132 |
+
rows.append(obj)
|
| 133 |
+
rows.sort(key=lambda x: x["_global_index"])
|
| 134 |
+
return rows
|
| 135 |
+
|
| 136 |
+
rows = []
|
| 137 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 138 |
+
for line_no, line in enumerate(f):
|
| 139 |
+
if line_no < offset:
|
| 140 |
+
continue
|
| 141 |
+
if limit is not None and len(rows) >= limit:
|
| 142 |
+
break
|
| 143 |
+
line = line.strip()
|
| 144 |
+
if line:
|
| 145 |
+
obj = json.loads(line)
|
| 146 |
+
obj["_global_index"] = line_no
|
| 147 |
+
rows.append(obj)
|
| 148 |
+
return rows
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def append_jsonl(path, item):
|
| 152 |
+
with open(path, "a", encoding="utf-8") as f:
|
| 153 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def safe_log(x):
|
| 157 |
+
return math.log(max(x, EPS))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def stat_key(*parts):
|
| 161 |
+
return "||".join(str(x) for x in parts)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def parse_stat_key(text):
|
| 165 |
+
return tuple(str(text).split("||"))
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def get_stage(step, total):
|
| 169 |
+
r = step / total
|
| 170 |
+
if r < 0.18:
|
| 171 |
+
return "stage_1"
|
| 172 |
+
if r < 0.38:
|
| 173 |
+
return "stage_2"
|
| 174 |
+
if r < 0.62:
|
| 175 |
+
return "stage_3"
|
| 176 |
+
if r < 0.82:
|
| 177 |
+
return "stage_4"
|
| 178 |
+
return "stage_5"
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def render_dialogue(item, max_chars=1200):
|
| 182 |
+
if item.get("input"):
|
| 183 |
+
text = item["input"]
|
| 184 |
+
else:
|
| 185 |
+
lines = []
|
| 186 |
+
for turn in item.get("dialogue", []):
|
| 187 |
+
role = str(turn.get("role", "")).lower()
|
| 188 |
+
utterance = str(turn.get("utterance", "")).strip()
|
| 189 |
+
if role and utterance:
|
| 190 |
+
lines.append(f"{role}:{utterance}")
|
| 191 |
+
text = "\n".join(lines)
|
| 192 |
+
return text[:max_chars]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def count_hits(text, words):
|
| 196 |
+
return sum(text.count(w) for w in words)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def text_features(item, dialogue_text):
|
| 200 |
+
first_client = item.get("first_client_utterance", "")
|
| 201 |
+
text = f"{first_client}\n{dialogue_text}"
|
| 202 |
+
chars = len(text)
|
| 203 |
+
return {
|
| 204 |
+
"emotion": count_hits(text, EMOTION_WORDS),
|
| 205 |
+
"request": count_hits(text, REQUEST_WORDS) + text.count("?") + text.count("?"),
|
| 206 |
+
"detail": count_hits(text, DETAIL_WORDS) + max(0, chars // 260),
|
| 207 |
+
"hesitation": count_hits(text, HESITATION_WORDS),
|
| 208 |
+
"positive": count_hits(text, POSITIVE_WORDS),
|
| 209 |
+
"relation": count_hits(text, RELATION_WORDS),
|
| 210 |
+
"career": count_hits(text, CAREER_WORDS),
|
| 211 |
+
"crisis": count_hits(text, CRISIS_WORDS),
|
| 212 |
+
"knowledge": count_hits(text, KNOWLEDGE_WORDS),
|
| 213 |
+
"topic": item.get("topic", ""),
|
| 214 |
+
"topic_zh": item.get("topic_zh", ""),
|
| 215 |
+
"turn_count": int(item.get("turn_count", 0) or 0),
|
| 216 |
+
"chars": chars,
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def dynamic_target_len(features, min_len, max_len):
|
| 221 |
+
base = 58
|
| 222 |
+
base += min(18, features["turn_count"])
|
| 223 |
+
base += min(12, features["chars"] // 220)
|
| 224 |
+
base += min(8, features["emotion"] + features["detail"] // 2)
|
| 225 |
+
base += 4 if features["request"] else 0
|
| 226 |
+
if base % 2:
|
| 227 |
+
base += 1
|
| 228 |
+
return max(min_len, min(max_len, base))
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def topic_group(features):
|
| 232 |
+
topic = str(features.get("topic", ""))
|
| 233 |
+
topic_zh = str(features.get("topic_zh", ""))
|
| 234 |
+
text = f"{topic} {topic_zh}".lower()
|
| 235 |
+
|
| 236 |
+
if features.get("crisis", 0):
|
| 237 |
+
return "crisis"
|
| 238 |
+
if features.get("knowledge", 0) >= 2 or any(x in text for x in ["knowledge", "therapy", "心理知识", "治疗", "咨询方式"]):
|
| 239 |
+
return "knowledge"
|
| 240 |
+
if any(x in text for x in ["academic", "school", "学业", "校园", "考试", "学习"]):
|
| 241 |
+
return "academic"
|
| 242 |
+
if any(x in text for x in ["career", "work", "职场", "职业", "工作"]):
|
| 243 |
+
return "career"
|
| 244 |
+
if any(x in text for x in ["family", "parent", "家庭", "亲子", "父母"]):
|
| 245 |
+
return "family"
|
| 246 |
+
if any(x in text for x in ["romantic", "love", "marriage", "婚恋", "恋爱", "伴侣"]):
|
| 247 |
+
return "romance"
|
| 248 |
+
if any(x in text for x in ["interpersonal", "social", "人际", "社交", "朋友", "同学"]):
|
| 249 |
+
return "interpersonal"
|
| 250 |
+
if any(x in text for x in ["depression", "anxiety", "emotion", "抑郁", "焦虑", "情绪"]):
|
| 251 |
+
return "emotion"
|
| 252 |
+
if any(x in text for x in ["health", "sleep", "body", "健康", "睡眠", "躯体"]):
|
| 253 |
+
return "health"
|
| 254 |
+
if any(x in text for x in ["habit", "behavior", "行为", "习惯"]):
|
| 255 |
+
return "habit"
|
| 256 |
+
if any(x in text for x in ["identity", "自我", "认同"]):
|
| 257 |
+
return "identity"
|
| 258 |
+
if any(x in text for x in ["growth", "planning", "成长", "规划"]):
|
| 259 |
+
return "planning"
|
| 260 |
+
if any(x in text for x in ["adaptation", "适应"]):
|
| 261 |
+
return "adaptation"
|
| 262 |
+
if any(x in text for x in ["sexual", "性心理"]):
|
| 263 |
+
return "sexuality"
|
| 264 |
+
return "general"
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def topic_specific_bias(tag, role, features, step, total):
|
| 268 |
+
group = topic_group(features)
|
| 269 |
+
r = step / total
|
| 270 |
+
bias = 0.0
|
| 271 |
+
|
| 272 |
+
if role == "counselor":
|
| 273 |
+
if group == "crisis":
|
| 274 |
+
bias += {"ClosedQuestion": 1.10, "Reflection": 0.65, "Paraphrase": 0.35}.get(tag, 0)
|
| 275 |
+
bias += {"Suggest": 0.55, "Inform": 0.45}.get(tag, 0) if r > 0.32 else 0
|
| 276 |
+
bias += {"Backchannel": -0.35, "Thanking": -0.25}.get(tag, 0)
|
| 277 |
+
elif group == "knowledge":
|
| 278 |
+
bias += {"Inform": 1.10, "ClosedQuestion": 0.35, "OpenQuestion": 0.25, "Paraphrase": 0.20}.get(tag, 0)
|
| 279 |
+
bias += 0.30 if tag == "Suggest" and r > 0.55 else 0
|
| 280 |
+
bias += {"Reflection": -0.25, "Affirm": -0.15, "Backchannel": -0.25}.get(tag, 0)
|
| 281 |
+
elif group in {"academic", "career", "planning"}:
|
| 282 |
+
bias += {"ClosedQuestion": 0.38, "Inform": 0.58, "Suggest": 0.62, "OpenQuestion": 0.25, "Paraphrase": 0.18}.get(tag, 0)
|
| 283 |
+
bias += 0.18 if tag == "Reflection" and features.get("emotion", 0) else 0
|
| 284 |
+
bias += -0.20 if tag == "Backchannel" else 0
|
| 285 |
+
bias += -0.25 if tag == "Suggest" and r < 0.38 else 0
|
| 286 |
+
elif group in {"family", "romance", "interpersonal"}:
|
| 287 |
+
bias += {"Reflection": 0.78, "OpenQuestion": 0.48, "Paraphrase": 0.48, "Affirm": 0.28}.get(tag, 0)
|
| 288 |
+
bias += -0.35 if tag == "Inform" else 0
|
| 289 |
+
bias += -0.35 if tag == "Suggest" and r < 0.58 else 0
|
| 290 |
+
bias += 0.20 if tag == "Suggest" and r > 0.66 else 0
|
| 291 |
+
elif group in {"emotion", "identity"}:
|
| 292 |
+
bias += {"Reflection": 0.82, "Affirm": 0.35, "OpenQuestion": 0.35, "Paraphrase": 0.32}.get(tag, 0)
|
| 293 |
+
bias += -0.30 if tag == "Suggest" and r < 0.62 else 0
|
| 294 |
+
bias += -0.18 if tag == "Inform" else 0
|
| 295 |
+
elif group in {"health", "habit"}:
|
| 296 |
+
bias += {"ClosedQuestion": 0.48, "Inform": 0.45, "Suggest": 0.55, "Paraphrase": 0.25}.get(tag, 0)
|
| 297 |
+
bias += 0.18 if tag == "Reflection" and features.get("emotion", 0) else 0
|
| 298 |
+
bias += -0.20 if tag == "Suggest" and r < 0.42 else 0
|
| 299 |
+
elif group in {"adaptation", "sexuality"}:
|
| 300 |
+
bias += {"OpenQuestion": 0.40, "Reflection": 0.50, "Paraphrase": 0.35, "ClosedQuestion": 0.24}.get(tag, 0)
|
| 301 |
+
bias += 0.22 if tag == "Inform" and r > 0.45 else 0
|
| 302 |
+
|
| 303 |
+
else:
|
| 304 |
+
if group == "crisis":
|
| 305 |
+
bias += {"SelfDisclosure": 0.75, "Hesitation": 0.42, "DetailedDescription": 0.30, "SimpleAnswer": 0.25}.get(tag, 0)
|
| 306 |
+
bias += -0.95 if tag == "PositiveEmotion" and r < 0.85 else 0
|
| 307 |
+
bias += -0.35 if tag == "Thanking" else 0
|
| 308 |
+
elif group == "knowledge":
|
| 309 |
+
bias += {"Question": 0.85, "UnderstandingCheck": 0.75, "SimpleAnswer": 0.32, "Request": 0.28}.get(tag, 0)
|
| 310 |
+
bias += {"SelfDisclosure": -0.15, "Hesitation": -0.10, "PositiveEmotion": -0.25}.get(tag, 0)
|
| 311 |
+
elif group in {"academic", "career", "planning"}:
|
| 312 |
+
bias += {"DetailedDescription": 0.40, "Request": 0.35, "UnderstandingCheck": 0.30, "Agreement": 0.20}.get(tag, 0)
|
| 313 |
+
bias += 0.22 if tag == "SelfDisclosure" and features.get("emotion", 0) else 0
|
| 314 |
+
bias += -0.22 if tag == "PositiveEmotion" and r < 0.68 else 0
|
| 315 |
+
elif group in {"family", "romance", "interpersonal"}:
|
| 316 |
+
bias += {"SelfDisclosure": 0.62, "DetailedDescription": 0.46, "Hesitation": 0.32, "Agreement": 0.15}.get(tag, 0)
|
| 317 |
+
bias += -0.22 if tag == "Request" and r < 0.55 else 0
|
| 318 |
+
bias += -0.28 if tag == "PositiveEmotion" and r < 0.72 else 0
|
| 319 |
+
elif group in {"emotion", "identity"}:
|
| 320 |
+
bias += {"SelfDisclosure": 0.72, "Hesitation": 0.42, "DetailedDescription": 0.28}.get(tag, 0)
|
| 321 |
+
bias += -0.42 if tag == "PositiveEmotion" and r < 0.78 else 0
|
| 322 |
+
elif group in {"health", "habit"}:
|
| 323 |
+
bias += {"DetailedDescription": 0.45, "SimpleAnswer": 0.22, "Request": 0.30, "UnderstandingCheck": 0.18}.get(tag, 0)
|
| 324 |
+
bias += 0.18 if tag == "SelfDisclosure" and features.get("emotion", 0) else 0
|
| 325 |
+
elif group in {"adaptation", "sexuality"}:
|
| 326 |
+
bias += {"SelfDisclosure": 0.42, "Hesitation": 0.38, "DetailedDescription": 0.35, "Question": 0.22}.get(tag, 0)
|
| 327 |
+
|
| 328 |
+
return bias
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def parse_tag(entry):
|
| 332 |
+
role, rest = entry.split(":[", 1)
|
| 333 |
+
return role, rest[:-1]
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def tags_only(history, role=None):
|
| 337 |
+
out = []
|
| 338 |
+
for h in history:
|
| 339 |
+
if ":[" not in h:
|
| 340 |
+
continue
|
| 341 |
+
r, t = parse_tag(h)
|
| 342 |
+
if role is None or r == role:
|
| 343 |
+
out.append(t)
|
| 344 |
+
return out
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def repetition_penalty(tag, history, role):
|
| 348 |
+
recent_all = tags_only(history[-10:])
|
| 349 |
+
recent_role = tags_only(history[-16:], role)
|
| 350 |
+
penalty = 0.0
|
| 351 |
+
penalty += 0.55 * recent_all.count(tag)
|
| 352 |
+
penalty += 0.75 * recent_role.count(tag)
|
| 353 |
+
if recent_role and recent_role[-1] == tag:
|
| 354 |
+
penalty += 2.2
|
| 355 |
+
if len(recent_role) >= 2 and recent_role[-2:] == [tag, tag]:
|
| 356 |
+
penalty += 4.0
|
| 357 |
+
return penalty
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def diversity_bonus(tag, history, role):
|
| 361 |
+
recent_role = tags_only(history[-18:], role)
|
| 362 |
+
if tag not in recent_role:
|
| 363 |
+
return 1.2
|
| 364 |
+
if recent_role.count(tag) == 1:
|
| 365 |
+
return 0.35
|
| 366 |
+
return 0.0
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def phase_bias(tag, role, step, total):
|
| 370 |
+
r = step / total
|
| 371 |
+
bias = 0.0
|
| 372 |
+
|
| 373 |
+
if role == "counselor":
|
| 374 |
+
if r < 0.20:
|
| 375 |
+
bias += {"OpenQuestion": 0.55, "Reflection": 0.35, "Thanking": 0.15}.get(tag, 0)
|
| 376 |
+
elif r < 0.55:
|
| 377 |
+
bias += {"Reflection": 0.45, "Paraphrase": 0.35, "OpenQuestion": 0.30, "Affirm": 0.20}.get(tag, 0)
|
| 378 |
+
elif r < 0.82:
|
| 379 |
+
bias += {"Suggest": 0.45, "Inform": 0.35, "Reflection": 0.25, "ClosedQuestion": 0.12}.get(tag, 0)
|
| 380 |
+
else:
|
| 381 |
+
bias += {"Suggest": 0.35, "Affirm": 0.35, "Other": 0.18}.get(tag, 0)
|
| 382 |
+
else:
|
| 383 |
+
if r < 0.18:
|
| 384 |
+
bias += {"DetailedDescription": 0.45, "SelfDisclosure": 0.35, "Hesitation": 0.20}.get(tag, 0)
|
| 385 |
+
elif r < 0.55:
|
| 386 |
+
bias += {"DetailedDescription": 0.35, "SelfDisclosure": 0.35, "SimpleAnswer": 0.16}.get(tag, 0)
|
| 387 |
+
elif r < 0.82:
|
| 388 |
+
bias += {"Agreement": 0.20, "Request": 0.25, "UnderstandingCheck": 0.20, "SelfDisclosure": 0.20}.get(tag, 0)
|
| 389 |
+
else:
|
| 390 |
+
bias += {"PositiveEmotion": 0.45, "Agreement": 0.25, "Thanking": 0.20}.get(tag, 0)
|
| 391 |
+
|
| 392 |
+
return bias
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def content_bias(tag, role, features, step, total):
|
| 396 |
+
r = step / total
|
| 397 |
+
bias = 0.0
|
| 398 |
+
|
| 399 |
+
if role == "client":
|
| 400 |
+
if tag == "SelfDisclosure":
|
| 401 |
+
bias += min(0.85, 0.14 * features["emotion"])
|
| 402 |
+
if features["knowledge"] and not features["emotion"]:
|
| 403 |
+
bias -= 0.25
|
| 404 |
+
if tag == "DetailedDescription":
|
| 405 |
+
bias += min(0.75, 0.10 * features["detail"] + 0.04 * features["chars"] / 300)
|
| 406 |
+
if tag == "Request":
|
| 407 |
+
bias += min(0.75, 0.18 * features["request"])
|
| 408 |
+
if r < 0.22:
|
| 409 |
+
bias -= 0.25
|
| 410 |
+
if tag == "Question":
|
| 411 |
+
bias += min(0.45, 0.08 * features["request"])
|
| 412 |
+
bias += min(0.75, 0.16 * features["knowledge"])
|
| 413 |
+
if tag == "Hesitation":
|
| 414 |
+
bias += min(0.55, 0.14 * features["hesitation"])
|
| 415 |
+
if features["knowledge"]:
|
| 416 |
+
bias -= 0.15
|
| 417 |
+
if tag == "PositiveEmotion":
|
| 418 |
+
bias += min(0.45, 0.08 * features["positive"])
|
| 419 |
+
if r < 0.75:
|
| 420 |
+
bias -= 0.65
|
| 421 |
+
if features["crisis"]:
|
| 422 |
+
bias -= 0.80
|
| 423 |
+
if tag == "UnderstandingCheck":
|
| 424 |
+
bias += min(0.60, 0.12 * features["knowledge"])
|
| 425 |
+
if tag == "Thanking":
|
| 426 |
+
if r < 0.88:
|
| 427 |
+
bias -= 1.10
|
| 428 |
+
if features["crisis"]:
|
| 429 |
+
bias -= 0.35
|
| 430 |
+
|
| 431 |
+
else:
|
| 432 |
+
if tag == "Reflection":
|
| 433 |
+
bias += min(0.85, 0.12 * features["emotion"])
|
| 434 |
+
bias += min(0.90, 0.22 * features["crisis"])
|
| 435 |
+
if tag == "Paraphrase":
|
| 436 |
+
bias += min(0.50, 0.06 * features["detail"])
|
| 437 |
+
if features["knowledge"]:
|
| 438 |
+
bias += 0.12
|
| 439 |
+
if tag == "OpenQuestion":
|
| 440 |
+
bias += 0.25 if r < 0.45 else 0.05
|
| 441 |
+
if tag == "Suggest":
|
| 442 |
+
bias += min(0.70, 0.14 * features["request"])
|
| 443 |
+
if r < 0.40:
|
| 444 |
+
bias -= 0.35
|
| 445 |
+
if features["crisis"]:
|
| 446 |
+
bias += 0.35 if r > 0.35 else 0.05
|
| 447 |
+
if tag == "Inform":
|
| 448 |
+
bias += 0.20 if features["career"] or features["topic"] in {"academic_school", "career_work"} else 0
|
| 449 |
+
bias += min(1.00, 0.20 * features["knowledge"])
|
| 450 |
+
bias += min(0.55, 0.16 * features["crisis"])
|
| 451 |
+
if r < 0.35:
|
| 452 |
+
bias -= 0.20
|
| 453 |
+
if tag == "Affirm":
|
| 454 |
+
bias += 0.25 if features["emotion"] else 0.10
|
| 455 |
+
if features["knowledge"] and not features["emotion"]:
|
| 456 |
+
bias -= 0.10
|
| 457 |
+
if tag == "ClosedQuestion":
|
| 458 |
+
bias += min(0.90, 0.18 * features["crisis"])
|
| 459 |
+
if tag == "Thanking" and r > 0.35:
|
| 460 |
+
bias -= 0.85
|
| 461 |
+
if tag == "Thanking" and r < 0.88:
|
| 462 |
+
bias -= 1.20
|
| 463 |
+
|
| 464 |
+
if features["relation"] and role == "counselor" and tag in {"Reflection", "Paraphrase"}:
|
| 465 |
+
bias += 0.18
|
| 466 |
+
|
| 467 |
+
bias += topic_specific_bias(tag, role, features, step, total)
|
| 468 |
+
|
| 469 |
+
return bias
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
def is_allowed(tag, role, step, total, history, features):
|
| 473 |
+
r = step / total
|
| 474 |
+
if tag == "Greeting":
|
| 475 |
+
return False
|
| 476 |
+
if tag == "Thanking" and r < 0.82:
|
| 477 |
+
return False
|
| 478 |
+
if role == "counselor" and tag == "Thanking" and r < 0.88:
|
| 479 |
+
return False
|
| 480 |
+
if tag == "Backchannel":
|
| 481 |
+
recent_role = tags_only(history[-8:], role)
|
| 482 |
+
if recent_role.count("Backchannel") >= 1:
|
| 483 |
+
return False
|
| 484 |
+
if role == "counselor" and tag == "Suggest" and r < 0.30:
|
| 485 |
+
return False
|
| 486 |
+
positive_floor = 0.72 if features.get("crisis", 0) else 0.55
|
| 487 |
+
if role == "client" and tag == "PositiveEmotion" and r < positive_floor:
|
| 488 |
+
return False
|
| 489 |
+
return True
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def build_prompt(history, dialogue_text, item, features):
|
| 493 |
+
tag_part = " ".join(history[-28:])
|
| 494 |
+
topic = item.get("topic_zh") or item.get("topic") or "unknown"
|
| 495 |
+
definitions = []
|
| 496 |
+
next_role = "client" if history[-1].startswith("counselor") else "counselor"
|
| 497 |
+
for tag, desc in TAG_DEFINITIONS[next_role].items():
|
| 498 |
+
definitions.append(f"{next_role}:[{tag}] = {desc}")
|
| 499 |
+
definition_text = "\n".join(definitions)
|
| 500 |
+
|
| 501 |
+
return f"""You are generating a counseling dialogue-act trajectory.
|
| 502 |
+
The next act must fit the short dialogue content, the topic, the phase, and the previous acts.
|
| 503 |
+
Prefer natural counseling flow. Avoid repetitive tag patterns.
|
| 504 |
+
|
| 505 |
+
[Topic]
|
| 506 |
+
{topic}
|
| 507 |
+
|
| 508 |
+
[Short Dialogue]
|
| 509 |
+
{dialogue_text}
|
| 510 |
+
|
| 511 |
+
[Content Signals]
|
| 512 |
+
emotion={features['emotion']} request={features['request']} detail={features['detail']} hesitation={features['hesitation']} crisis={features['crisis']} knowledge={features['knowledge']} topic_group={topic_group(features)}
|
| 513 |
+
|
| 514 |
+
[Recent Tag History]
|
| 515 |
+
{tag_part}
|
| 516 |
+
|
| 517 |
+
[Available tags for next role]
|
| 518 |
+
{definition_text}
|
| 519 |
+
|
| 520 |
+
Next dialogue act:
|
| 521 |
+
"""
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def load_annotated(folder):
|
| 525 |
+
dialogs = []
|
| 526 |
+
for path in Path(folder).glob("**/*.json"):
|
| 527 |
+
try:
|
| 528 |
+
obj = load_json(path)
|
| 529 |
+
turns = []
|
| 530 |
+
for turn in obj.get("dialogue", []):
|
| 531 |
+
role = str(turn.get("role", "")).lower()
|
| 532 |
+
tag = turn.get("tag") or turn.get("dialogue_tag")
|
| 533 |
+
if role in {"client", "counselor"} and tag:
|
| 534 |
+
turns.append((role, str(tag)))
|
| 535 |
+
if len(turns) > 3:
|
| 536 |
+
dialogs.append(turns)
|
| 537 |
+
except Exception:
|
| 538 |
+
continue
|
| 539 |
+
print(f"[INFO] loaded annotated dialogues: {len(dialogs)}", flush=True)
|
| 540 |
+
return dialogs
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def normalize(counter):
|
| 544 |
+
total = sum(counter.values())
|
| 545 |
+
if total <= 0:
|
| 546 |
+
return {}
|
| 547 |
+
return {k: v / total for k, v in counter.items()}
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def build_stats(dialogs):
|
| 551 |
+
stage_role = defaultdict(Counter)
|
| 552 |
+
transition = defaultdict(Counter)
|
| 553 |
+
global_role = defaultdict(Counter)
|
| 554 |
+
start_role = defaultdict(Counter)
|
| 555 |
+
end_role = defaultdict(Counter)
|
| 556 |
+
|
| 557 |
+
for dialog in dialogs:
|
| 558 |
+
n = len(dialog)
|
| 559 |
+
for i, (role, tag) in enumerate(dialog):
|
| 560 |
+
stage = get_stage(i, n)
|
| 561 |
+
stage_role[(stage, role)][tag] += 1
|
| 562 |
+
global_role[role][tag] += 1
|
| 563 |
+
if i < max(3, n // 8):
|
| 564 |
+
start_role[role][tag] += 1
|
| 565 |
+
if i >= n - max(3, n // 8):
|
| 566 |
+
end_role[role][tag] += 1
|
| 567 |
+
if i > 0:
|
| 568 |
+
prev_role, prev_tag = dialog[i - 1]
|
| 569 |
+
transition[(stage, prev_role, prev_tag, role)][tag] += 1
|
| 570 |
+
|
| 571 |
+
return {
|
| 572 |
+
"stage": {k: normalize(v) for k, v in stage_role.items()},
|
| 573 |
+
"transition": {k: normalize(v) for k, v in transition.items()},
|
| 574 |
+
"global": {k: normalize(v) for k, v in global_role.items()},
|
| 575 |
+
"start": {k: normalize(v) for k, v in start_role.items()},
|
| 576 |
+
"end": {k: normalize(v) for k, v in end_role.items()},
|
| 577 |
+
}
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def load_stats_file(path):
|
| 581 |
+
obj = load_json(path)
|
| 582 |
+
raw = obj.get("stats", obj)
|
| 583 |
+
return {
|
| 584 |
+
"stage": {parse_stat_key(k): v for k, v in raw.get("stage", {}).items()},
|
| 585 |
+
"transition": {parse_stat_key(k): v for k, v in raw.get("transition", {}).items()},
|
| 586 |
+
"global": raw.get("global", {}),
|
| 587 |
+
"start": raw.get("start", {}),
|
| 588 |
+
"end": raw.get("end", {}),
|
| 589 |
+
}
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def load_model(checkpoint_dir, use_4bit=True):
|
| 593 |
+
bnb_config = None
|
| 594 |
+
if use_4bit:
|
| 595 |
+
bnb_config = BitsAndBytesConfig(
|
| 596 |
+
load_in_4bit=True,
|
| 597 |
+
bnb_4bit_quant_type="nf4",
|
| 598 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL_ID, trust_remote_code=True)
|
| 602 |
+
if tokenizer.pad_token is None:
|
| 603 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 604 |
+
|
| 605 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
| 606 |
+
BASE_MODEL_ID,
|
| 607 |
+
quantization_config=bnb_config,
|
| 608 |
+
device_map="auto",
|
| 609 |
+
trust_remote_code=True,
|
| 610 |
+
)
|
| 611 |
+
model = PeftModel.from_pretrained(base_model, checkpoint_dir)
|
| 612 |
+
model.eval()
|
| 613 |
+
return tokenizer, model
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def batch_conditional_lm_scores(model, tokenizer, prompt, candidates, max_length):
|
| 617 |
+
prefix_ids = tokenizer(prompt, add_special_tokens=False)["input_ids"]
|
| 618 |
+
texts = [prompt + " " + candidate for candidate in candidates]
|
| 619 |
+
enc = tokenizer(
|
| 620 |
+
texts,
|
| 621 |
+
return_tensors="pt",
|
| 622 |
+
add_special_tokens=False,
|
| 623 |
+
truncation=True,
|
| 624 |
+
max_length=max_length,
|
| 625 |
+
padding=True,
|
| 626 |
+
)
|
| 627 |
+
input_ids = enc["input_ids"].to(model.device)
|
| 628 |
+
attention_mask = enc["attention_mask"].to(model.device)
|
| 629 |
+
|
| 630 |
+
with torch.inference_mode():
|
| 631 |
+
outputs = model(input_ids=input_ids, attention_mask=attention_mask)
|
| 632 |
+
|
| 633 |
+
logits = outputs.logits[:, :-1, :]
|
| 634 |
+
labels = input_ids[:, 1:]
|
| 635 |
+
mask = attention_mask[:, 1:].float()
|
| 636 |
+
log_probs = F.log_softmax(logits, dim=-1)
|
| 637 |
+
selected = log_probs.gather(2, labels.unsqueeze(-1)).squeeze(-1)
|
| 638 |
+
|
| 639 |
+
start = max(0, min(selected.shape[1] - 1, len(prefix_ids) - 1))
|
| 640 |
+
candidate_mask = torch.zeros_like(mask)
|
| 641 |
+
candidate_mask[:, start:] = mask[:, start:]
|
| 642 |
+
scores = (selected * candidate_mask).sum(dim=1) / candidate_mask.sum(dim=1).clamp_min(1.0)
|
| 643 |
+
|
| 644 |
+
out = scores.detach().cpu().tolist()
|
| 645 |
+
del outputs
|
| 646 |
+
return out
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def candidate_tags(role, step, total, history, stats, features):
|
| 650 |
+
stage = get_stage(step, total)
|
| 651 |
+
base = COUNSELOR_TAGS if role == "counselor" else CLIENT_TAGS
|
| 652 |
+
stat_tags = set(stats["stage"].get((stage, role), {}).keys())
|
| 653 |
+
stat_tags.update(stats["global"].get(role, {}).keys())
|
| 654 |
+
tags = [tag for tag in base if tag in stat_tags or tag in base]
|
| 655 |
+
return [tag for tag in tags if is_allowed(tag, role, step, total, history, features)]
|
| 656 |
+
|
| 657 |
+
|
| 658 |
+
def choose_candidate(scored, rng, temperature, top_k, top_p, deterministic_gap):
|
| 659 |
+
scored = sorted(scored, key=lambda x: x["score"], reverse=True)
|
| 660 |
+
if not scored:
|
| 661 |
+
return None, []
|
| 662 |
+
|
| 663 |
+
gap = scored[0]["score"] - scored[1]["score"] if len(scored) > 1 else float("inf")
|
| 664 |
+
if gap > deterministic_gap:
|
| 665 |
+
return scored[0], scored[:top_k]
|
| 666 |
+
|
| 667 |
+
pool = scored[: max(1, min(top_k, len(scored)))]
|
| 668 |
+
raw = torch.tensor([x["score"] for x in pool], dtype=torch.float32)
|
| 669 |
+
probs = torch.softmax(raw / max(temperature, 1e-4), dim=0).tolist()
|
| 670 |
+
|
| 671 |
+
ranked = sorted(zip(pool, probs), key=lambda x: x[1], reverse=True)
|
| 672 |
+
kept = []
|
| 673 |
+
acc = 0.0
|
| 674 |
+
for item, prob in ranked:
|
| 675 |
+
kept.append((item, prob))
|
| 676 |
+
acc += prob
|
| 677 |
+
if acc >= top_p:
|
| 678 |
+
break
|
| 679 |
+
|
| 680 |
+
total = sum(prob for _, prob in kept)
|
| 681 |
+
pick = rng.random() * total
|
| 682 |
+
acc = 0.0
|
| 683 |
+
for item, prob in kept:
|
| 684 |
+
acc += prob
|
| 685 |
+
if pick <= acc:
|
| 686 |
+
return item, pool
|
| 687 |
+
return kept[-1][0], pool
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
def finalize_history(history):
|
| 691 |
+
last_role, _ = parse_tag(history[-1])
|
| 692 |
+
if last_role == "counselor":
|
| 693 |
+
history.append("client:[Thanking]")
|
| 694 |
+
history.append("counselor:[Greeting]")
|
| 695 |
+
else:
|
| 696 |
+
history.append("counselor:[Affirm]")
|
| 697 |
+
history.append("client:[Thanking]")
|
| 698 |
+
history.append("counselor:[Greeting]")
|
| 699 |
+
return history
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
def generate_trajectory(item, tokenizer, model, stats, args, sample_index):
|
| 703 |
+
dialogue_text = render_dialogue(item, max_chars=args.dialogue_chars)
|
| 704 |
+
features = text_features(item, dialogue_text)
|
| 705 |
+
target_len = dynamic_target_len(features, args.min_len, args.max_len)
|
| 706 |
+
|
| 707 |
+
rng_seed = args.seed + sample_index * 1009 + sum(ord(c) for c in str(item.get("id", "")))
|
| 708 |
+
rng = random.Random(rng_seed)
|
| 709 |
+
|
| 710 |
+
history = ["counselor:[Greeting]", "client:[Greeting]"]
|
| 711 |
+
role = "counselor"
|
| 712 |
+
trace = []
|
| 713 |
+
|
| 714 |
+
for step in range(2, target_len - 2):
|
| 715 |
+
stage = get_stage(step, target_len)
|
| 716 |
+
prompt = build_prompt(history, dialogue_text, item, features)
|
| 717 |
+
|
| 718 |
+
prev_role, prev_tag = parse_tag(history[-1])
|
| 719 |
+
tags = candidate_tags(role, step, target_len, history, stats, features)
|
| 720 |
+
if not tags:
|
| 721 |
+
tags = ["Other"]
|
| 722 |
+
|
| 723 |
+
candidates = [f"{role}:[{tag}]" for tag in tags]
|
| 724 |
+
lm_scores = batch_conditional_lm_scores(model, tokenizer, prompt, candidates, args.max_length)
|
| 725 |
+
|
| 726 |
+
scored = []
|
| 727 |
+
for tag, candidate, lm in zip(tags, candidates, lm_scores):
|
| 728 |
+
s = safe_log(stats["stage"].get((stage, role), {}).get(tag, 1e-6))
|
| 729 |
+
g = safe_log(stats["global"].get(role, {}).get(tag, 1e-6))
|
| 730 |
+
t = safe_log(stats["transition"].get((stage, prev_role, prev_tag, role), {}).get(tag, 1e-6))
|
| 731 |
+
rep = repetition_penalty(tag, history, role)
|
| 732 |
+
div = diversity_bonus(tag, history, role)
|
| 733 |
+
cb = content_bias(tag, role, features, step, target_len)
|
| 734 |
+
pb = phase_bias(tag, role, step, target_len)
|
| 735 |
+
|
| 736 |
+
score = (
|
| 737 |
+
args.w_lm * lm
|
| 738 |
+
+ args.w_stage * s
|
| 739 |
+
+ args.w_trans * t
|
| 740 |
+
+ args.w_global * g
|
| 741 |
+
- args.w_repeat * rep
|
| 742 |
+
+ args.w_diversity * div
|
| 743 |
+
+ args.w_content * cb
|
| 744 |
+
+ args.w_phase * pb
|
| 745 |
+
)
|
| 746 |
+
scored.append({
|
| 747 |
+
"candidate": candidate,
|
| 748 |
+
"tag": tag,
|
| 749 |
+
"score": score,
|
| 750 |
+
"lm": lm,
|
| 751 |
+
"content": cb,
|
| 752 |
+
"phase": pb,
|
| 753 |
+
"repeat": rep,
|
| 754 |
+
})
|
| 755 |
+
|
| 756 |
+
best, pool = choose_candidate(
|
| 757 |
+
scored,
|
| 758 |
+
rng=rng,
|
| 759 |
+
temperature=args.temperature,
|
| 760 |
+
top_k=args.top_k,
|
| 761 |
+
top_p=args.top_p,
|
| 762 |
+
deterministic_gap=args.deterministic_gap,
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
history.append(best["candidate"])
|
| 766 |
+
if args.keep_trace:
|
| 767 |
+
trace.append({
|
| 768 |
+
"step": step,
|
| 769 |
+
"role": role,
|
| 770 |
+
"chosen": best,
|
| 771 |
+
"top": pool[: min(5, len(pool))],
|
| 772 |
+
})
|
| 773 |
+
|
| 774 |
+
role = "client" if role == "counselor" else "counselor"
|
| 775 |
+
|
| 776 |
+
history = finalize_history(history)
|
| 777 |
+
|
| 778 |
+
tag_counts = Counter(tags_only(history))
|
| 779 |
+
role_counts = {
|
| 780 |
+
"client": Counter(tags_only(history, "client")),
|
| 781 |
+
"counselor": Counter(tags_only(history, "counselor")),
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
result = {
|
| 785 |
+
"index": sample_index,
|
| 786 |
+
"id": item.get("id", item.get("dialogue_id", str(sample_index))),
|
| 787 |
+
"source_dataset": item.get("source_dataset", ""),
|
| 788 |
+
"source_id": item.get("source_id", ""),
|
| 789 |
+
"topic": item.get("topic", ""),
|
| 790 |
+
"topic_zh": item.get("topic_zh", ""),
|
| 791 |
+
"turn_count": item.get("turn_count", None),
|
| 792 |
+
"input": dialogue_text,
|
| 793 |
+
"features": features,
|
| 794 |
+
"topic_group": topic_group(features),
|
| 795 |
+
"target_len": target_len,
|
| 796 |
+
"output": " ".join(history),
|
| 797 |
+
"tag_counts": dict(tag_counts),
|
| 798 |
+
"role_tag_counts": {
|
| 799 |
+
"client": dict(role_counts["client"]),
|
| 800 |
+
"counselor": dict(role_counts["counselor"]),
|
| 801 |
+
},
|
| 802 |
+
}
|
| 803 |
+
if args.keep_trace:
|
| 804 |
+
result["trace"] = trace
|
| 805 |
+
return result
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def output_path(args):
|
| 809 |
+
name = args.output_name
|
| 810 |
+
if not name:
|
| 811 |
+
stamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 812 |
+
count = "all" if args.limit is None else str(args.limit)
|
| 813 |
+
name = f"da_trajectories_offset{args.offset}_n{count}_{stamp}.jsonl"
|
| 814 |
+
return Path(args.output_dir) / name
|
| 815 |
+
|
| 816 |
+
|
| 817 |
+
def parse_args():
|
| 818 |
+
parser = argparse.ArgumentParser()
|
| 819 |
+
parser.add_argument("--input-file", default=INPUT_FILE)
|
| 820 |
+
parser.add_argument("--annotated-dir", default=ANNOTATED_DIR)
|
| 821 |
+
parser.add_argument("--checkpoint-dir", default=CHECKPOINT_DIR)
|
| 822 |
+
parser.add_argument("--output-dir", default=OUTPUT_DIR)
|
| 823 |
+
parser.add_argument("--output-name", default="")
|
| 824 |
+
parser.add_argument("--stats-file", default=STATS_FILE)
|
| 825 |
+
parser.add_argument("--offset", type=int, default=0)
|
| 826 |
+
parser.add_argument("--limit", type=int, default=20)
|
| 827 |
+
parser.add_argument("--spread", action="store_true")
|
| 828 |
+
parser.add_argument("--num-shards", type=int, default=1)
|
| 829 |
+
parser.add_argument("--shard-id", type=int, default=0)
|
| 830 |
+
parser.add_argument("--seed", type=int, default=20260703)
|
| 831 |
+
parser.add_argument("--min-len", type=int, default=64)
|
| 832 |
+
parser.add_argument("--max-len", type=int, default=92)
|
| 833 |
+
parser.add_argument("--dialogue-chars", type=int, default=900)
|
| 834 |
+
parser.add_argument("--max-length", type=int, default=2048)
|
| 835 |
+
parser.add_argument("--top-k", type=int, default=5)
|
| 836 |
+
parser.add_argument("--top-p", type=float, default=0.88)
|
| 837 |
+
parser.add_argument("--temperature", type=float, default=0.64)
|
| 838 |
+
parser.add_argument("--deterministic-gap", type=float, default=0.48)
|
| 839 |
+
parser.add_argument("--w-lm", type=float, default=4.0)
|
| 840 |
+
parser.add_argument("--w-stage", type=float, default=0.08)
|
| 841 |
+
parser.add_argument("--w-trans", type=float, default=0.12)
|
| 842 |
+
parser.add_argument("--w-global", type=float, default=0.01)
|
| 843 |
+
parser.add_argument("--w-repeat", type=float, default=1.85)
|
| 844 |
+
parser.add_argument("--w-diversity", type=float, default=0.52)
|
| 845 |
+
parser.add_argument("--w-content", type=float, default=1.18)
|
| 846 |
+
parser.add_argument("--w-phase", type=float, default=0.50)
|
| 847 |
+
parser.add_argument("--no-4bit", action="store_true")
|
| 848 |
+
parser.add_argument("--keep-trace", action="store_true")
|
| 849 |
+
parser.add_argument("--resume", action="store_true")
|
| 850 |
+
return parser.parse_args()
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
def main():
|
| 854 |
+
args = parse_args()
|
| 855 |
+
if args.limit is not None and args.limit <= 0:
|
| 856 |
+
args.limit = None
|
| 857 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 858 |
+
out_path = output_path(args)
|
| 859 |
+
summary_path = out_path.with_suffix(".summary.json")
|
| 860 |
+
config_path = out_path.with_suffix(".config.json")
|
| 861 |
+
|
| 862 |
+
save_json(config_path, vars(args))
|
| 863 |
+
|
| 864 |
+
done_ids = set()
|
| 865 |
+
if args.resume and out_path.exists():
|
| 866 |
+
with open(out_path, "r", encoding="utf-8") as f:
|
| 867 |
+
for line in f:
|
| 868 |
+
if line.strip():
|
| 869 |
+
done_ids.add(json.loads(line).get("id"))
|
| 870 |
+
print(f"[INFO] resume enabled, loaded done ids: {len(done_ids)}", flush=True)
|
| 871 |
+
elif out_path.exists():
|
| 872 |
+
out_path.unlink()
|
| 873 |
+
|
| 874 |
+
data = read_jsonl(args.input_file, limit=args.limit, offset=args.offset, spread=args.spread)
|
| 875 |
+
if args.num_shards > 1:
|
| 876 |
+
if args.shard_id < 0 or args.shard_id >= args.num_shards:
|
| 877 |
+
raise ValueError("--shard-id must be in [0, --num-shards)")
|
| 878 |
+
data = [item for pos, item in enumerate(data) if pos % args.num_shards == args.shard_id]
|
| 879 |
+
print(f"[INFO] loaded input rows: {len(data)}", flush=True)
|
| 880 |
+
print(f"[INFO] output: {out_path}", flush=True)
|
| 881 |
+
|
| 882 |
+
tokenizer, model = load_model(args.checkpoint_dir, use_4bit=not args.no_4bit)
|
| 883 |
+
if args.stats_file and os.path.exists(args.stats_file):
|
| 884 |
+
stats = load_stats_file(args.stats_file)
|
| 885 |
+
print(f"[INFO] loaded stats file: {args.stats_file}", flush=True)
|
| 886 |
+
else:
|
| 887 |
+
stats = build_stats(load_annotated(args.annotated_dir))
|
| 888 |
+
|
| 889 |
+
generated = []
|
| 890 |
+
for local_i, item in enumerate(data):
|
| 891 |
+
sample_index = int(item.get("_global_index", args.offset + local_i))
|
| 892 |
+
item_id = item.get("id", str(sample_index))
|
| 893 |
+
if item_id in done_ids:
|
| 894 |
+
continue
|
| 895 |
+
|
| 896 |
+
print("\n" + "-" * 60, flush=True)
|
| 897 |
+
print(f"[INFO] sample {local_i + 1}/{len(data)} global_index={sample_index} id={item_id}", flush=True)
|
| 898 |
+
result = generate_trajectory(item, tokenizer, model, stats, args, sample_index)
|
| 899 |
+
append_jsonl(out_path, result)
|
| 900 |
+
generated.append(result)
|
| 901 |
+
|
| 902 |
+
print(
|
| 903 |
+
f"[OK] len={result['target_len']} topic={result.get('topic_zh') or result.get('topic')} "
|
| 904 |
+
f"distinct_tags={len(result['tag_counts'])}",
|
| 905 |
+
flush=True,
|
| 906 |
+
)
|
| 907 |
+
print(result["output"], flush=True)
|
| 908 |
+
|
| 909 |
+
lengths = [x["target_len"] for x in generated]
|
| 910 |
+
all_tags = Counter()
|
| 911 |
+
for x in generated:
|
| 912 |
+
all_tags.update(x["tag_counts"])
|
| 913 |
+
|
| 914 |
+
summary = {
|
| 915 |
+
"output": str(out_path),
|
| 916 |
+
"generated": len(generated),
|
| 917 |
+
"offset": args.offset,
|
| 918 |
+
"limit": args.limit,
|
| 919 |
+
"length_min": min(lengths) if lengths else None,
|
| 920 |
+
"length_max": max(lengths) if lengths else None,
|
| 921 |
+
"length_avg": sum(lengths) / len(lengths) if lengths else None,
|
| 922 |
+
"tag_counts": dict(all_tags),
|
| 923 |
+
}
|
| 924 |
+
save_json(summary_path, summary)
|
| 925 |
+
print("\n[INFO] summary:", json.dumps(summary, ensure_ascii=False, indent=2), flush=True)
|
| 926 |
+
|
| 927 |
+
|
| 928 |
+
if __name__ == "__main__":
|
| 929 |
+
main()
|
requirements.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch>=2.5
|
| 2 |
+
transformers>=4.57.6,<5
|
| 3 |
+
peft>=0.17,<1
|
| 4 |
+
accelerate>=1
|
| 5 |
+
bitsandbytes>=0.45
|
| 6 |
+
huggingface_hub>=0.34
|
| 7 |
+
safetensors>=0.5
|
special_tokens_map.json
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"additional_special_tokens": [
|
| 3 |
+
"<|im_start|>",
|
| 4 |
+
"<|im_end|>",
|
| 5 |
+
"<|object_ref_start|>",
|
| 6 |
+
"<|object_ref_end|>",
|
| 7 |
+
"<|box_start|>",
|
| 8 |
+
"<|box_end|>",
|
| 9 |
+
"<|quad_start|>",
|
| 10 |
+
"<|quad_end|>",
|
| 11 |
+
"<|vision_start|>",
|
| 12 |
+
"<|vision_end|>",
|
| 13 |
+
"<|vision_pad|>",
|
| 14 |
+
"<|image_pad|>",
|
| 15 |
+
"<|video_pad|>"
|
| 16 |
+
],
|
| 17 |
+
"eos_token": {
|
| 18 |
+
"content": "<|im_end|>",
|
| 19 |
+
"lstrip": false,
|
| 20 |
+
"normalized": false,
|
| 21 |
+
"rstrip": false,
|
| 22 |
+
"single_word": false
|
| 23 |
+
},
|
| 24 |
+
"pad_token": {
|
| 25 |
+
"content": "<|endoftext|>",
|
| 26 |
+
"lstrip": false,
|
| 27 |
+
"normalized": false,
|
| 28 |
+
"rstrip": false,
|
| 29 |
+
"single_word": false
|
| 30 |
+
}
|
| 31 |
+
}
|
tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4
|
| 3 |
+
size 11422654
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_bos_token": false,
|
| 3 |
+
"add_prefix_space": false,
|
| 4 |
+
"added_tokens_decoder": {
|
| 5 |
+
"151643": {
|
| 6 |
+
"content": "<|endoftext|>",
|
| 7 |
+
"lstrip": false,
|
| 8 |
+
"normalized": false,
|
| 9 |
+
"rstrip": false,
|
| 10 |
+
"single_word": false,
|
| 11 |
+
"special": true
|
| 12 |
+
},
|
| 13 |
+
"151644": {
|
| 14 |
+
"content": "<|im_start|>",
|
| 15 |
+
"lstrip": false,
|
| 16 |
+
"normalized": false,
|
| 17 |
+
"rstrip": false,
|
| 18 |
+
"single_word": false,
|
| 19 |
+
"special": true
|
| 20 |
+
},
|
| 21 |
+
"151645": {
|
| 22 |
+
"content": "<|im_end|>",
|
| 23 |
+
"lstrip": false,
|
| 24 |
+
"normalized": false,
|
| 25 |
+
"rstrip": false,
|
| 26 |
+
"single_word": false,
|
| 27 |
+
"special": true
|
| 28 |
+
},
|
| 29 |
+
"151646": {
|
| 30 |
+
"content": "<|object_ref_start|>",
|
| 31 |
+
"lstrip": false,
|
| 32 |
+
"normalized": false,
|
| 33 |
+
"rstrip": false,
|
| 34 |
+
"single_word": false,
|
| 35 |
+
"special": true
|
| 36 |
+
},
|
| 37 |
+
"151647": {
|
| 38 |
+
"content": "<|object_ref_end|>",
|
| 39 |
+
"lstrip": false,
|
| 40 |
+
"normalized": false,
|
| 41 |
+
"rstrip": false,
|
| 42 |
+
"single_word": false,
|
| 43 |
+
"special": true
|
| 44 |
+
},
|
| 45 |
+
"151648": {
|
| 46 |
+
"content": "<|box_start|>",
|
| 47 |
+
"lstrip": false,
|
| 48 |
+
"normalized": false,
|
| 49 |
+
"rstrip": false,
|
| 50 |
+
"single_word": false,
|
| 51 |
+
"special": true
|
| 52 |
+
},
|
| 53 |
+
"151649": {
|
| 54 |
+
"content": "<|box_end|>",
|
| 55 |
+
"lstrip": false,
|
| 56 |
+
"normalized": false,
|
| 57 |
+
"rstrip": false,
|
| 58 |
+
"single_word": false,
|
| 59 |
+
"special": true
|
| 60 |
+
},
|
| 61 |
+
"151650": {
|
| 62 |
+
"content": "<|quad_start|>",
|
| 63 |
+
"lstrip": false,
|
| 64 |
+
"normalized": false,
|
| 65 |
+
"rstrip": false,
|
| 66 |
+
"single_word": false,
|
| 67 |
+
"special": true
|
| 68 |
+
},
|
| 69 |
+
"151651": {
|
| 70 |
+
"content": "<|quad_end|>",
|
| 71 |
+
"lstrip": false,
|
| 72 |
+
"normalized": false,
|
| 73 |
+
"rstrip": false,
|
| 74 |
+
"single_word": false,
|
| 75 |
+
"special": true
|
| 76 |
+
},
|
| 77 |
+
"151652": {
|
| 78 |
+
"content": "<|vision_start|>",
|
| 79 |
+
"lstrip": false,
|
| 80 |
+
"normalized": false,
|
| 81 |
+
"rstrip": false,
|
| 82 |
+
"single_word": false,
|
| 83 |
+
"special": true
|
| 84 |
+
},
|
| 85 |
+
"151653": {
|
| 86 |
+
"content": "<|vision_end|>",
|
| 87 |
+
"lstrip": false,
|
| 88 |
+
"normalized": false,
|
| 89 |
+
"rstrip": false,
|
| 90 |
+
"single_word": false,
|
| 91 |
+
"special": true
|
| 92 |
+
},
|
| 93 |
+
"151654": {
|
| 94 |
+
"content": "<|vision_pad|>",
|
| 95 |
+
"lstrip": false,
|
| 96 |
+
"normalized": false,
|
| 97 |
+
"rstrip": false,
|
| 98 |
+
"single_word": false,
|
| 99 |
+
"special": true
|
| 100 |
+
},
|
| 101 |
+
"151655": {
|
| 102 |
+
"content": "<|image_pad|>",
|
| 103 |
+
"lstrip": false,
|
| 104 |
+
"normalized": false,
|
| 105 |
+
"rstrip": false,
|
| 106 |
+
"single_word": false,
|
| 107 |
+
"special": true
|
| 108 |
+
},
|
| 109 |
+
"151656": {
|
| 110 |
+
"content": "<|video_pad|>",
|
| 111 |
+
"lstrip": false,
|
| 112 |
+
"normalized": false,
|
| 113 |
+
"rstrip": false,
|
| 114 |
+
"single_word": false,
|
| 115 |
+
"special": true
|
| 116 |
+
},
|
| 117 |
+
"151657": {
|
| 118 |
+
"content": "<tool_call>",
|
| 119 |
+
"lstrip": false,
|
| 120 |
+
"normalized": false,
|
| 121 |
+
"rstrip": false,
|
| 122 |
+
"single_word": false,
|
| 123 |
+
"special": false
|
| 124 |
+
},
|
| 125 |
+
"151658": {
|
| 126 |
+
"content": "</tool_call>",
|
| 127 |
+
"lstrip": false,
|
| 128 |
+
"normalized": false,
|
| 129 |
+
"rstrip": false,
|
| 130 |
+
"single_word": false,
|
| 131 |
+
"special": false
|
| 132 |
+
},
|
| 133 |
+
"151659": {
|
| 134 |
+
"content": "<|fim_prefix|>",
|
| 135 |
+
"lstrip": false,
|
| 136 |
+
"normalized": false,
|
| 137 |
+
"rstrip": false,
|
| 138 |
+
"single_word": false,
|
| 139 |
+
"special": false
|
| 140 |
+
},
|
| 141 |
+
"151660": {
|
| 142 |
+
"content": "<|fim_middle|>",
|
| 143 |
+
"lstrip": false,
|
| 144 |
+
"normalized": false,
|
| 145 |
+
"rstrip": false,
|
| 146 |
+
"single_word": false,
|
| 147 |
+
"special": false
|
| 148 |
+
},
|
| 149 |
+
"151661": {
|
| 150 |
+
"content": "<|fim_suffix|>",
|
| 151 |
+
"lstrip": false,
|
| 152 |
+
"normalized": false,
|
| 153 |
+
"rstrip": false,
|
| 154 |
+
"single_word": false,
|
| 155 |
+
"special": false
|
| 156 |
+
},
|
| 157 |
+
"151662": {
|
| 158 |
+
"content": "<|fim_pad|>",
|
| 159 |
+
"lstrip": false,
|
| 160 |
+
"normalized": false,
|
| 161 |
+
"rstrip": false,
|
| 162 |
+
"single_word": false,
|
| 163 |
+
"special": false
|
| 164 |
+
},
|
| 165 |
+
"151663": {
|
| 166 |
+
"content": "<|repo_name|>",
|
| 167 |
+
"lstrip": false,
|
| 168 |
+
"normalized": false,
|
| 169 |
+
"rstrip": false,
|
| 170 |
+
"single_word": false,
|
| 171 |
+
"special": false
|
| 172 |
+
},
|
| 173 |
+
"151664": {
|
| 174 |
+
"content": "<|file_sep|>",
|
| 175 |
+
"lstrip": false,
|
| 176 |
+
"normalized": false,
|
| 177 |
+
"rstrip": false,
|
| 178 |
+
"single_word": false,
|
| 179 |
+
"special": false
|
| 180 |
+
},
|
| 181 |
+
"151665": {
|
| 182 |
+
"content": "<tool_response>",
|
| 183 |
+
"lstrip": false,
|
| 184 |
+
"normalized": false,
|
| 185 |
+
"rstrip": false,
|
| 186 |
+
"single_word": false,
|
| 187 |
+
"special": false
|
| 188 |
+
},
|
| 189 |
+
"151666": {
|
| 190 |
+
"content": "</tool_response>",
|
| 191 |
+
"lstrip": false,
|
| 192 |
+
"normalized": false,
|
| 193 |
+
"rstrip": false,
|
| 194 |
+
"single_word": false,
|
| 195 |
+
"special": false
|
| 196 |
+
},
|
| 197 |
+
"151667": {
|
| 198 |
+
"content": "<think>",
|
| 199 |
+
"lstrip": false,
|
| 200 |
+
"normalized": false,
|
| 201 |
+
"rstrip": false,
|
| 202 |
+
"single_word": false,
|
| 203 |
+
"special": false
|
| 204 |
+
},
|
| 205 |
+
"151668": {
|
| 206 |
+
"content": "</think>",
|
| 207 |
+
"lstrip": false,
|
| 208 |
+
"normalized": false,
|
| 209 |
+
"rstrip": false,
|
| 210 |
+
"single_word": false,
|
| 211 |
+
"special": false
|
| 212 |
+
}
|
| 213 |
+
},
|
| 214 |
+
"additional_special_tokens": [
|
| 215 |
+
"<|im_start|>",
|
| 216 |
+
"<|im_end|>",
|
| 217 |
+
"<|object_ref_start|>",
|
| 218 |
+
"<|object_ref_end|>",
|
| 219 |
+
"<|box_start|>",
|
| 220 |
+
"<|box_end|>",
|
| 221 |
+
"<|quad_start|>",
|
| 222 |
+
"<|quad_end|>",
|
| 223 |
+
"<|vision_start|>",
|
| 224 |
+
"<|vision_end|>",
|
| 225 |
+
"<|vision_pad|>",
|
| 226 |
+
"<|image_pad|>",
|
| 227 |
+
"<|video_pad|>"
|
| 228 |
+
],
|
| 229 |
+
"bos_token": null,
|
| 230 |
+
"clean_up_tokenization_spaces": false,
|
| 231 |
+
"eos_token": "<|im_end|>",
|
| 232 |
+
"errors": "replace",
|
| 233 |
+
"extra_special_tokens": {},
|
| 234 |
+
"model_max_length": 131072,
|
| 235 |
+
"pad_token": "<|endoftext|>",
|
| 236 |
+
"split_special_tokens": false,
|
| 237 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 238 |
+
"unk_token": null
|
| 239 |
+
}
|
validation.json
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"adapter_sha256": "f9cf6a1654d91c341678d2464098bc26c27bc58404cd57bc0a6f227d50bb6631",
|
| 3 |
+
"matches_selected_checkpoint_and_final_model": true,
|
| 4 |
+
"adapter_tensors": 504,
|
| 5 |
+
"adapter_parameters": 21823488,
|
| 6 |
+
"all_tensors_finite": true,
|
| 7 |
+
"model_card_and_python_syntax_validated": true,
|
| 8 |
+
"planning_functions_match_original": true,
|
| 9 |
+
"gpu_smoke_test": {
|
| 10 |
+
"passed": true,
|
| 11 |
+
"input": "examples/input.jsonl",
|
| 12 |
+
"output": "examples/trajectory.json",
|
| 13 |
+
"target_length_budget": 8,
|
| 14 |
+
"realized_acts": 9,
|
| 15 |
+
"max_input_length": 512,
|
| 16 |
+
"quantization": "NF4",
|
| 17 |
+
"torch": "2.5.1+cu121",
|
| 18 |
+
"transformers": "4.57.6",
|
| 19 |
+
"peft": "0.17.1",
|
| 20 |
+
"bitsandbytes": "0.49.2"
|
| 21 |
+
}
|
| 22 |
+
}
|
vocab.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|