Compare commits

...

1584 Commits

Author SHA1 Message Date
zhangbo9674
42afde58d5 fix loss bug (#11161) 2025-11-04 14:54:42 +08:00
Shuhao Liang
4e587e2df3 Fix empty usage error of aux-loss-free (#11116) 2025-09-26 14:38:28 +08:00
Shuhao Liang
1b10b5733e Fix FusedRMSLinear backward compute (#11095) 2025-09-23 15:11:51 +08:00
Shuhao Liang
da47d99ec7 Implement auxiliary-loss-free load balancing (#11031) 2025-09-23 15:10:59 +08:00
liuruyan
8d5dead090 fix_fa3_mem (#11033)
* fix_fa3_mem

* update strategy
2025-09-23 15:10:21 +08:00
chen2016013
95438f974e update post norm rc (#11097)
Co-authored-by: zhangbo9674 <zhangbo54@baidu.com>
2025-09-23 15:09:58 +08:00
XiangzheWang
03cf7010cd use key-value to init dataloader (#11067) 2025-09-04 11:41:19 +08:00
Shuhao Liang
9b1c1660b4 Fix post_process_backward calc stream wait (#11063) 2025-09-04 10:14:42 +08:00
liuruyan
349c92f8d1 fix_fa3_bug (#11038) 2025-09-02 11:10:55 +08:00
zhangbo9674
3737315dde best speed (#11023) 2025-08-28 14:47:23 +08:00
liuruyan
5b4855dd1f Add stepped O1 recompute (#11010)
* add_stepped_rc

* polish code

* remove stepevent

* fix bug
2025-08-28 10:01:29 +08:00
liuruyan
79c421f22d Update quant cache (#11007)
* fix

* update quant cache

---------

Co-authored-by: zhangbo9674 <zhangbo54@baidu.com>
2025-08-28 10:01:22 +08:00
hong
17cc8a4763 fix gate prob (#10972)
* fix gate prob

* remove useless code
2025-08-28 09:51:08 +08:00
hong
f83311ac57 optimize cross entropy speed (#11012) 2025-08-27 16:34:58 +08:00
Shuhao Liang
475942a9dc Implement Decoder backward self-overlapping (#11003) 2025-08-27 15:48:03 +08:00
Shuhao Liang
de9c524534 Fix slow convergence issue when enable overlap_p2p_comm (#10992) 2025-08-27 15:34:19 +08:00
hong
76cb4b7cca optimize moe and dense bw split (#11015) 2025-08-26 19:37:45 +08:00
hong
69e9f967d6 optimizer embedding grad speed (#11011) 2025-08-26 17:46:38 +08:00
zhangbo9674
fe9e9f8246 fix bug (#11006) 2025-08-26 15:07:17 +08:00
chen2016013
6e6b373939 CE bug fix (#10999)
* CE bug fix

* Update trainer_callback.py

* CE bug fix

* Update modeling.py

---------

Co-authored-by: zhangbo9674 <zhangbo54@baidu.com>
2025-08-26 10:24:00 +08:00
liuruyan
7ce548e107 Fa3 recompute (#10994)
* fix

* add fa3 rc

---------

Co-authored-by: zhangbo9674 <zhangbo54@baidu.com>
2025-08-25 17:09:56 +08:00
liuruyan
1ab02cd8e4 quant transpost disable (#10987) 2025-08-25 17:09:47 +08:00
zhangbo9674
fb6d8af3c8 fix bug (#10995) 2025-08-25 14:04:30 +08:00
zhangbo9674
a3e234492d support load hf ckpt (#10976) 2025-08-22 15:20:15 +08:00
zhangbo9674
73f451c391 fix bug (#10986) 2025-08-21 17:51:55 +08:00
zhangbo9674
e63b1e727a fix (#10977) 2025-08-21 16:29:51 +08:00
hong
740f4718d3 fix numel bug (#10979) 2025-08-21 00:22:54 +08:00
hong
45b9caa72a opti lm head backward perf (#10975) 2025-08-20 19:53:00 +08:00
hong
fb22a9fa1a yarn rope use fp32 (#10973) 2025-08-20 19:51:26 +08:00
Shuhao Liang
0efb20228b Implement overlapping of MTP Decoder Layer (#10963) 2025-08-20 19:51:06 +08:00
zhangbo9674
21d7d20a08 fix (#10970) 2025-08-20 19:38:34 +08:00
Shuhao Liang
4d1b2a9f01 Dense node supports send_mtp_embed (#10967) 2025-08-19 19:39:37 +08:00
liuruyan
6e0febaee3 add quant cache (#10969) 2025-08-19 19:33:39 +08:00
liuruyan
0e9051a29f Add sequence and output dimension subbatch (#10947)
* add subbatch

* remove backward_dw

* deal 0 size

* fix subbatch bug

* fix cuda 700

* polish code

* fix nan
2025-08-19 19:27:54 +08:00
risemeup1
6a3fb150a8 not recomput o1 (#10953)
* not recomput o1

* not recomput o1

* not recomput o1

* not recomput o1

* not recomput o1

* fix
2025-08-16 19:55:47 +08:00
Shuhao Liang
e91f55aa17 Implement overlapping of Dense and MoE DecoderLayers (#10959) 2025-08-16 15:25:03 +08:00
hong
842684706b fix fa3 scale bug (#10961) 2025-08-16 10:30:56 +08:00
chen2016013
8cb171231f save args for rms_norm output (#10930)
* add bwd

* fix bug

* Update modeling.py

* Update modeling_pp.py

* Update modeling_pp.py

* Update fp8_utils.py

---------

Co-authored-by: zhangbo9674 <zhangbo54@baidu.com>
2025-08-14 20:37:15 +08:00
Shuhao Liang
114bee101a Add use of fused_partial_rope op (#10942) 2025-08-14 15:46:53 +08:00
hong
6964fc80c9 mlp use add to (#10945)
Co-authored-by: xuexixi <xuexixi@baidu.com>
2025-08-13 21:08:07 +08:00
zhangbo9674
ba1cc7bfa5 fix bug (#10940) 2025-08-13 15:14:37 +08:00
zhangbo9674
72dc153e69 add final config (#10933) 2025-08-12 16:20:28 +08:00
hong
38751cb3d6 fix mlp bw split bug (#10932)
Co-authored-by: phlrain <phliuhonguy@126.com>
2025-08-12 10:45:11 +08:00
hong
e661a3e3c9 optimize mlp bw split (#10931)
Co-authored-by: phlrain <phliuhonguy@126.com>
2025-08-12 10:14:56 +08:00
hong
b5ebfdd50b fix unverlap bw split (#10928)
Co-authored-by: phlrain <phliuhonguy@126.com>
2025-08-11 20:23:51 +08:00
zhangbo9674
542c1b58ae Add config control for quant cache (#10926)
* add config

* refine
2025-08-11 15:43:23 +08:00
hong
b93fda90ae fp8_quant_cache_and_using_fp8_gemm (#10923)
* update

* update modeling and modeling_pp

* add shared export fp8 quant cache

* polish code

---------

Co-authored-by: phlrain <phiuhongyu@126.com>
2025-08-11 11:19:08 +08:00
hong
9d1130bfe5 support bw split (#10915)
* support bw split

* fix bug

* polish code
2025-08-09 20:43:42 +08:00
zhangbo9674
e911a76bc5 Support fp8 weight quant cache (#10914)
* support fp8 weight quant cache

* fix bug

* fix confilct
2025-08-08 00:13:34 +08:00
zhangbo9674
ef47c116f8 Support magic send for mtp (#10916)
* support fp8 weight quant cache

* fix bug

* fix confilct

* support magic send
2025-08-08 00:13:26 +08:00
chen2016013
87fa744144 Fix mtp bug when send_mtp_embed=True (#10909)
* Fix mtp bug

* fix mtp bug

* Update fp8_utils.py

* fix mtp bug

---------

Co-authored-by: root <root@yqlcc01-bbc-yqonlinea-com-1567437.yqlcc01.baidu.com>
2025-08-07 11:44:27 +08:00
liuruyan
2ff16f8558 fix 0 size bug (#10906) 2025-08-05 11:16:33 +08:00
risemeup1
48e3e3280c Fix conflict (#10902)
* refine fp8_utils

* refine fp8_utils

* refine fp8_utils

* fix

* fix after review

* fix

* fix

* fix

* fix

* fix
2025-08-01 10:48:47 +08:00
zhangbo9674
a3b6c2cb1b fix conflict (#10900) 2025-07-31 16:24:09 +08:00
HU Shenwei
17089c8c42 [Test Config] Add default test config for N1C8 dsv3 (#10898)
* feat(config): add default N1C8 dsv3 config

* feat(config): add default N1C8 dsv3 config
2025-07-31 16:24:02 +08:00
hong
ac58fa403a support send recv overlap (#10853)
* support send recv overlap

* update

* update

* update

* update

* fix bug
2025-07-31 16:10:38 +08:00
liuruyan
0e4be4d140 Add adaptived recomptue of o1 (#10891)
* add adaptived recomptue of O1

* add adaptived recomptue ratio

* add adaptived recomptue ratio
2025-07-31 16:10:22 +08:00
risemeup1
c7b0059a19 refine fp8_utils (#10848)
* refine fp8_utils

* refine fp8_utils

* refine fp8_utils

* fix

* fix after review

* fix

* fix

* fix

* fix
2025-07-31 16:10:11 +08:00
zhangbo9674
8a0986e36d support wgrad gemm (#10892) 2025-07-29 10:32:45 +08:00
chen2016013
ba94cdc465 update deep_gemm (#10754)
* update deep_gemm

* delete print

* Update setup.py

* add test_jit

* refine

* refine code

* Update compiler.py

* Update gemm.py

* Update m_grouped_gemm.py

* Update wgrad_gemm.py

* add arg sms
2025-07-28 19:18:42 +08:00
liuruyan
884ca21724 Balance_gate & O1 recompute configuration (#10883)
* balance_gate

* add configuration of o1 rc nums
2025-07-28 14:52:23 +08:00
Yuang Liu
6d58c7cbc7 fix aadiff (#10874) 2025-07-22 12:18:10 +08:00
hong
b8faf6685d support send recv overlap pre code (#10872) 2025-07-21 17:38:39 +08:00
chen2016013
b099c8896e Fix overlap stream bug (#10873)
Co-authored-by: phlrain <phliuhongyu@126.com>
2025-07-21 15:01:41 +08:00
chen2016013
e1efedd178 fix pre-dispatch bug (#10869)
Co-authored-by: phlrain <phliuhongyu@126.com>
2025-07-21 14:47:48 +08:00
risemeup1
b4b05877d2 fix not overlap bug (#10864) 2025-07-18 17:22:17 +08:00
zhangbo9674
75e51dfbb7 fix bug (#10862) 2025-07-17 21:36:06 +08:00
chen2016013
33e01f1e9a replace custom ops with paddle ops (#10857)
Co-authored-by: phlrain <phliuhongyu@126.com>
2025-07-17 19:10:25 +08:00
zhangbo9674
6cd171efb3 allco on comm (#10859) 2025-07-17 17:17:43 +08:00
zhangbo9674
3fee1505c9 fix bug (#10856) 2025-07-17 15:54:15 +08:00
liuruyan
831d818c04 add recompute of postnorm in pp (#10849) 2025-07-16 18:07:07 +08:00
zhangbo9674
c52eb6fc1b Refine fp8 quant and combine backward overlap (#10830)
* refine

* refine

* refine
2025-07-16 10:36:40 +08:00
liuruyan
c9ec40aea1 Add post norm recompute. (#10824)
* Add post norm recompute.

* fix assert

* fix bug
2025-07-15 18:23:42 +08:00
zhangbo9674
ae4f27b2a2 support quant return transpose only (#10833)
* support quant tanrspose only

* fix bug
2025-07-10 11:32:59 +08:00
hong
5ccd5a8187 fix dual pp event wait bug (#10829) 2025-07-09 17:53:44 +08:00
hong
8a5ea21f6c support bw split (#10823) 2025-07-07 15:49:58 +08:00
chen2016013
bdab8887ce support dispatch both bf16 & fp8 (#10817) 2025-07-04 22:26:39 +08:00
zhangbo9674
b5b94e5597 delete add (#10813) 2025-07-04 14:40:36 +08:00
hong
dad134e4e5 optimize scale transpose (#10810) 2025-07-04 10:12:51 +08:00
hong
be62526018 optimizer_dual_pp_post_node_memory (#10806) 2025-07-03 17:52:07 +08:00
hong
fe5e87ae00 lock gemm sm 112 (#10805) 2025-07-03 17:03:57 +08:00
zhangbo9674
e3f1b627d7 Add fp8 opt config for dualpipe (#10804)
* add fp8 control for dualpipe

* change kitchen api to padddle api
2025-07-03 16:10:04 +08:00
sneaxiy
ff837631ea add expert num 32 (#10802) 2025-07-03 13:07:25 +08:00
zhangbo9674
b9db2c1602 Refine fp8 node (#10798)
* refine fp8 node

* refine fp8 node

* fix bug

* fix

* fix bug

* opt tma
2025-07-03 12:03:57 +08:00
sneaxiy
d1475574d1 Support expert number 16 in FP8 operators (#10799)
* support expert number 16

* fix bug
2025-07-03 10:45:13 +08:00
chen2016013
82907917e3 Adapt dispatch_quant_node to fp8 fusion moe node (#10794)
* refine fp8 code

* fix bug

* fix bug

* reine mem

* fix

* refine meme

* add fuse pass

* add fuse config

* refine tma

* add cinn decorate

* refine

* adapt modeling_pp to fp8 fusion moe node

* update

---------

Co-authored-by: zhangbo9674 <zhangbo54@baidu.com>
2025-07-02 14:55:37 +08:00
hong
200e59b1a9 optimize dual pp memory (#10787)
* optimizer dual pp memory

* add config
2025-07-02 10:16:12 +08:00
Zhaowu Pan
e7a2b02b0d Fix comp and 0size problems. (#10773)
Co-authored-by: zhangyuqin <zhangyuqin@baidu.com>
2025-06-25 19:01:38 +08:00
zhangbo9674
dbda77a815 Change custom op to paddle api (#10748)
* change api

* fix bug

* fix bug

* fix
2025-06-25 10:04:44 +08:00
sneaxiy
c466d2ee7b Add expert subbatch & inplace fused_swiglu_probs_bwd ops (#10757) 2025-06-23 23:45:06 +08:00
Zhaowu Pan
382fa86545 fix 0size problem in unzip-zip op (#10755)
Co-authored-by: zhangyuqin <zhangyuqin@baidu.com>
2025-06-20 11:52:56 +08:00
Zhaowu Pan
7ecb1dcc09 fix big_tensor issue in swiglu_probs_bwd (#10735) 2025-06-13 16:50:08 +08:00
Shuhao Liang
4a872d4cbc Add cuda stream for fused quant kernel (#10716) 2025-06-12 22:17:47 +08:00
zhangbo9674
80f18ee4ba refine fp8 code (#10669)
* refine fp8 code

* fix bug

* fix bug

* reine mem

* fix

* refine meme

* add fuse pass

* add fuse config

* refine tma

* add cinn decorate

* refine
2025-06-09 14:26:04 +08:00
Zhaowu Pan
42b72cd3fe fix grid y problem in spaq (#10709) 2025-06-05 20:22:48 +08:00
Zhaowu Pan
4a23f8beae Disable fast math due to precision issue (#10697)
* Disable fast math for fused precision isssue.

* Disable TDU fm.
2025-06-04 13:20:34 +08:00
Zhaowu Pan
4ba0e3081d limit stack use to prevent CUDA error 2 (#10696)
* control stack use to prevent overflow

* fix
2025-06-04 10:15:23 +08:00
Zhaowu Pan
85cd9cb7b0 patch possible dequant overflow (#10691) 2025-06-03 12:21:53 +08:00
Shuhao Liang
f2712b7e7c Add fused_transpose_split_quant kernel (#10657) 2025-06-03 10:44:53 +08:00
Zhaowu Pan
361ef0805d fix zip overflow (#10672) 2025-05-29 16:33:12 +08:00
Zhaowu Pan
07be8652e5 Adding fused_swiglu_probs_bwd op (#10604)
* Add fused swiglu_probs_bwd op

* add o2s as output

* fix 3d tensor input and add vectorize optimizations.

* fix tests of vec4

* Optimize reduce performance

* delete timeline

* Update setup_fp8.py

fix arch

* Fix multi-dimension issue.
2025-05-28 15:39:32 +08:00
Shuhao Liang
6c206e19da Add fused_stack_transpose_quant kernel (optional transpose) (#10649) 2025-05-28 14:34:49 +08:00
hong
a4d90ab27b support new fa3 api (#10661) 2025-05-27 23:21:13 +08:00
Zhaowu Pan
f705b6ba59 Add int64_t index type for possible overflow position. (#10663) 2025-05-27 20:10:57 +08:00
Zhaowu Pan
4bfc44d783 Add arbitrary padding to handle extreme inbalance case. (#10623) 2025-05-22 16:36:06 +08:00
risemeup1
67b21ae8a8 Support fusion moe (#10507)
* support fusion moe

* fix

* fix

* fix
2025-05-22 16:31:42 +08:00
chen2016013
5406b5e5c2 update DeepGEMM (#10429)
* merge

* Update m_grouped_gemm.py
2025-05-21 16:40:23 +08:00
risemeup1
670cbd9e75 Refine setup.py (#10577)
* fix

* fix
2025-05-15 15:18:41 +08:00
Zhaowu Pan
ae560afb1e Support arbitrary num_experts and topk, with bfloat16 zip prob. (#10583)
* Add arbitrary expert_num and topk support for unzip and zip.

* Merge bfloat16 zip prob support for flex num_experts and topk
2025-05-13 17:08:51 +08:00
hong
07d42410f3 update default sm num (#10586) 2025-05-13 15:35:10 +08:00
hong
65d2d3a29f optimize fp8 deep gemm tma (#10580) 2025-05-12 15:46:55 +08:00
Zhaowu Pan
6e8b317626 Adding swiglu_prod_act_quant op (spaq) (#10463)
* First version, passed precision test.

* Add optest.

* restore setup.py

* Adding optional prob for spaq

* Optimized spaq in last-dim 8x cases.

* fix type

* Further improve performance with_prob

* remove unessesary calculations.
2025-05-12 11:05:18 +08:00
Zhaowu Pan
ab69953892 Add FP32 support for zip op, optimize precision in bf16. (#10433) 2025-04-21 17:29:09 +08:00
Zhaowu Pan
d3ea4ec5f4 Undo old cupti patch (#10367) 2025-04-09 16:27:43 +08:00
zhangbo9674
a14cafdf4c fix bug (#10348) 2025-04-08 20:18:16 +08:00
ShenLiang
4113c5dd29 fix bug of expert init (#10347) 2025-04-04 18:55:23 +08:00
zhangyuqin1998
1433482a3b fix mem leakage (#10344) 2025-04-03 21:47:28 +08:00
hong
c3c6695add optimize linear keepx quant (#10332)
Co-authored-by: Pan Zhaowu <panzhaowu@baidu.com>
2025-04-03 17:37:56 +08:00
Zhaowu Pan
0e158fb8b5 Fix fused_act_dequant op with memset output to 0 (#10339)
* fix dequant initialize issue

* fix type
2025-04-03 17:34:07 +08:00
risemeup1
b7723f6980 Support Group Gemm Mask (#10280)
* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix
2025-04-03 17:25:38 +08:00
zhangbo9674
925e330ba7 add num_sms (#10324) 2025-04-02 10:20:44 +08:00
hong
01f08ba143 optimize linear keepx quant (#10322)
Co-authored-by: Pan Zhaowu <panzhaowu@baidu.com>
2025-04-02 10:18:46 +08:00
Zhaowu Pan
4770b1f409 Adding probs recover functionality to tokens_zip_op (#10308)
* Adding probs recover functionality to tokens_zip_op

* Fix memset bug.

* Re-opening other modules.
2025-04-01 10:46:29 +08:00
zhangbo9674
599fe9aac3 fix (#10320) 2025-04-01 10:20:10 +08:00
zhangbo9674
868add19a5 fix oom (#10307) 2025-03-31 13:49:03 +08:00
Zhaowu Pan
e90215b01c Adding simple token_zip op to get better performance. (#10300) 2025-03-28 17:13:58 +08:00
Zhaowu Pan
07572b4101 Implemented unzip_stable_op to fully substitute permute function (#10288)
* Adding unzip_stable_op

* Add rowmap invalid tag to prevent deadlock

* Finish polishing, adding tests.

* Fix miscs

* polish tests

* polish comments

* Add group padding to make masked_group_gemm happy

* Add special support for fp8 scales

* Fix typo

* fix test problems.

* final polish

* Adding banners
2025-03-28 17:13:27 +08:00
hong
411eef30fa Fp8 speed optmize (#10272)
* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* Add more type support for TDU.

* fix

* fix

* fix

* fix

* optmize attention memory

* polish code

* remove useless code

* update

* adding vectorization to 3 kernels.

* update

* update

* Adding fused_act_dequant kernel.

* update

* update

* update

* update

* update

---------

Co-authored-by: risemeup1 <515586620@qq.com>
Co-authored-by: Pan Zhaowu <panzhaowu@baidu.com>
2025-03-28 10:36:21 +08:00
Zhaowu Pan
6dcb2ba214 Adding fused_act_dequant kernel. (#10276) 2025-03-27 17:06:28 +08:00
risemeup1
97df5a8bbd [fp8]zip and group gemm (#10214)
* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix
2025-03-27 16:35:47 +08:00
zhangbo9674
ad0a6f6d90 add record_stream for dispatch and combine output (#10270)
* add record_stream for dispatch and combine output

* fix bug

* fix

* fix

* fix
2025-03-27 15:33:35 +08:00
hong
89c150db4b optmize grouped gemm (#10274)
Co-authored-by: Pan Zhaowu <panzhaowu@baidu.com>
2025-03-26 18:12:40 +08:00
Zhaowu Pan
574b1869c8 Optimizing TokenDispatcherUtils ops' performance. (#10262)
* adding vectorization to 3 kernels.

* Add manual mixed-precision part

* polish code
2025-03-26 17:57:16 +08:00
zhangbo9674
c5781392df Fix 0size for fp8 ExpertNode (#10263)
* fix 0 size

* refine mem
2025-03-26 11:06:30 +08:00
zhangyuqin1998
e3ba0cc88e fix_leakage (#10254) 2025-03-25 15:35:44 +08:00
Zhaowu Pan
b8eff335bd Adding Tdu FP32 type support (#10250)
* Add more type support for TDU.

* Fix bug
2025-03-25 11:28:58 +08:00
ShenLiang
996336f737 fix maxseqlen to 4097 (#10230) 2025-03-20 18:40:46 +08:00
Zhaowu Pan
53bc36b555 Fix arch issue(CUDA 222) in hopper arch (#10209) 2025-03-20 17:25:01 +08:00
zhangyuqin1998
221333f4dc support first_k_dense_replace for dualpipe (#10226) 2025-03-20 16:47:05 +08:00
ShenLiang
bb73548b7f Default config for dsv3 (#10225)
* add default config

* add default config

* add default config
2025-03-20 16:07:47 +08:00
zhangbo9674
d5367925b6 Optimize gpu memory usage for UnPermute (#10217)
* optimize expert memory

* refine

* fix bug

---------

Co-authored-by: phlrain <phliuhongyu@126.com>
2025-03-20 15:50:27 +08:00
zhangyuqin1998
f27dab36e7 support overlap for fusion moe (#10220) 2025-03-20 14:17:07 +08:00
zhangbo9674
c886cb7c4d Remove dependency on FP8 when using BF16 (#10219) 2025-03-20 14:13:39 +08:00
zhangyuqin1998
f566b66a99 Spliting fusion moe, fix memlory leakage of fusion moe (#10192)
* Support overlap for fusion moe, fix memlory leakage of fusion moe

* fix

* fix conflict
2025-03-20 10:29:22 +08:00
hong
22e4f9a67f Revert "optimize ds3 attention impl (#10200)" (#10208)
This reverts commit 58edb00c69.
2025-03-20 00:29:16 +08:00
zhangbo9674
642869eb52 fix permute grad bug in pp (#10213) 2025-03-19 23:46:58 +08:00
ShenLiang
eb2c98844a [revert]Add timer for deepep (#10212)
* Revert "add timer for deepep (#10211)"

This reverts commit a874a9b585.

* revert timer
2025-03-19 21:03:56 +08:00
zhangbo9674
ce004144d6 fix (#10207) 2025-03-19 20:49:07 +08:00
ShenLiang
a874a9b585 add timer for deepep (#10211) 2025-03-19 20:43:18 +08:00
zhangyuqin1998
dff10bf21e Merge MoEFlexTokenLayer to MoELayer (#10205) 2025-03-19 20:25:54 +08:00
hong
0a77769e3e Optimize attention output linear fp8 memory (#10204)
* optimize atten impl

* optimize_attention_output_linear_fp8_memory
2025-03-19 19:18:47 +08:00
Zhaowu Pan
cf5f6a5a30 Add several fused quanted ops in support of FP8 training (#10202)
* Added two fused op, refractor some old swiglu code.

* delete unecessary print.
2025-03-19 18:32:24 +08:00
Zhaowu Pan
fea2a8c3fc Adding TokenDispatcherUtils, for MoE token dispatch and regroup, in preparation for GroupedGEMM using in training. (#10190)
* Add regroup_tokens op and optest, fix topk_to_multihot setup.py

* Add test file

* fix miscs

* Add tokens_unzip & weighted_zip in preparation of fp8-groupedgemm

* Added expert_idx output to tokens_unzip op.

* Fix prob datatype issue.

* Implemented double input&output regroup op.

* Further fix bf16 issues.

* Fix implicit bug.

* Change the unzip op to save more useful data

* Refractor and combining tokens_unzip_and_zip.

* Fixed concurrent semaphore bug.

* delete synchronize in zip op, and starting to add guided unzip kernel.

* Add fp8 support for unzip op, but cannot fake a tensor for testing.

* Added guided_unzip op.

* Modified guided_unzip to satisfy real usage.

* polish code

* Fix typos and polish & tested code
2025-03-19 18:32:07 +08:00
hong
58edb00c69 optimize ds3 attention impl (#10200) 2025-03-19 18:31:46 +08:00
zhangbo9674
314841d84a Fix dequant bug and dw compute bug (#10193)
* fix dequant bug

* fix bug

* fix bug

* fix
2025-03-19 16:17:49 +08:00
risemeup1
5ecbd04dd6 fix (#10191) 2025-03-19 13:52:35 +08:00
risemeup1
a360eeb50b fix (#10189) 2025-03-19 12:00:34 +08:00
zhangbo9674
37ec16ec66 Use Fp8 dispatch for moe layer (#10165)
* add flag DSV3_USE_FP8_GEMM

* fix

* add fp8 comm

* fix bug

* fix bug

* fix bug

* fix bug

* fix bug

* fix

* fix bug

* fix bug

* replace index_select to gather

* close fuse_moe

* fix dequant bug
2025-03-18 22:12:55 +08:00
ShenLiang
bfaa97ec0e fix expert parameters (#10184) 2025-03-18 22:12:15 +08:00
zhangyuqin1998
473ac84846 Opt dualpipe overlap (#10173) 2025-03-18 15:07:38 +08:00
ShenLiang
a1759fec56 using gather (#10158) 2025-03-18 14:30:54 +08:00
zhangbo9674
cb4be8fc34 Add flag DSV3_USE_FP8_GEMM (#10133)
* add flag DSV3_USE_FP8_GEMM

* fix
2025-03-18 11:18:04 +08:00
zhangyuqin1998
9d98f0848d Adapt to the fix_cpu_stall (#10154) 2025-03-17 11:35:14 +08:00
zhangbo9674
f4bf969c7c Delete fp8 gemm warning (#10134)
* refine

* fix
2025-03-17 10:32:23 +08:00
umiswing
1fbbe2a212 Fix cpu stall in permute and unpermute (#10147)
* commit for save

* revert gpu sum in add loss for mtp
2025-03-16 22:25:10 +08:00
zhangyuqin1998
99c047ae1c [Distribution] Support DualPipeV for deepseek (#10138)
* [Distribution] Support DualPipeV for deepseek

* add

* fix

* add

* add
2025-03-15 17:23:33 +08:00
risemeup1
614e1aa765 fix (#10130) 2025-03-14 11:08:59 +08:00
Zhaowu Pan
4eeb1923a8 Added topk_to_multihot and grad kernel to prevent CPU Stall. (#10127) 2025-03-13 21:02:06 +08:00
Zhaowu Pan
6c3172a4a5 Add fused_swiglu_act(transpose)_quant op to extern op in gpt-3. (#10124)
* Add fused_swiglu_act(transpose)_quant op to extern op in gpt-3

* Polishing code.

* remove unecessary lines.

* remove unecessary lines in cu

* Add padding function to fused_swiglu_act_quant_op
2025-03-13 19:26:33 +08:00
zhangbo9674
464075a365 op fuse flag (#10122) 2025-03-13 19:09:50 +08:00
ShenLiang
6a203f58a8 Add distributed run for dsv3 (#10119)
* add distributed run

* fix topo

* add distributed print
2025-03-13 17:25:35 +08:00
zhangbo9674
2ab44c441a support fp8 && refine gemm runtime && opt cpu sync in moe (#10116) 2025-03-13 16:24:44 +08:00
ltd0924
f68aadad26 [LLM] fix config reload (#10114)
* [LLM] fix config reload

* close md5 check

* Update processor.py

* Update download_model.py
2025-03-13 14:18:36 +08:00
vivienfanghuagood
ee3de2682c add_benchmark (#10110)
* add_benchmark
2025-03-13 12:08:59 +08:00
ZhenxingLi
94dd1d86a4 [AutoParallel] Fix qwen2vl image shape (#10086)
* Update auto_trainer.py

* Update auto_trainer.py
2025-03-13 11:40:09 +08:00
lizhenyun01
f6c0e6db0b optimize mla to get best performance (#10102)
* support auto search for mla chunksize

* optimize mla to get best performance

* fix

* add note for mla
2025-03-13 11:05:04 +08:00
co63oc
6a8e047057 [Typos] Fix typos (#9933) 2025-03-13 09:56:01 +08:00
Zhong Hui
e5a41fac94 Update README.md for paddlenlp 3.0 beta4 (#10098)
* Update README.md for paddlenlp 3.0 beta4

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md
2025-03-12 21:49:45 +08:00
liufengwei0103
183cd790bc [AutoParalle] update README.md (#10033)
* update README.md

* format

* delete intermidate_api

* add more explanation about code example

* add more explanation about code example

* update web ref

* refine infer readme

* fix path

* fix bug

* fix bug

* fix bug

* fix bug

* fix bug

* fix bug

* fix bug

* refine according to comment

* update recommended paddle version 3.0-rc

* fix bug

* fix bug

* change arg ref to github file

* fix typo

* update paddle version

* add json config, move readme to auto_parallel dir

* fix

* fix

* delete qwen shell launch example

* recover gpt input data config

* recover gpt config

* recover gpt config

* recover gpt config

* update code example path hint

* move line

* change name style

* delete ppo

* normalize task name

* normalize task name

* normalize task name

* fix gpt json config

* recover qwen debug file

* delete run_pretrain_auto.sh
2025-03-12 20:34:27 +08:00
Zhong Hui
d8d6bec83a Refine inference doc (#10090)
* refine inference doc

* refine

* Rename inference.rst to inference_index.rst

* Update index.rst
2025-03-12 20:10:30 +08:00
ltd0924
79dbdbb3aa [LLM] fix speculate_decoding output bug (#10106) 2025-03-12 18:06:54 +08:00
Ting
3d023bd10f Support deepseek-v3/loraGA/ on xpu (#9928)
* support deepseek-v3/loraGA/ on xpu

* fix ds2 config

* fix ds3 eval

* fix seq_aux_loss, weight load time consume, moe tp

* Optimize code of expert dispatch

* optimize moe expert dispatch

* remove redunctant code.

* EP support, MTP fix

* remove print

* add alltoall backward

* fix all2all bwd

* support drop tokens, disable acc cal

* fix bug

* add base_model_prefix in ds3 modeling pp

* fix ci shape mismatch

* update
2025-03-12 18:03:56 +08:00
Liujie0926
985075fcbe [CI]Fix proxy (#10104)
* add set -e for unittest

* update proxy

* fix
2025-03-12 17:50:51 +08:00
freeliuzc
83b1a6f241 Fix serving allocate block bug (#10100) 2025-03-12 15:11:10 +08:00
Yuanle Liu
762a680d30 [Inference] Update docs (#10089)
* change_h100_to_h800

* Update README.md
2025-03-12 14:24:16 +08:00
Yuanle Liu
a37512ff7d [Inference] Enhance fused_rotary_position_encoding and get_position_ids_and_mask_… (#10077)
* enhance fused_rotary_position_encoding and get_position_ids_and_mask_encoder_batch

* update

* fix src_length

* update

* update

* fix ci
2025-03-12 14:17:39 +08:00
ltd0924
9408f4c3ce [Doc] 完善文档,更新示例模型 (#10084)
* [Doc] 完善文档,更新示例模型

* [Doc] 完善文档,更新示例模型

* [Doc] 完善文档,更新示例模型

* fix bug

---------

Co-authored-by: luotingdan <luotingdan@baidu.com>
2025-03-12 11:27:44 +08:00
lizhenyun01
6d80be73ba [INFER] auto set mla_use_tensorcore (#10095) 2025-03-12 10:32:25 +08:00
lzy
f85f1e9bf3 supports mla wg4(Low-precision accumulation) (#10072)
* Support MLA by using 4 WG
2025-03-11 18:14:59 +08:00
ShenLiang
034e4d85e0 Fix oom in dsv3 (#10068) 2025-03-11 16:36:55 +08:00
Zhong Hui
c27a341e30 Remove not need files (#10079) 2025-03-11 16:08:48 +08:00
Zhong Hui
bffd3b549b Skipping 0-D tensor Error. (#10075) 2025-03-11 16:00:19 +08:00
ltd0924
f6ad587ad7 [Doc] 文档完善,新增模型环境设备需求 (#10071)
* [Doc] 文档完善,新增模型环境设备需求

* [Doc] 文档完善,新增模型环境设备需求

---------

Co-authored-by: luotingdan <luotingdan@baidu.com>
2025-03-11 15:15:32 +08:00
Liujie0926
2e8b5d2d55 fix case only in a100 (#10054) 2025-03-11 15:03:32 +08:00
ZhenxingLi
354be23c8f [AutoParallel] Get dtensor from ShardDataloader (#10009)
* get dtensor from ShardDataloader and acc split

* Rename dtensor_idx to dense_tensor_idx

* fix 2D dense_tensor_idx

* Update auto_trainer.py

* Update auto_trainer.py
2025-03-11 15:02:54 +08:00
Yuanle Liu
a3942c8974 update total_max_length use export model (#10052) 2025-03-11 14:58:16 +08:00
chen
3421d486df Fix MTP triton cache not found (#10066) 2025-03-11 14:34:23 +08:00
Zhong Hui
8db460e586 add model list to doc. (#10031) 2025-03-11 14:10:06 +08:00
will-jl944
92a75980a8 Fix eval pp bug when do_train is false (#10012) 2025-03-11 14:04:43 +08:00
lugimzzz
4cd17eaf49 [LLM]support groupwise quant for llama (#10050)
* support groupwise quant for llama

* support groupwise quant for llama
2025-03-11 12:39:28 +08:00
Function-Samuel
a23e504e4b Fix flash_attn diff in base api (#10027) 2025-03-11 11:13:40 +08:00
Yichen Zhang
e1536c0d5c Add import check of local_layer (#10036) 2025-03-11 10:57:37 +08:00
risemeup1
b35f79efd2 [fp8] Support deep gemm in paddle (#9955)
* support fp8 gemm

* support fp8 gemm

* fix

* fix

* update deepGeem remote

* fix test_gemm

* support group_gemm

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* fix
2025-03-11 10:51:11 +08:00
Liujie0926
dfe3a2878c update wheel's name of paddlenlp_ops (#10047)
* update wheel's name

* fix exit

* update paddlenlp_ops install

* fix
2025-03-10 21:51:39 +08:00
liym27
15fbec8813 Revert "[AutoParallel] Support reshard attention mask in intermediate_api (#9…" (#10067)
This reverts commit c9d8e3aabd.
2025-03-10 21:35:50 +08:00
Zhong Hui
219e709889 Update devices README.md (#10062)
* Update README.md
2025-03-10 20:17:13 +08:00
ltd0924
814cc4507d [LLM] fix bug (#10058)
Co-authored-by: luotingdan <luotingdan@baidu.com>
2025-03-10 17:58:51 +08:00
liym27
c9d8e3aabd [AutoParallel] Support reshard attention mask in intermediate_api (#9975) 2025-03-10 17:39:10 +08:00
Zhong Hui
8452021418 Update static_models.md (#10053) 2025-03-10 17:17:02 +08:00
dimensionplane
6861e1749d [LLM] Update GLM (#10000)
* Update GLM

* glm

---------

Co-authored-by: wangxueyang <xueyang.wang@aminer.cn>
2025-03-10 16:30:58 +08:00
bukejiyu
2506f448f5 [server]Add a model download script and fix bugs for the server. (#10034)
* fix

* fix download

* fix

* fix

* support download

---------

Co-authored-by: ltd0924 <32387785+ltd0924@users.noreply.github.com>
2025-03-10 15:00:05 +08:00
ltd0924
098f2348d2 [Doc] 自行下载模型文档说明 (#10048)
* [Doc] 自行下载模型文档说明

* [doc] 支持用户自行下载静态图

* [doc] 支持用户自行下载静态图

* [Doc] fix format

---------

Co-authored-by: luotingdan <luotingdan@baidu.com>
2025-03-10 14:19:00 +08:00
Liujie0926
4554b1cdb6 [CI]Fix ci scripts (#10045)
* update loss_base by Paddle#71301

* fix spelling error

* fix exit code rerun

* fix upload
2025-03-10 14:05:57 +08:00
lzy
ef9aecc0ec [MLA] make MLA supports blocksize 32 (#10039)
* make mla supports blocksize 32

* make mla supports append
2025-03-10 11:58:21 +08:00
Chang Lu
a8ee9438ad [XPU] add llama 7b&13b xpu scripts (#10025)
* add xpu scripts

* Update modeling_auto.py
2025-03-10 11:15:14 +08:00
Guoxia Wang
59fbc79bc0 Add enable_offload_queue to PipelineParallel (#9708) 2025-03-10 10:54:55 +08:00
umiswing
da96c7258e add rdma config hint (#10040) 2025-03-09 20:42:56 +08:00
bukejiyu
a9fd4082a5 update doc (#10028) 2025-03-09 16:06:19 +08:00
Weiguo Zhu
bcc9236344 fix (#10037) 2025-03-09 11:55:08 +08:00
l1cacheDell
23a4880866 [Performance optimization] Sage Attention Enhancement (#10021)
* fuse all sageattn kernels & unified API entry

* remove files

* bug fix

* upload header file
2025-03-07 17:48:18 +08:00
blacksheep-Aristotle
a99829122d [Auto] Using auto parallel to validate SFT/LORA of llama model (#9728)
* add single_model network and use intermediate api

* [AutoParallel]: fix llama_model_network run error

* New version of auto config

* fix gpt_network to use intermediate_api

* fix gpt_network to use intermediate_api

* update api

* update plan

* qwen fit base api

* [AutoParallel]:gpt single network support tp to share_embedding

* add intermediate ci

* add single_model network and use intermediate api

* New version of auto config

* fix sharding

* fix gpt_network to use intermediate_api

* fix gpt_network to use intermediate_api

* update gpt run_pretrain_py

* fix sharding error

* fix gpt format error

* [AutoParallel]:fix llama vpp ci error

* [AutoParallel]:fix ipp error

* [AutoParallel]:fix a100 ci error

* [AutoParallel]:fix a100 ci error

* [AutoParallel]:add explanatory note

* Delete =1.0.0

* [AutoParallel]:add run_fintune scripts

* [AutoParallel]:auto parallel support lora model

* update auto_lora_model

* update auto_lora_model

* [AutoParallel]:nlp support run lora model with intermediate

* [AutoParallel]:update format

* [AutoParallel]:support input attentionmask

* [AutoParallel]:shard dataloader support multi inputs

* [AutoParallel]:auto_sft rebase develop

* [AutoParallel]:auto_sft rebase develop

* [AutoParallel]:fix lora parallel mode

* [AutoParallel]: fix bug about file dep circular and lora config error

* [AutoParallel]: recover default base api config in launch script

* [AutoParallel]: add to do

* [AutoParallel]: add to do

* add single_model network and use intermediate api

* [AutoParallel]: fix llama_model_network run error

* New version of auto config

* fix gpt_network to use intermediate_api

* fix gpt_network to use intermediate_api

* update api

* update plan

* qwen fit base api

* [AutoParallel]:gpt single network support tp to share_embedding

* add intermediate ci

* add single_model network and use intermediate api

* New version of auto config

* fix sharding

* fix gpt_network to use intermediate_api

* fix gpt_network to use intermediate_api

* update gpt run_pretrain_py

* fix sharding error

* fix gpt format error

* [AutoParallel]:fix llama vpp ci error

* [AutoParallel]:fix ipp error

* [AutoParallel]:fix a100 ci error

* [AutoParallel]:fix a100 ci error

* [AutoParallel]:add explanatory note

* Delete =1.0.0

* [AutoParallel]:add run_fintune scripts

* [AutoParallel]:auto parallel support lora model

* update auto_lora_model

* [AutoParallel]:nlp support run lora model with intermediate

* [AutoParallel]:update format

* [AutoParallel]:support input attentionmask

* [AutoParallel]:shard dataloader support multi inputs

* [AutoParallel]:auto_sft rebase develop

* [AutoParallel]:auto_sft rebase develop

* [AutoParallel]: add lora ci and fix bug

* [AutoParallel]: fix lint error

* [AutoParallel]: fix lint error

* [AutoParallel]: fix lint error

* [AutoParallel]: fix ci error about print model

* [AutoParallel]: fix typo

* [AutoParallel]: fix

* [AutoParallel]: fix llama_dygraph_auto_bs8_fp16_DP2-MP2-PP2_intermediate loss base

* [AutoParallel]: delete typo

* [AutoParallel]: delete comment

* [AutoParallel]: fix ci error not on a100

* [AutoParallel]: delete comment

* [AutoParallel]: delete useless code

* [AutoParallel]: ddelete launch script

* [AutoParallel]: recover label mesh to

* [AutoParallel]: fix ci error

* [AutoParallel]: fix loss in ci

* [AutoParallel]: revert editing to max_length padding

* [AutoParallel]: delete comment

* update llama lora test case loss

* add blank line

* delete commment

* format

* delete last slash

* add deterministic flag

---------

Co-authored-by: YuangLiu <liuyuang@baidu.com>
Co-authored-by: liufengwei02 <liufengwei02@baidu.com>
2025-03-07 17:47:13 +08:00
xuxinyi389
3d5cac9df1 [AutoParallel] Add deepseek-v3 config (#10019)
* add_config

* update_config

* update_config

* add_describe
2025-03-07 17:33:40 +08:00
tianshuo78520a
63d920b565 del update_inputs.cu (#10022) 2025-03-07 00:54:58 -08:00
ltd0924
19e10ba59e [LLM] fix llm model path and support download from txt (#10026)
* [LLM] fix llm model path and support download from txt

* [LLM] fix llm model path and support download from txt
2025-03-07 16:28:54 +08:00
vivienfanghuagood
1db27cdaf9 Support mmlu-pro (#10023)
* add_mmlu

* update

* add_gsk8k

* add_mmlu_pro

* add
2025-03-07 15:00:09 +08:00
Weiguo Zhu
34d2980658 [News] update readme (#10020)
* new

* update

* update
2025-03-07 14:16:18 +08:00
freeliuzc
3dc05ada30 update spec docs (#10016) 2025-03-07 13:32:03 +08:00
ShenLiang
d2a976466a Add deepep for deepseekv3 (#10007) 2025-03-07 11:25:16 +08:00
freeliuzc
df10f2c615 update doc (#10014) 2025-03-06 21:13:32 +08:00
Weiguo Zhu
4711e147a1 Update version (#10015) 2025-03-06 20:35:49 +08:00
bukejiyu
0a665a0418 [inference]add docker doc (#9998)
* add doc

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* [LLM] 服务化部署文档

* update

* [LLM] 服务化部署文档

---------

Co-authored-by: ltd0924 <32387785+ltd0924@users.noreply.github.com>
2025-03-06 18:40:06 +08:00
zhangyuqin1998
5329d28881 [Distribution] Support DualPipeV for GPT3 (#9993)
* [Distribution] Support DualPipeV in GPT3

* fix

* fix
2025-03-06 17:21:27 +08:00
lizhenyun01
80272fd51c Default set FLAGS_cascade_attention_max_partition_size as 32K (#10013) 2025-03-06 17:15:25 +08:00
chen
385f613f09 Remove some bug config for block gemm (#10002) 2025-03-06 17:14:37 +08:00
Weiguo Zhu
fce1bf5399 update license (#10003) 2025-03-06 16:55:36 +08:00
Weiguo Zhu
658bec29dd [LLM] Fix MTP for pipeline parallel (#9972)
* fix params loading
2025-03-06 16:22:26 +08:00
Weiguo Zhu
51ea8a42b8 [Doc] Add Qwen/QwQ-32B model ids (#10005)
* update Qwen models

* merge
2025-03-06 14:54:32 +08:00
ltd0924
a313a26f73 [LLM] support fix seq len and cmd run service (#10004)
* [LLM] support fix seq len

* [LLM] support cmd run service

* [LLM] support cmd run service
2025-03-06 14:51:27 +08:00
l1cacheDell
b36d306a65 [Feat] Sage Attention Kernels Support for sm80, sm89, sm90 (#9848)
* add sage attn sm90 kernels

* fix

* add ds sageattn kernel

* update kernels

* update setup_cuda.py

* update dsk MLA kernel

* clean PR branch

* fix sa usage

* bugfix

* modify, for static mode inference SA

* add license info

* add license info for py file

* modify license info

* modify license info

* bsz=1 assert

* fix kernel

* move to import line

* merge develop & support wint8&fp8
2025-03-06 14:47:07 +08:00
Yuanle Liu
ed7f01da68 [Inference] Add deepseek doc (#9964)
* add deepseek doc

* fix dead links

* remove png

* fp8 for mtp

* check

* add weight_block_size and moe_quant_type

* Update inference.md

* add server

* fix

* update

* Update deepseek.md

* update

* update

---------

Co-authored-by: DrownFish19 <DrownFish19@gmail.com>
Co-authored-by: ckl117 <ckl117@163.com>
Co-authored-by: bukejiyu <395822456@qq.com>
2025-03-06 14:12:57 +08:00
umiswing
a381674fd4 Add moe flex dispatcher (#9977)
* add wip flex dispatcher

* wip fix PyLayer segfault

* remove redundant args

* refine

* add group as args

* add license, fix a bug

* refine codestyle

* refine
2025-03-06 11:49:26 +08:00
ltd0924
2c1b1062e0 [LLM] Support for automatic deployment of services, modification of environment variable names (#9966) 2025-03-06 11:41:28 +08:00
gaoziyuan
2921a5168e 【Inference】Add benchmark client test scripts (#9996)
* add benchmark client scripts

* add benchmark client scripts

* add benchmark client scripts

* add benchmark client scripts

* add benchmark client scripts

* add benchmark client scripts
2025-03-05 19:36:35 -08:00
Function-Samuel
c98163bd51 [AutoParallel] Support intermediate_api baichuan test (#9988) 2025-03-06 11:19:58 +08:00
lizhenyun01
47e32664af [DSK] fix tenercore precision while split kv (#9994)
* fix tenercore precision while split kv

* fix

* fix

* fix

* update unittest
2025-03-05 18:12:02 -08:00
Weiguo Zhu
2773ce3e44 fix prm test (#9997) 2025-03-06 09:32:56 +08:00
xuxinyi389
ab1a90cd00 [AutoParallel] Add pp stage id (#9965)
* add_pp_stage_id

* fix some bugs in dygraph pipeline parallel

---------

Co-authored-by: Yichen Zhang <zhangyichen03@baidu.com>
2025-03-05 21:03:13 +08:00
Yuanle Liu
614d10a34b [LLM INFER] update step_paddle (#9991)
* fix step_paddle
2025-03-05 19:52:25 +08:00
ming1753
9f93974e60 [DSK] DeepSeek Support FP8 (#9956)
* DeekSeek suport FP8

* support fp8 block gemm and group quant

* support fp8 gemm with tensor scale tune on sm90

* support read weight_block_size from model config.json

* move tune_fp8_gemm.sh to csrc

* coptimize per_token_group_quant_fp8_api

* support per_token_group_quant_fp8_api transpose_scale True

* optimize preprocess_for_moe

* support tensor core mla

* check fp8 code and support wint8-moe in R1-FP8-small
* deepseek fp8 support moe wint8


---------

Co-authored-by: ckl117 <ckl117@163.com>
Co-authored-by: zhoutianzi666 <17801055074@163.com>
2025-03-05 19:05:51 +08:00
lugimzzz
5ada4dbe99 fix ci (#9989) 2025-03-05 15:47:50 +08:00
Chang Lu
d6fc58dbcf fix profile tool (#9976) 2025-03-05 15:39:10 +08:00
Tian
eb25ccb618 [LLM] add moe parallel groups (#9982) 2025-03-05 15:37:09 +08:00
greycooker
fd0da9381b Fix wandb proxy (#9960) 2025-03-05 15:02:58 +08:00
freeliuzc
14c829eac3 Fix mtp speed (#9987)
* fix mla's precision

* modify mtp serving strategy

---------

Co-authored-by: carryyu <569782149@qq.com>
2025-03-05 12:31:57 +08:00
lugimzzz
f4d4eea5e2 [LLM]fix ci (#9986) 2025-03-05 11:15:17 +08:00
Zhong Hui
4c2a3f76be Update paddle_patch.py (#9984) 2025-03-04 20:48:28 +08:00
Yuanle Liu
91d1a2343c [Inference] MLA use tensor core (#9952)
* mla use tensor core

* update

* update cutlass

* fix

* fix

* add some logic

* 耗时异常

* fix

* update

* fix mla split_kv

* support write cache

* write spec cache

* fix infer.py mla_absorb

* fuse noaux_tc

* fix server

* fix dybatch

* fix start_server.sh

* support mtp with new version

* fix mtp dynamic bug

* fix server

* fix mla's precision and del unused code

* fix mla_hopper.h

---------

Co-authored-by: lizhenyun01 <1500424927@qq.com>
Co-authored-by: freeliuzc <lzc842650834@gmail.com>
Co-authored-by: carryyu <569782149@qq.com>
2025-03-04 19:57:58 +08:00
bukejiyu
a99d6ada59 [Inference] refine csrc/tools/build_wheel.sh (#9971)
* update gpu whl

* add

* update
2025-03-04 01:57:30 -08:00
Chang Lu
55d57fbffc Change llama loss on xpu (#9973) 2025-03-04 16:57:40 +08:00
Zhong Hui
cf4e9c8ed1 Update paddle_patch.py (#9978) 2025-03-04 15:01:17 +08:00
vivienfanghuagood
350acbfb19 Support MMLU eval (#9967)
* add_mmlu

* update

* add_gsk8k
2025-03-04 11:39:53 +08:00
Zhong Hui
5100d08da7 Fix update paddle_patch.py (#9968) 2025-03-04 11:00:52 +08:00
jax
cda527960d Longlora (#9970)
* longlora-paddle

* update tests for longlora

* update longlora test

* update modeling

* update test

* update test

* update test

* update

* update
2025-03-04 10:34:39 +08:00
lugimzzz
cc925d0aea [MergeKit]add log (#9948)
* add log

* add log
2025-03-03 20:49:12 +08:00
lugimzzz
4b65eecb2d [llm]add bf16 moment adamw (#9732)
* add adam

* add triton ops

* update model

* add

* add triton ops

* fix

* fix

* support 16bit

* support 16bit
2025-03-03 17:21:06 +08:00
Yichen Zhang
5936abec96 [AutoParallel] Add auto parallel moe layer (#9886)
* add auto parallel moe layer

* add local layer in MoELayer

* add expert parallel with dygraph auto parallel

* expert parallel in static auto parallel
2025-03-03 14:58:48 +08:00
Zhong Hui
10dd453b40 [Feature] Support float8 dtype storage and deepseek v3 with fp8 inference. (#9906)
* suppport float8 dtype.

* fix

* fix for empty shape.

* Support load fp8 model.

* debug

* [DeepSeek] Support for float8 loading and inference.

* Add paddle patch.

* refine safetensors.

* refine code.

* Fix moe dtype error.

* fix paddle.Tensor.

* fix kwargs with patch api.

* fix for fast safe open

* fix merge kit.

* fix inference.

* remove set device.
2025-03-03 14:54:45 +08:00
nunnunko777
8a8c64f9fb Add Process Reward Model. (#9598)
* Add Process Reward Model.

* Support return_dict=True

* reimplement prm & support Mistrail.

* lowercase in mode path

* tokenizer add_special_tokens=False for placeholder & reward tokens

* support flash mask

* add prm tests

* causal mask

* fix import error of LlamaLMHead & MistralLMHead

* fix import error of LlamaLMHead & MistralLMHead

* verify loss computation

* fix rag reward_tokens

* fix arg reward_tokens

* Lint

* Lint

* Lint

* add test

* remove redundant notes.

* add readme doc

* fix import error
2025-03-03 11:49:45 +08:00
Weiguo Zhu
5477fb85c5 [doc] update config and add docs for grpo (#9962)
* add grpo doc and config

* update ppo

* update

* update

* update

* lint

* update doc

* skip ci
2025-03-03 10:02:23 +08:00
Weiguo Zhu
40c3530dff [RL] Fix PPO and add GRPO (#9925)
* fix ppo and grpo v1

* update grpo

* delete notes and modify argument (#10)

* [RL] Fix PPO and add GRPO  (#11)

* delete notes and modify argument

* delete ppo_config.json

* modify format

* lint

* fix model config set

* fix grpo (#12)

* [New Features] support json file data (#13)

* delete notes and modify argument

* delete ppo_config.json

* modify format

* support json data

* modify argument

* fix

* fix ci

* fix

* fix datapath (#14)

* delete notes and modify argument

* delete ppo_config.json

* modify format

* support json data

* modify argument

* fix data

---------

Co-authored-by: greycooker <94276438+greycooker@users.noreply.github.com>
Co-authored-by: gongel <ainlp88@qq.com>
2025-02-27 21:01:30 +08:00
freeliuzc
85e1238ace 1.fix dynamic_forward of mtp. 2.fix llama-eagle multi-device (#9947) 2025-02-27 20:48:00 +08:00
kevin
02bf7c8dbc [LLM] update llm server dockerfiles (#9940)
* [LLM] update llm server dockerfiles

* update llm dockerfile
2025-02-27 16:39:16 +08:00
Weiguo Zhu
00f1e66c5a [requirements] tokenizers for py38 (#9953) 2025-02-27 16:31:36 +08:00
blacksheep-Aristotle
45b50121b5 use training_args to contorl split input (#9943) 2025-02-27 11:45:32 +08:00
Yuanle Liu
72dd32d903 [DSK] Implement mla use matrix-absorption (#9875)
Implement matrix-absorption version of MLA

---------

Co-authored-by: lizhenyun01 <1500424927@qq.com>
Co-authored-by: lizhenyu04 <lizhenyu04@baidu.com>
2025-02-26 22:10:39 +08:00
Siming Dai
011ae71a8f [Unified Checkpoint] Fix split param loading directly when using ignore_merge_optimizer (#9935)
* fix

* refine code

* update typename
2025-02-26 16:02:14 +08:00
xuxinyi389
b6956a3905 [Autoparallel] Mtp for DeepSeekV3 (#9884)
* refine log

* fix

* add model args

* suppoort_deepseekv2_autoparallel_with_DP/MP

* poolish

* remove_env_set

* update_code

* add_v3

* support_sharding

* move_to_v3

* fix_typo

* update_v3_config

* refine

* refine

* fix

* fix

* fix

* fix

* fix

* mtp_for_v3

* deepseekv3_for_pp

* update_run_pretrain_auto.sh

* update_sh

* fix_typo

---------

Co-authored-by: zhangbo9674 <zhangbo54@baidu.com>
2025-02-26 14:54:51 +08:00
freeliuzc
f60f83e541 【Inference】Support mtp serving (#9936)
* Unify the mtp usage of predictor and serving.

* 1.support speculate complicated args. 2.format serving code

* 1. support mtp serving.  2. Unify Spec argument

* fix mtp serving

* merge develop

* delete debug

* support serving compute accept_ratio
2025-02-26 14:04:21 +08:00
ZiyiHuang
c71287d1fc [taskflow] Fix taskflow bug (#9930)
* fix

* add doc

* update docs

* add experiment

* update readme.md

---------

Co-authored-by: DrownFish19 <DrownFish19@gmail.com>
2025-02-25 19:08:08 +08:00
Weiguo Zhu
7acaf18fa1 [LLM] Add MTP for Deepseekv3 (#9876)
* mtp

* MTP

* update deafult config

* update MTP

* update seq_aux_loss

* update output

* lint

* fix for qwen2moe
2025-02-25 13:28:25 +08:00
Function-Samuel
9790880fc2 Support intermediate_api qwen test (#9910)
* split from pr9882

* gate_up_fused_proj
2025-02-25 12:53:01 +08:00
Function-Samuel
694bb50c68 Support intermediate_api gpt-3 test (#9912)
* split from pr9882

* fix
2025-02-25 12:51:59 +08:00
Yuanle Liu
30df8b6b6a [DeepSeek] Fix some bugs for dsk-v3 (#9874)
* use fused rope

* fix import
2025-02-24 11:58:17 +08:00
AIbin
0b26a02d0b [Inference] Support qwen2_5_vl (#9924)
* support qwen2_5_vl

* update support qwen2_vl & qwen2_5_vl & support multi models mapping
2025-02-24 11:01:51 +08:00
zhaohaixu
0c65ce7f9c [LLM] fix block_size setting for llama. (#9921) 2025-02-21 17:57:21 +08:00
Liujie0926
c65dc182c7 [CI]update ci scripts (#9889)
* update ci scripts

* upload fail_log to bos

* fix unittest

* fix

* paddlenlp_ops build

* fix env

* revert

* fix log
2025-02-21 14:06:51 +08:00
Sijun He
a095e97929 Update finetune.md (#9922) 2025-02-21 13:53:19 +08:00
lugimzzz
b8ebe3ee0d add count trained tokens (#9800)
* add count

* fix

* fix
2025-02-20 16:40:40 +08:00
bukejiyu
347d77ccc2 add gpu whl (#9890) 2025-02-20 14:08:04 +08:00
Weiguo Zhu
7ea422863f [DOC] PP-UIE (#9913) 2025-02-20 11:39:42 +08:00
liym27
b49d9ff37c [Benchmark] Align benchmark conf for static baichuan2 gpt3 (#9901)
* align benchmark conf for static baichuan2 gpt3

* align benchmark conf for static qwen-14b

* fix scripts
2025-02-20 11:37:17 +08:00
Weiguo Zhu
2e1d57bb6f [DOC] Update README for PP-UIE (#9911)
* update doc for pp-uie

* update
2025-02-20 11:16:08 +08:00
ZiyiHuang
3a5e9b831f [LLM-IE] Add pp-uie to Taskflow (#9845)
* fix taskflow

* add llm/ie for SFT of ie task

* remove data folder

* update readme

* add taskflow

* remove taskflow

* add sft for ie task

* add multi_stage_predict of taskflow

* fix some bug and rename qwen2 as uie-llm

* fixed test and lint

* fixed test and lint

* fixed test and lint

* update 0109

* update 0109

* update 0113

* updaate 0113

* remove static mode in taskflow

* update 0115

* update 0115

* update 0115

* update 0116

* update 0116

* update readme.md

* update readme.md

* update 0116

* update taskflow.py and readme.md

* rename model name

* update
2025-02-20 10:26:15 +08:00
Weiguo Zhu
777fc2793f [TaskFlow] Fix pir for taskflow (#9822)
* fix pir for taskflow

* update suffix for PIR(ON/OFF)

* fix and revert skip

* update dependency_parsing

* fix pir bug

* fix pir bug

* fix lint

* fix ci

* disable test case

---------

Co-authored-by: Zhong Hui <zhonghui.net@gmail.com>
Co-authored-by: Fantasy-02 <1026931135@qq.com>
2025-02-20 10:21:53 +08:00
freeliuzc
11684064d6 [Inference] Fix deepseek_v3 with mtp in multi-gpu mode (#9894)
* fix deepseek_v3 with mtp in multi-gpu mode

* fix IWR bug
2025-02-19 20:22:01 +08:00
liym27
08183d7fea [CI] Update the best conf for gpt-13b in dygraph mode (#9891)
* update the best conf for gpt-13b in dygraph mode

* fix run mode
2025-02-19 15:54:53 +08:00
Longzhi Wang
7e9052a921 【SpecInfer】修复 InferenceWithReference 接收率不高的 bug (#9880) 2025-02-18 22:41:43 -08:00
ltd0924
60ef0afaf8 [Server] Support multi machine deployment (#9872) 2025-02-19 13:31:42 +08:00
lugimzzz
775ed2ad36 fix (#9885) 2025-02-19 11:47:57 +08:00
liym27
8e4ff0743c [Test] Suppport intermediate_api llama test (#9850)
* suppport intermediate_api llama test
* fix
* add 70b
2025-02-18 15:40:53 +08:00
xuxinyi389
c42a3d6270 [AutoParallel]support_ppo_ckpt (#9823)
* support_ppo_ckpt

* fix readme

* fix_typo
2025-02-18 15:31:40 +08:00
Weiguo Zhu
71bfc333ad [Docs] news of DeepSeek (#9834) 2025-02-18 12:07:43 +08:00
Zhong Hui
ac980d3dc2 [Docs] fix docs for inference and servering (#9877)
* fix docs.

* refine docs.

* inference servering doc to one.

* fix

* refactor.

* fix link.

* add flask server doc.

* fix typo.

* model with new tab.
2025-02-17 19:25:45 +08:00
Zhuoqun Li
2e06a18d7a [LLM] move modeling.py and modeling_nv.py to transformers (#9676)
* move modeling.py and modeling_nv.py to transformers

* move modeling.py and modeling_nv.py to transformers and simplify import path

* move modeling.py and modeling_nv.py to transformers and add test_modeling

---------

Co-authored-by: DrownFish19 <DrownFish19@gmail.com>
2025-02-17 19:16:49 +08:00
xuxinyi389
5eeb7aa17a [AutoParallel] Support deepseekv2 with DP/MP (#9862)
* suppoort_deepseekv2_autoparallel_with_DP/MP

* poolish

* remove_env_set

* update_code

* add_v3

* support_sharding

* move_to_v3

* fix_typo

* update_v3_config
2025-02-17 15:50:27 +08:00
freeliuzc
235c24e984 [Inference]Support mtp with deepseek-v3 (#9856)
* support mtp with deepseek_v3 both in static and dygraph mode

* fix speculate tokenizer in unittest

* delete useless code
2025-02-15 18:14:56 +08:00
Zhong Hui
62eac0ca04 [PreTrain] Support deepseek mfu for pretraining and fix tflops for pretrain pipe model (#9855)
* git flops with pp model.

* Support hareware tflops for deepseek.
2025-02-15 16:45:37 +08:00
Weiguo Zhu
8f4e0f09d2 [Inference] Update deepseek (#9864)
* fix

* fix infra
2025-02-14 18:02:38 +08:00
QingshuChen
5ebe42b1ac [XPU] Add xpu fused op for deepseek (#9854) 2025-02-14 16:18:31 +08:00
Ruibiao Chen
98d27d659a Support XPU for auto-paralllel LLaMa (#9796)
* Support XPU for auto-paralllel LLaMa

* Update

* Update

* Update

* Update

* Fix CI errors

* Update
2025-02-14 16:03:23 +08:00
Zhong Hui
ca22425e06 [Optimization] Support lower memory cards. (#9804)
* support lower memory cards.

* add doc for v100 16G such devices.

* remove debug info.

* add pre divided factor to overcome overfit problem for fp16 attention.
2025-02-14 14:53:46 +08:00
Yuanle Liu
1ca1d593fe [Bugfix] Fix dsk rope diff (#9859)
* fix dsk diff

* fix

* update
2025-02-14 14:11:37 +08:00
Siming Dai
5a1c4ac0e0 save extra special tokens (#9837) 2025-02-13 14:20:11 +08:00
zty-king
3900428f6c Solve the compatibility problem of type annotation Python version (#9853) 2025-02-13 11:38:05 +08:00
Yuanle Liu
d53e39de17 [DSK] support deepseek-v3/r1 (mha/fp16/bf16/wint8/wint4) (#9769)
* support deepseek-v3

* support head_dim=192,256 for append_attn c16

* update 0113

* attention run

* refine code

* add softmax_scale

* support weight_only_int8

* refine code

* support tp

* delete test_append_attn

* add splited fused_moe from ziyuan

* fix repe for deepseek-v3

* add deepseek-v3 class

* fix wint8 precision and refine code

* fix wint4, big diff

* add e_score_correction_bias

* fix head_dim

* fix v3 verify

* fix d2s

* fix v3 verify

* support qk_head_dim != v_head_dim

* fix wint8 v_head_dim

* fix rope

* fix qwen2

* mla use position_ids only

* remove control flow

* remove gpu concat

* fix norm weight dtype

* remove all_reduce in fused_moe

* fix static run

* refine rope code

* compute position_ids use custom op

* fuse rope

* fix macro

* fix mixtral

* support mla for speculate

* fix tokenizer and qwen

* fix moe diff due to e_score_correction_bias

* fix fast tokenizer

* fix import

---------

Co-authored-by: lizhenyun01 <1500424927@qq.com>
Co-authored-by: lizhenyun <lizhenyun@baidu.com>
2025-02-13 00:21:25 +08:00
Tian
763c59af39 [LLM] fix checkpoint save for non flash mode (#9830) 2025-02-12 14:02:54 +08:00
Zhong Hui
85b77f2d90 [Inference] Flask server compatible with OpenAI api. (#9828)
* flask server compatible with OpenAI api.

* fix max_length to max_tokens.

* fix with think model.
2025-02-12 13:32:39 +08:00
Siming Dai
9ded9bf880 [Unified Checkpoint] Fix expert parallel (#9821)
* fix expert parallel

* fix split_param for expert parallel

* add filter_sync_parameters
2025-02-12 10:59:00 +08:00
lugimzzz
765ab8d076 [Mergekit]update & add LoRA merge (#9811)
* add

* fix bug

* fix

* add

* add lora merge

* add

* add

* add

* add

* add

* add
2025-02-11 17:46:33 +08:00
Weiguo Zhu
58fc49f32e [LLM] Add pipeline and flashmask for Qwen2Moe and Deepseek (#9827)
* add modleing_pp

* add modleing_pp for qwen2moe

* add flashmask and pp for Qwen2MoE and Deepseek

* remove

* fix fast_tokenizer save

* update for topk_weight of noaux_tc

* fix for flashmask

* add use_expert_parallel for pretrain

* fix tokenizer test
2025-02-11 16:23:55 +08:00
Weiguo Zhu
86286e09f8 Fix position_ids for infra (#9841) 2025-02-11 14:06:45 +08:00
Weiguo Zhu
55db2ff067 [Inference] Fix multibatch inference (#9831)
* fix batch infra

* fix deepseekv2 infra
2025-02-10 11:52:52 +08:00
will-jl944
eab22f2b4a [XPU] Support empty_cache on XPUs (#9789)
* [XPU] Support empty_cache on XPUs

* warn if current device doesn't support
2025-02-08 11:46:10 +08:00
Yuanle Liu
a9d8648120 [Readme] Update mixtral.md (#9829) 2025-02-07 12:02:23 +08:00
will-jl944
bad224079f Fix LLAMA arg parsing bug in pp (#9806) 2025-02-06 19:25:17 +08:00
YUNSHEN XIE
fa98268be9 修复benchmark多机任务异常退出的处理 (#9651)
* 修复benchmark多机任务异常退出的处理

* fix bug

* update
2025-02-06 17:09:19 +08:00
Chang Lu
54b8882079 [AutoParallel] add sharding tensor_fusion save load switch (#9810)
* support tensor_fusion save load

* apply suggestions from code review
2025-02-05 16:45:09 +08:00
Weiguo Zhu
96856bdd0e [LLM] Update model convert and fix TP for deepseekv3 (#9797)
* fix model convert and tp in MoEMLP

* fix tp_action filter

* update convert accoding to num_nextn_predict_layers

* add deepseek-R1
2025-01-24 18:12:08 +08:00
Siming Dai
3967f76e66 fix split_param (#9817) 2025-01-24 11:01:00 +08:00
Zhong Hui
2f85a64edd [README] Update README.md for documention (#9785)
* Update README.md

* Update README.md

* Update README_en.md
2025-01-23 11:41:43 +08:00
Ting
e247c85405 [Trainer] Wrap model when lora is ON and only do evaluation. (#9803) 2025-01-23 11:37:29 +08:00
Zhong Hui
30fa8b920d [CI] Fix ci of small models (#9633) 2025-01-23 11:16:31 +08:00
freeliuzc
bb103a32da [Inference] Support eagle for llama (#9812) 2025-01-23 11:14:32 +08:00
kevin
bb0c9ad75b [LLM] merge code from fastdeploy (#9791)
* [LLM] update llm server dockerfiles

* merge code from fastdeploy
2025-01-23 11:12:14 +08:00
Mangodadada
ac095f5096 mergekit gpu 1226 (#9702)
* mergekit gpu 1226

* merge model gpu

* merge gpu

* add lora model

* change valueerror

* add lora

* gpu test
2025-01-21 15:38:15 +08:00
Liujie0926
7c1c9baec7 [LLM Benchmark]update scripts (#9722)
* add no_proxy & del paddlenlp_ops

* update timeout for dpo

* fix sequence_parallel

* add timeout

* add Total_Tokens_per_second_per_gpu

* fix Tokens_per_second_per_gpu

* update Total_Tokens_per_second_per_gpu
2025-01-21 15:19:36 +08:00
Tian
730a7626ec [LLM] support flash device on static model (#9619) (#9787)
* [LLM] support flash device on static model

* [LLM] adapt pdc sdk
2025-01-21 14:52:10 +08:00
aooxin
fb3e4c0403 [Infer] Add pir_model path for server infer. (#9790) 2025-01-17 11:13:33 +08:00
Ting
d039ad2c56 fix dpo pp criterion (#9786) 2025-01-16 17:21:23 +08:00
Siming Dai
13053a7148 [MoE] fix expert parallel (#9760)
* fix moe uc
2025-01-16 14:14:37 +08:00
Weiguo Zhu
1afb9b2ed4 fix (#9779) 2025-01-15 13:22:22 +08:00
blacksheep-Aristotle
9e0b830eb1 Fix ce error (#9783)
* [AutoParallel]:fix ci error

* [AutoParallel]:fix ci error
2025-01-15 13:22:01 +08:00
Siming Dai
8fb109ae11 Update register_sequence_parallel_allreduce_hooks (#9782)
* fix sequence parallel

* update register_sequence_parallel_allreduce_hooks

* update fuse_sequence_parallel_allreduce
2025-01-15 11:15:06 +08:00
Tian
efd07c0e59 [Distributed] support fuse optimizer (#9519) (#9777) 2025-01-14 18:01:20 +08:00
Siming Dai
7b53fec78d [BugFix] Fix matryoshka norm loss (#9774)
* fix matryoshka norm
2025-01-14 17:32:42 +08:00
Zhong Hui
4bdb06c3ba Update README.md (#9766)
* Update README.md
2025-01-14 15:16:55 +08:00
blacksheep-Aristotle
595e74f331 Fix ernie ci auto trainer error (#9758)
* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* [AutoParallel]:fix ernine auto_trainer error

* Update run_pretrain_auto.py
2025-01-14 14:03:39 +08:00
greycooker
94e798f986 fix loraga merge (#9765)
* fix loraga merge

* change sign
2025-01-14 10:41:54 +08:00
Chang Lu
027b5304f5 [AutoParallel] open tensor_fusion for benchmark (#9749)
* open tensor_fusion for benchmark
2025-01-10 16:48:29 +08:00
Weiguo Zhu
2c556e76fb [LLM] Add DeepseekV3 (#9738)
* update deepseek-v2

* add deepseek_v3

* update for deepseekv3

* update deepseekv3 model_ids
2025-01-10 14:15:22 +08:00
Weiguo Zhu
cf5e3e72e1 [tokenizer] Fix AutoTokenizer (#9745)
* fix auto tokenizer

* fix auto tokenizer

* lint

---------

Co-authored-by: lyuwenyu <wenyu.lyu@gmail.com>
2025-01-10 14:07:55 +08:00
Siming Dai
b4325b980d [Trainer] update sequence parallel (#9757)
* update emb doc

* update register_sequence_parallel_allreduce_hooks

* update fuse_sequence_parallel_allreduce
2025-01-10 11:26:19 +08:00
will-jl944
331131b3af [NPU] Adapt to new flash_attention_npu api (#9762) 2025-01-10 11:10:14 +08:00
Longzhi Wang
048387fb5b [Inference] merge speculate_step into step op (#9674) 2025-01-09 19:08:25 -08:00
Longzhi Wang
9af0466f17 fix speculate_verify_and_update op (#9759) 2025-01-09 19:04:58 -08:00
lizhenyun01
55e7e33e2a fix get_block_shape_and_split_kv_block (#9752) 2025-01-08 23:13:32 -08:00
blacksheep-Aristotle
fb60645d8a [AutoParallel] Fix ernie auto_trainer error (#9753) 2025-01-08 19:48:40 +08:00
Jie.Z
1d74d62b82 [Model] Add XLMRoBERTaModel in paddlenlp (#9720)
* add xlm_roberta in paddlenlp
2025-01-08 16:56:56 +08:00
xuxinyi389
b286544727 [AutoParallel]ckpt support local views keys to global views keys (#9604)
* ckpt_support_moe

* fix_bugs
2025-01-08 16:15:43 +08:00
aooxin
95ae8a82aa [CI] Fix import bugs. (#9751) 2025-01-08 11:07:16 +08:00
blacksheep-Aristotle
06da1c3a96 [AutoParallel]: fix ernie ci error (#9750) 2025-01-07 18:06:58 +08:00
Siming Dai
67bc4e2cc2 [Unified Checkpoint] Fix expert parallel (#9741) 2025-01-07 11:16:26 +08:00
YUNSHEN XIE
142258ce8c Modify the environment variables and model configuration of the benchmark test case. (#9725) 2025-01-06 20:13:38 +08:00
Zhong Hui
171726d047 [BugFix] Update predictor.py (#9742) 2025-01-06 19:46:46 +08:00
Weiguo Zhu
4953500520 [Docs] Fix (#9746)
* add `Before submitting` for PR

* fix dead links

* fix dead links

* Update sync to avoid dead links.

* avoid fused_ln in README.md

* update scripts/get_modified_files.py

* update

* fix README.md
2025-01-06 19:46:15 +08:00
waliwali777
7e06e02528 [AutoParallel] Add test for PIR refined recompute (#9679)
* Add test for refine recompute

* move `refined_ops_patterns` flag to auto training args
2025-01-06 17:36:21 +08:00
will-jl944
1f07325ace Adapt to new npu flash_attention api (#9735) 2025-01-06 17:01:07 +08:00
Chang Lu
a83e8faadb [AutoParallel] add parameter enable_stage1_tensor_fusion_blanced_save_load and enable_stage1_tensor_fusion (#9714)
* add param

* update note
2025-01-06 14:04:19 +08:00
zhink
a52035f6ba Added FLAGS to replace four params and the value can be adjusted for better speedup (#9624)
* add FLAGS instead max_partition_size

* encoder_max_partition_size eq max_seq_len when encoder
2025-01-06 11:03:11 +08:00
aooxin
bb85eb42ab add common models and common params unit test for llm predictor. (#9711)
* add test_predictor_v1.

* del. src_length and fix bug.

* del. GPUsPredictorTest previous.

* update.

* activate ci

---------

Co-authored-by: Yuanle Liu <yuanlehome@163.com>
2025-01-04 07:22:59 +08:00
Tian
7713ca8a57 [LLM] [Cherry-Pick] Integrate PDC SDK for LLM training fault tolerance platform (#9706)
* Add PDC sdk (#9431)
* [LLM] support download ckpt from pdc (#9443)
---------

Co-authored-by: dongzezhao <2283296285@qq.com>
Co-authored-by: luoyuedong <530122286@qq.com>
2025-01-03 17:29:30 +08:00
will-jl944
3e15f0ec3b Add offload_recompute_inputs (#9715) 2025-01-03 14:14:04 +08:00
Zhong Hui
dac27c4a12 [Docs] Refactor custom devices. (#9734) 2025-01-03 11:37:46 +08:00
blacksheep-Aristotle
575896cca8 add single_model network and use intermediate api (#9412)
* add single_model network and use intermediate api

* [AutoParallel]: fix llama_model_network run error

* New version of auto config

* bug fix

* [AutoParallel]:add qwen run intermedaite api script

* fix sharding

* support attn_mask not None for pp

* fix for mp

* update api calling

* update the script

* add qwen mp/sp/pp config and process attn_mask and position_id

* fix issue of pipeline and add lazy_init

* fix gpt_network to use intermediate_api

* fix gpt_network to use intermediate_api

* [Auto Parallel] add llama2 7b/13b intermediate benchmark config

* update api

* update plan

* qwen fit base api

* fix alibi and attn_mask

* bug fix

* [AutoParallel]:gpt single network support tp to share_embedding

* [AutoParallel]:gpt single network support tp to share_embedding

* add intermediate ci

* add single_model network and use intermediate api

* New version of auto config

* fix sharding

* fix gpt_network to use intermediate_api

* fix gpt_network to use intermediate_api

* update ci loss baseline

* update gpt run_pretrain_py

* fix sharding error

* fix gpt format error

* [AutoParallel]:fix llama vpp ci error

* [AutoParallel]:fix llama A100 ci failed

* [AutoParallel]:update model formate

* [AutoParallel]:fix ipp error

* [AutoParallel]:fix a100 ci error

* [AutoParallel]:fix a100 ci error

* [AutoParallel]:update model_netowrk formate

* [AutoParallel]:add explanatory note

* [AutoParallel]:add explanatory note

* [AutoParallel]:add explanatory note

* Delete =1.0.0

---------

Co-authored-by: YuangLiu <liuyuang@baidu.com>
Co-authored-by: zhengzhonghui <zhengzhonghui@baidu.com>
Co-authored-by: jeff41404 <jeff41404@gmail.com>
2025-01-03 09:25:24 +08:00
yujun
fa3fd39a02 [Refined Recompute] Remove refined recompute deep copy (#9617)
* remove rr deep copy

* make sure test on gpu
2025-01-02 14:50:39 +08:00
Siming Dai
3a3bb653ed [Embedding] Fix embedding random (#9721) 2025-01-02 14:49:20 +08:00
lugimzzz
3aa9f4c339 [llm] Add KTO (#9689)
* add kto

* add kto

* add kto

* add kto'

* add kto

* add

* fix conflict

* add llm
2024-12-31 14:12:57 +08:00
Tian
dff62a10ea [LLM] [Cherry-Pick] add asynchronous metrics dumper for llm training (#9704)
* [LLM] add metrics dumper in background (#9049)

* [LLM] compat older paddlenlp for metrics dumper (#9072)

* fix exit bug for paddlenlp (#9237)

* fix UT

---------

Co-authored-by: ShenLiang <2282912238@qq.com>
2024-12-30 15:38:09 +08:00
Liujie0926
62274fa58c [LLM_benchmark]update LLM_benchmark scripts (#9662) 2024-12-30 14:54:10 +08:00
waliwali777
c080bb8d3f fix_recompute_test (#9672) 2024-12-30 11:12:47 +08:00
Ting
07ad5e61f5 support qwen dpo fused kernel (#9686) 2024-12-30 10:58:10 +08:00
lugimzzz
79695ccd74 [llm]support dpo pp for qwen & llama (#9695)
* support dpo pp

* add dpo pp

* add dpo pp
2024-12-27 16:53:01 +08:00
Tian
691ae01d14 [LLM] valid loss before optimizer step (#9255) (#9705) 2024-12-27 16:05:25 +08:00
zhink
7197b79c1d [Inference] Use cuda core(int8_sq) for m <=4 in gemm_dequant OP (#9707) 2024-12-27 14:07:01 +08:00
xuxinyi389
b53f7ebd67 fix_typo (#9703) 2024-12-27 11:01:36 +08:00
blacksheep-Aristotle
a0c4b4ccda update gpt&baichuan&qwen ce name (#9697)
* update gpt&baichuan&qwen ce name

* update gpt&baichuan&qwen ce name

* update gpt&baichuan&qwen ce name

* update gpt&baichuan&qwen ce name

* update gpt&baichuan&qwen ce name
2024-12-26 18:59:15 +08:00
xuxinyi389
8c04a159ad [AutoParallel] merge ckpt for inference (#9688)
* add_readme

* add_unified_ckpt

* fix typo
2024-12-26 18:02:28 +08:00
tianyuzhou668
f7f3957d24 [Iluvatar] Add readme for llama-13b (#9670)
Co-authored-by: tianyuzhou668 <tianyuzhou668@github.com>
2024-12-26 15:41:55 +08:00
chen
36d53337ed [LLM INFER] cutlass 3.x gemm on sm90 (#9398)
* cutlass 3.x gemm on sm90

* change cutlass to v3.5.1, because v3.5.0 don't support fp8 gemm on hopper

* support tune cutlass 3.x FP8 GEMM

* auto gen cutlass 3.x FP8 GEMM code

* add FP8 docs

* change FP8 tune, and remove -O3

* check

* check

* support dual gemm on sm90

* code check

* dual gemm cutlass kernel

* code check

* code check

* setup_cuda.py check

* delete invalid gemm config

* change gitignore

* Update csrc/setup_cuda.py

Co-authored-by: Yuanle Liu <yuanlehome@163.com>

---------

Co-authored-by: ckl117 <ck117@163.com>
Co-authored-by: Yuanle Liu <yuanlehome@163.com>
2024-12-25 23:06:15 -08:00
greycooker
d007615b91 fix loraga amp (#9699) 2024-12-26 15:02:12 +08:00
Jie.Z
40fa402dc4 [Embedding] Add inf-cl in embedding trainer (#9673)
* add inf-cl in embedding trainer
2024-12-25 17:19:25 +08:00
kevin
da320870f8 [LLM] Add deploy server (#9581)
* [LLM] add deploy server
2024-12-25 16:32:43 +08:00
sneaxiy
f67f421184 [MLU] Add MLU llama readme (#9671) (#9685)
Co-authored-by: PeiyuLau <135964669+PeiyuLau@users.noreply.github.com>
2024-12-25 12:47:30 +08:00
PeiyuLau
801682de72 [MLU] Add MLU llama readme (#9671) 2024-12-24 14:35:38 +08:00
sneaxiy
947ee9d669 Optimize performance for Qwen2 model (#9616)
* Optimizer performance for Qwen2 model

* fix format

* fix swiglu

* fix ut

* fix ut failure
2024-12-24 14:29:02 +08:00
Siming Dai
3374e7fcf9 [UnifiedCheckpoint] Add tied_weight_keys for pipeline model (#9663)
* update trainer.py

* fix tied_weights_keys

* update
2024-12-23 21:05:28 +08:00
Siming Dai
97ae9adc3c [Unified Checkpoint] bug fix for missing optimizer.safetensors.index.json (#9669)
* Update unified_checkpoint.py
2024-12-23 15:58:01 +08:00
yujun
1842d6d133 [Ops] Add paddlenlp_kernel for CUDA and Triton ops(#9471)
* add paddlenlp_gpu_ops

* add inf_cl loss function

* rename ppnlp_kernel

* rename paddlenlp_kernel
2024-12-23 14:36:04 +08:00
Liujie0926
f4f578cc40 [CI]update blacklist for gpt3 (#9555)
* update blacklist

* update

* update

* update

* update

* fix

* fix
2024-12-23 14:16:41 +08:00
Mangodadada
c6ab784b90 merge docs (#9657)
* merge docs1218

* docs

* fix soft link

* rename

* fix merge docs

* rename

* merge docs 1220

* merge docs
2024-12-23 11:06:10 +08:00
AIbin
e91c2d3d63 【Qwen2-VL Inference】add qwen2-vl high performance inference (#9575)
* qwen2-vl
2024-12-20 17:02:39 +08:00
Qiming Zhu
a26ddc4242 Structured Index of Documents (#9411)
* Structured Index of Documents

* 替换pdf为url

* 更改下载方式

* 更新README

* 更新README

* 修改环境安装指令
2024-12-20 15:28:23 +08:00
shang-mt
297dbced6b [Doc] [Mthreads] Support llama 13B pre-train (#9666) 2024-12-20 14:35:27 +08:00
Zhong Hui
029801da82 [DOC] Polish README of UC (#9668) 2024-12-20 14:20:16 +08:00
Siming Dai
9b6271271b [Trainer] update remove_master_weight (#9640) 2024-12-20 13:25:55 +08:00
zhengzhonghui
cae63987b7 [BugFix] Make the timer compatible with devices other than GPU (#9665) 2024-12-20 12:06:32 +08:00
wanly young
2d950b959a [DCU] update hygon dcu docs (#9298)
* update hygon dcu docs
2024-12-20 11:30:31 +08:00
will-jl944
0b6ed4ddb7 [XPU] qwen2 supports fused_rope (#9660) 2024-12-20 09:37:50 +08:00
lugimzzz
19fcdcbf17 fix lora (#9659) 2024-12-19 18:43:23 +08:00
blacksheep-Aristotle
25415fbe3d fix qwen&baichaun&gpt ci error (#9650)
* fix qwen&baichaun&gpt ci error

* fix qwen&baichaun&gpt ci error

* fix qwen&baichaun&gpt ci error

* fix qwen&baichaun&gpt ci error

* fix qwen&baichaun&gpt ci error

* add gpt_dy ce

* revert qwen&baichuan dygraph ce

* revert qwen&baichuan dygraph ce

---------

Co-authored-by: xuexixi <xuexixi@baidu.com>
2024-12-19 14:34:17 +08:00
Siming Dai
49d762f2ac [Trainer] update trainer.py for seed resume (#9656) 2024-12-19 14:19:15 +08:00
lugimzzz
e0ace1614b [llm]update peft docs (#9655)
* fix docs

* fix docs

* fix docs

* fix docs
2024-12-19 12:51:57 +08:00
lcykww
90bc68e163 MoRA Implementation (#9562)
* MoRA Implementation

* MoRA算法

* MoRA

* MoRA

* MoRA

* MoRA

* MoRA

* MoRA

* MoRA

* MoRA
2024-12-18 17:08:20 +08:00
Siming Dai
605a4eaad2 Update embedding trainer state (#9629)
* add trainer state

* add trainer_state
2024-12-18 16:16:51 +08:00
ZhenxingLi
047046635e [AutoParallel] Add config replace_with_c_embedding (#9638)
* update

* Update ci_case_auto.sh
2024-12-18 14:55:19 +08:00
will-jl944
b9cf723cc4 Fix paddle.where (#9652) 2024-12-18 14:46:22 +08:00
Mangodadada
fa0febce87 mergekit_with_sparsify (#9561)
* mergekit_with_sparsify

* mergekit_with_sparsify

* 参数上传修改

* change sparsify style

* test

* add merge

* add merge

* add merge

* add merge

* add test

* add tensor

* add merge

* add del

* add merge

* add merge

* del base

* del base

* alpha

* update follow comments

---------

Co-authored-by: lugimzzz <zhenglujing@baidu.com>
2024-12-18 12:24:15 +08:00
greycooker
407b3e6fc6 [PEFT]Add LoRA-GA (#9592)
* Support LoRA-GA initialization

* modify loraga_reinit

* Support multi GPU initialization

* support resume training and gradient offlaod hook

* remove trl/llm_utils.py

* use loraga trainer

* fix comment

* fix loraga

* change variable name
2024-12-18 10:36:44 +08:00
Siming Dai
2231feb068 [Embedding] Add embedding training (#9508)
* add Qwen2SentenceEmbedding

* add embedding trainer

---------

Co-authored-by: DrownFish19 <DrownFish19@gmail.com>
2024-12-17 20:51:28 +08:00
zhengzhonghui
da7a7d296f [AutoParallel] change loss_base after dropout support spmd (#9647)
* [AutoParallel] change loss_base after dropout support spmd

* [AutoParallel] change loss_base after dropout support spmd
2024-12-17 16:07:18 +08:00
waliwali777
4451c05879 Add replace_with_parallel_cross_entropy flag (#9579)
* Add replace_with_parallel_cross_entropy flag

* add a100 loss_base

* fix
2024-12-17 15:57:42 +08:00
Zhong Hui
12fba788c0 Update README.md for 3.0 beta3(#9644) 2024-12-17 15:56:59 +08:00
waliwali777
bb9793130e add test (#9621) 2024-12-17 15:55:45 +08:00
Weiguo Zhu
9eb3cfeafc [Tokenizer] Fix tokenizer of llama3.3 (#9641)
* fix tokenizer of llama3 and add test case

* fix paddle.where
2024-12-17 14:04:25 +08:00
Weiguo Zhu
dc0ca03b52 [LLM DOCs] Add deepseek models (#9643)
* update
2024-12-16 19:30:44 +08:00
Zhong Hui
5a94e04521 [Release] Update version for beta3 (#9553)
* Update README.md
2024-12-16 19:16:02 +08:00
lugimzzz
da41c4f252 [llm]add adam-mini (#9542)
* add adam-mini

* fix following comments
2024-12-16 16:41:11 +08:00
lugimzzz
f3ba5b3c6a [llm]update dpo criterion (#9620)
* update dpo criterion

* update dpo criterion
2024-12-16 16:41:01 +08:00
thinking-computer
5e1f01fd97 [Custom Devices] feat(sdaa): support sdaa backend infer (#9570)
1.add sdaa python paddlenlp_ops setup and README
2.update llm scripts and README
2024-12-16 15:11:42 +08:00
Weiguo Zhu
98a1cdc081 Add news (#9632) 2024-12-16 13:41:35 +08:00
Zhuoqun Li
c8aa7bf1a3 [Embedding] add llama and nv-embed training (#9323)
* add llama and nv-embed training

* add llama and nv-embed training and refine evaluation

* add llama and nv-embed training and refine evaluation

* add llama and nv-embed training and refine evaluation

* add llama and nv-embed training and refine evaluation

* add llama and nv-embed training and refine evaluation

* add llama and nv-embed training and refine evaluation

* add llama and nv-embed training and refine evaluation

* add llama and nv-embed training and refine evaluation
2024-12-16 12:04:45 +08:00
Siming Dai
7947bca07f Update unified_checkpoint.md (#9634) 2024-12-13 18:18:09 +08:00
Ting
e7a48db5a2 [DOC] Checkpoint Compression Doc (#9614)
* Checkpoint Compression Doc

* Update unified_checkpoint.md

---------

Co-authored-by: Siming Dai <908660116@qq.com>
2024-12-13 16:45:44 +08:00
Liujie0926
d3f3bbfc0a [LLM benchmark]add qwen2.5-7b (#9524)
* add qwen2.5-7b

* add qwen2.5-1.5b/14b

* add fix

* update data

* fix

* fix

* fix

* Update run_ci.sh

* update ips for dpo

* add llama2
2024-12-13 16:43:28 +08:00
Liujie0926
4102eb0719 [CI]update a100 loss_base for gpt (#9626)
* [CI]update a100 loss_base

* fix PaddleNLP_CI

* update

* update
2024-12-13 15:46:22 +08:00
Wangzheee
db38937b39 [Inference] Change norm outputs in dynamic and static mode(#9569) 2024-12-13 13:12:01 +08:00
Weiguo Zhu
c96260bb5b Fix link (#9628) 2024-12-12 17:20:19 +08:00
Yuanle Liu
f1126c1cbe [Inference] Fix docs and support llama3.2 (#9613)
* fix docs and use fast tokenizer default
* support llama3.2
2024-12-12 16:50:04 +08:00
Longzhi Wang
4f571798dd [Inference] Fix get_save_output op and refactor specu_decoding (#9576)
* fix get_save_output op and refactor specu_decoding
* add token_penalty for speculate decoding
2024-12-12 14:59:54 +08:00
will-jl944
70e80c7c4a Speedup FusedHeadAndCrossEntropy (#9601) 2024-12-12 11:42:20 +08:00
tianhaodongbd
23cf634dbf fix pp_config bug (#9605) 2024-12-12 11:21:28 +08:00
yinfan98
f445a7a56a 【Hackathon 7th No.43】TokenizerFast for Ernie (#9594) 2024-12-12 10:14:30 +08:00
wawltor
cd5468ca66 fix the d2s bug in qwen2 modeling (#9603)
* fix the d2s bug in qwen2 modeling

* update the code for the predictor
2024-12-11 22:28:08 +08:00
Ting
b7c6b4e7e6 [Unified Checkpoint] Fix checkpoint quant log (#9606) 2024-12-11 20:46:29 +08:00
Weiguo Zhu
272e715199 fix (#9612) 2024-12-11 19:15:31 +08:00
Siming Dai
b205922c1f update embedding trainer (#9608) 2024-12-11 17:31:52 +08:00
YUNSHEN XIE
b4f6e82a3d fix benchmark scripts (#9597) 2024-12-11 16:24:46 +08:00
greycooker
b31c627a22 [Trainer]Fix _get_eval_sampler (#9374)
* Fix eval sampler

* change sampler name
2024-12-11 16:21:05 +08:00
Weiguo Zhu
325deb506e [Requirements] Update protobuf version (#9118) 2024-12-11 11:37:32 +08:00
Weiguo Zhu
45eeac77e1 [LLM] update tensor and pipeline parallel for chatglmv2 (#9204)
* fix_chatglmv2_8k

* update modeling and modeling_pp
2024-12-11 11:35:19 +08:00
lugimzzz
9421c0ae87 fix dpo (#9607) 2024-12-11 11:21:58 +08:00
blacksheep-Aristotle
9f237b4dd9 [AutoParallel]:add gpt&baichuan&qwen ce (#9591) 2024-12-10 14:32:42 +08:00
zhangbo9674
009aca6e44 [CI] Add llama2-7b-cinn test (#9578)
* refine log
* refine
2024-12-10 11:15:20 +08:00
blacksheep-Aristotle
8ed579a683 [AutoParallel]:add gpt & baichuan auto ci (#9551)
* [AutoParallel]:add gpt & baichuan auto ci

* [AutoParallel]:add gpt & baichuan auto ci

* [AutoParallel]:add gpt & baichuan auto ci

* [AutoParallel]:add gpt & baichuan auto ci

* [AutoParallel]:add gpt & baichuan auto ci

* [AutoParallel]:fix attention_error

* [AutoParallel]:fix attention_error

* [AutoParallel]:fix attention_error

* [AutoParallel]:fix attention_error

* [AutoParallel]:add gpt&baichaun ci

* [AutoParallel]:add gpt&baichaun ci

* [AutoParallel]:add gpt&baichaun ci

* [AutoParallel]:add gpt&baichaun ci
2024-12-09 18:36:11 +08:00
Weiguo Zhu
eb4e6a1591 [DOC] Fix dead links (#9585)
* update docs/llm
2024-12-09 17:25:15 +08:00
tianhaodongbd
c565b77e75 [npu] fix where bug (#9573)
* [npu] fix where bug

* fix
2024-12-09 14:54:22 +08:00
sneaxiy
19172578c5 [Timer] Add gpu timer (#9582) 2024-12-09 14:41:39 +08:00
ZhenxingLi
5b54d716dd [AutoParallel] Fix ckpt oom paddlenlp (#9507)
* Update ckpt_converter.py
2024-12-09 11:14:52 +08:00
thinking-computer
b8942010b7 fix(export_model): fix export_model.py python path (#9571)
1.fix python path to paddlenlp project
2024-12-08 18:35:36 -08:00
yinfan98
753436afe0 【Hackathon 7th No.43】Tokenizer for Gemma (#9577)
* add gemma tokenizer

* fix lint

* rm version

* Update tokenizer_fast.py

* Update tokenizer_fast.py
2024-12-09 09:42:33 +08:00
tianhaodongbd
cfcd079ca1 Adapting npu for FusedHeadAndCrossEntropy (#9499)
* Adapting npu for FusedHeadAndCrossEntropy

* wrapper npu function
2024-12-06 16:28:25 +08:00
Liujie0926
a603a49568 [CI] update scripts (#9547) 2024-12-06 14:48:54 +08:00
HydrogenSulfate
dfbd8f9e10 [Develop] Update adam ops for support amsgrad (#9568) 2024-12-06 11:40:21 +08:00
yinfan98
8bd881434b 【Hackathon 7th No.43】TokenizerFast for GPT (#9548)
* add qwen2 tokenizer fast

* add qwen2 tokenizer fast

* fix

* add gpt tokenizer fast

* delete print

* Update utils.py

* Update ernie-gen

* Update data_tools

* Update tokenizer.py

* Update tokenizer_fast.py
2024-12-05 14:07:33 +08:00
Siming Dai
fb57a5e137 [Unified Checkpoint] fix load missing keys (#9523)
* fix load missing keys

* Update check_completion.py
2024-12-05 13:28:25 +08:00
Cheng Yanfei
8d9c341c5a [Intel_HPU]FSDPA custom kernel API update (#9556)
* sdpa API update

* sdpa fuse transpose
2024-12-05 11:23:59 +08:00
Longzhi Wang
e6b8e5bfe4 [INFER] Add more model support for speculate_decoding and refactor speculate_decoding (#9504)
* align the speculative decoding and SPECULATE_BSZ

* add specu_decoding support for Mixtral,qwen2,qwen2-moe
2024-12-05 11:22:17 +08:00
Leo Chen
14ed2a220b add llama3.1 config (#9541) 2024-12-04 19:54:04 +08:00
blacksheep-Aristotle
a2b5e18965 [AutoParallel]: add qwen model_auto and ci (#9538)
* [AutoParallel]: add qwen model_auto and  ci

* [AutoParallel]: add qwen model_auto and  ci

* [AutoParallel]:add qwen ci
2024-12-04 16:25:53 +08:00
will-jl944
733059312d [XPU] qwen2 supports flash_attn on XPU (#9549) 2024-12-04 15:32:09 +08:00
Ting
a5ec6bf623 run dpo script support qwen2 (#9543) 2024-12-04 09:52:29 +08:00
Yuanle Liu
f7da5a6ac3 [Infer] Delete generate_rank_mapping when export multi cards model (#9552) 2024-12-03 20:14:31 +08:00
Siming Dai
c4d79f47f7 Fix multi-threading load_state_dict (#9464)
* Update model_utils.py

* Update model_utils.py
2024-12-03 16:20:50 +08:00
Siming Dai
2b3d7bf02d [Unified Checkpoint] fix single card loading without master weights (#9540) 2024-12-03 14:21:24 +08:00
Zhong Hui
44b5b0bb7e [Fix] Update requirements.txt (#9514) 2024-12-03 13:15:24 +08:00
Zhong Hui
4d0fd0bdfc Support call sft training with clone PaddleNLP (#9516)
* init.

* refactor

* fix import.

* fix error.

* refactor

* fix

* refactor.

* fix

* refine

* fix argument update.

* refactor.

* refactor.

* refactor

* fix typo.

* fix.

* add missing.

* support short call sft training.

* add missing file.

* fix import

* add init file.

---------

Co-authored-by: gongenlei <gongenlei@baidu.com>
2024-12-03 13:09:07 +08:00
Zero Rains
2c1387f9f3 [INFER][LLM] Add the AutoPredictor for inference (#9445)
* add the AutoPredictor

* decoupling the model loading and predictor loading

* polish the AutoPredictor and AutoModel
2024-12-03 11:38:49 +08:00
yinfan98
7a221ccb0b 【Hackathon 7th No.43】TokenizerFast for Qwen2 (#9532)
* add qwen2 tokenizer fast
2024-12-02 20:38:54 +08:00
Yuanle Liu
2522bf8b70 [INFER] Fix tune_cublaslt_int8_gemm.py and remove dist_config (#9520) 2024-12-02 17:19:18 +08:00
tianhaodongbd
eae8d9f032 support offload/reload optimizer's states for custom device (#9467) 2024-12-02 15:34:21 +08:00
Weiguo Zhu
0b6284e00f [Inference] Update DygraphInferencePredictor (#9491)
* update DygraphInferencePredictor

* update batch_size
2024-12-02 15:33:07 +08:00
Weiguo Zhu
d45518172d [CI] Compatible with paddle.where (#9534)
* fix
2024-12-02 11:55:42 +08:00
zhangbo9674
fc25d3285c Fix ckpt convert bug1 (#9522)
* refine log

* refine

* fix

* fix
2024-11-29 19:30:53 +08:00
Ting
741785a3d9 support pp accuracy calculation (#9379)
* support pp accuracy calculation

* add pp accuracy ci

* add comment

* update

* mv logits accumulation to cpu

* refactor code

* code refactor

* remove ci, not support yet

* update
2024-11-29 14:12:38 +08:00
zhangbo9674
020a25fb86 Fix ckpt convert bug (#9521)
* refine log

* refine

* refine

* refine
2024-11-29 11:00:12 +08:00
Ting
2985f90327 support quant ckpt limit strategy (#9494)
* support quant ckpt limit strategy

* bug fix

* bug fix

* fix bug

* add log, fix bug
2024-11-29 10:22:00 +08:00
Weiguo Zhu
756bce7431 update (#9511) 2024-11-28 21:48:01 +08:00
Longzhi Wang
049b0b5cf8 Add document for speculative decoding (#9492)
* Add document for speculative decoding

* update

* update docu
2024-11-28 01:41:27 -08:00
Yuanle Liu
e23214b4c2 Fix csrc readme (#9515) 2024-11-28 17:38:06 +08:00
Zhong Hui
5926c30e93 [Refactor] SFTTrainer SFTConfig (#9318)
* refactor

* fix import.
2024-11-28 17:30:02 +08:00
YUNSHEN XIE
cbe5af14ab 移除CUDA_DEVICE_MAX_CONNECTIONS环境变量, 优化benchmark执行脚本 (#9500)
* CE case执行移除CUDA_DEVICE_MAX_CONNECTIONS环境变量

* 优化benchmark执行脚本

* update
2024-11-28 15:13:50 +08:00
Walter Wu
3ef14dc19b Adding LoKrModel Class to paddle.peft library (#9269)
* passing pre-commit

* removing tp and pp logic for single gpu training

* add disable_lokr attribute in lokr_layer

* refine comments

* add lokr tests and modified layer bug

* add lokrtests

* add lokrtests

* add lokr_argument.json

* add integration test, fix bugs based on tests.

* refactor lora_dim to lokr_dim

* no inference

* add more tests

* resolve merge conflict

* add more randtests

* pass isort check(maybe)
2024-11-27 20:52:07 +08:00
yujun
8d8a42cc85 [BugFix] fix pp eval (#9505) 2024-11-27 19:24:09 +08:00
yinfan98
a9a6b80a62 【Hackathon 7th No.43】TokenizerFast for BLOOM (#9407)
* add bloom tokenizer fast

* fix fast

* Update test_tokenizer.py

* fix lint

* reopen ci

* rerun ci

* fix ci

* fix bloom test

* fix bloom coverage test

* fix bloom coverage test

* add copyright for bert tokenizer fast

* add copyright for bloom tokenizer fast
2024-11-27 14:36:19 +08:00
yujun
b1466d7e6e [NEW Feature] 新增基于hook的refined_recompute支持 (#9396)
* 代码实现refined_recompute

* 更新rr的实现,新增单测测试pp和非pp

* update llama and support refined recompute

* update rr

* update

* update create_skip_config_for_refined_recompute config.num_hidden_layers

* update llama pp recompute

* refined recompute only support recompute_use_reentrant=False

* LOD_TENSOR

* typo

* rr 支持qwen模型

* support RRColumnParallelLinear & RRRowParallelLinear

* fix

* update llm test

* fix

* update test_refined_recompute
2024-11-27 10:34:34 +08:00
Yuanle Liu
f5ca96efcd [LLM INFER] not use gemm_dequant default and fix bug (#9498)
* not use gemm_dequant default and fix bug
2024-11-26 20:51:11 +08:00
enzodechine
4b02477458 [XPU] set appropriate mask value for xpu (#9495) 2024-11-26 16:31:31 +08:00
zhink
0b4b810ae6 [Inference] use fp8 cuda core gemm kernel when M<=4 (#9423) 2024-11-26 13:29:41 +08:00
Weiguo Zhu
d6d181b719 [Tokenizer] Support fast tokenizer within AutoTokenizer import (#9466)
* add tokenizerfast import

* add test case
2024-11-26 12:00:53 +08:00
blacksheep-Aristotle
6141f80b17 [AutoParallel]:fix baichuan d2s fail (#9478) 2024-11-26 11:47:11 +08:00
lvdongyi
131888eb2c [ChatTemplate] Fix chat template for Yuan when answer is contained within question. (#9485)
* Fix chat template for Yuan when answer is contained within question

* add more models to test
2024-11-26 11:22:49 +08:00
Chang Lu
d9a4e682a1 [AutoParallel] open vpp test cast at v100 machines (#9468)
* update

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh
2024-11-26 10:48:37 +08:00
Weiguo Zhu
8fd33a9518 [Fix] Remove data args print (#9486) 2024-11-25 15:54:21 +08:00
Longzhi Wang
d68a385fcf [LLM INFER] Support speculative decoding (llama) (#9180)
* add specu_decoding custom cuda kernels

* rename the speculate_update kernel to speculate_verify_and_update kernel

* Add the speculate_decoding framework

* Add licence and more comment

* fix top_p_candidates and add cooment for proposer

* fix top_p_candidates

* add static graph support for speculate_decoding

* fix specu_decoding framework

* v1.0: fix accuracy of the framework

* fix custom op

* fix comment and add type annotation

* fix custom_op and speculate_read_res

* update

* update

* add input_ids_cpu for proposers to align with inner implementation

* fix typo

* update and add test

* fix the place of proposers

* fix code lint

* fix test

* remove the unused custom op

* remove the unused custom op

* merge speculate custom op

* fix conflict

* fix typo

* fix typo

* merge custom op and fix code style

* fix circular import

* fix circular import

* fix circular import

* fix typo

* fix import

* fix static

* refactor test

* refactor test

* refactor get_output and save_with_output_msg

* merge the SpeculatePredictor to BlockPredictor

* refactor read_res

* fix conflict and refactor comment
2024-11-24 21:55:21 -08:00
张明明
e3db4c048f fixbug for chatglm_v2's RetaryEmbedding dtype (#9476) 2024-11-24 21:54:15 -08:00
Ting
195fde32b8 [Unified Checkpoint] Checkpoint compression (#9183)
* checkpoint compression init

* add ckpt quant argument

* add ckpt quant ci

* fix ci

* fix lint

* remove stage O2, change O3 --> O2

* support async save

* file adjustment

* magic string remove

* ci fix

* ci fix, code refinement

* function extraction

* fix ci

* code refinement

* fix ci

* fix ci

* support non merge tp ckpt quantization

* fix ci

* update

* fix bug

* code refactor

* fix lint

* fix ci

* del old uc.py

* fix lint

* add mgpu ci

* fix ci

* multi thread loading

* fix lint

* fix bug

* refactor code

* add comment

* fix lint

* add comment

* add comment

* fix bug

* fix bugs when ckpt no quant and no master weight

* remove uni-test
2024-11-25 11:38:02 +08:00
blacksheep-Aristotle
58a6eb9c03 [AutoParallel]:fix run llama_13b_auto error (#9480) 2024-11-25 10:49:17 +08:00
Chang Lu
1ba3bef24b add param (#9481) 2024-11-22 21:27:29 +08:00
lixc
9494e9a380 [Inference]Move quantization code from run_finetune.py to run_quantization.py (#9450)
* 1. Move quantization code from run_finetune.py to run_quantization.py
2. Remove experimental code about quantization in llm/experimental. These code will merge in Paddleslim.

* repair experimental/ceval

* update readme and remove useless code

* add test for run_quantization

* update wrong comment

* update qwen2 fp8 quantization config
2024-11-22 17:11:26 +08:00
Siming Dai
7bfe5bc006 Fix eval for map dataset (#9472) 2024-11-22 14:58:10 +08:00
TranscenderNing
183e01201a add Moslora (#9331)
* add mos lora

* add tests

* correct something by comment

* add tests code for coverage rate
2024-11-22 10:15:50 +08:00
blacksheep-Aristotle
1ca1d4992b [AutoParallel]:gpt 13b model support fused_linear sp fused_attention and add gpt 13b pir ci (#9477) 2024-11-22 10:08:58 +08:00
blacksheep-Aristotle
b690222c50 [AutoParallel]: llama_model_auto support alibi (#9422)
* [AutoParallel]: llama_model_auto support alibi

* [AutoParallel]: llama_model_auto support alibi

* [AutoParallel]: llama_model_auto support alibi

* [AutoParallel]: change model_auto shard logits so change the loss base

* [AutoParallel]: change model_auto shard logits so change the loss base

* [AutoParallel]: fix llama run vpp error when use alibi
2024-11-22 10:08:26 +08:00
TranscenderNing
9ee691ac5f add reft method (#8819)
* solve lint error

* resolve test err

* add tests

* dependency error

* add tests for reft

* Supplementary test cases

* Supplementary test cases1

* Supplementary test cases11

* Supplementary test cases111

* correct CI-Unittest error

* correct CI-Unittest error

* correct CI-Unittest error

* correct CI-Unittest error1

* simplify code

* simplify codes

* delete reft

* make lint tidy

* add more tests

* unify trainer and simplify codes

* test predict

* delete nohup

* correct CaualTrainer to SFTTrainer

* test tests

* solve tests question

* solve conflict

* add set_seed

* solve set seed

* gpt3-ci err

* solve gpt3 ci problem
2024-11-21 18:59:28 +08:00
Yuanle Liu
90a1e335fd fix AutoInferenceModel for qwen-vl (#9463)
* fix AutoInferenceModel for qwen-vl

* fix AutoInferenceModel for qwen-vl

* fix readme.md in csrc

* fix export_model.py
2024-11-21 18:24:37 +08:00
whf313
6813e40b67 Revised PoSE (#8822)
* Yarn

* Revise

* Delete paddlenlp/transformers/llama/modeling_new.py

* Delete paddlenlp/transformers/llama/modeling_sparse.py

* Delete paddlenlp/transformers/long_sequence_strategies/embedding_strategies_old.py

* Delete paddlenlp/transformers/long_sequence_strategies/embedding_strategies_yarn.py

* Delete llm/run_finetune_old.py

* Update data.py

* Update test_long_sequence_strategies_pose.py

* Update test_long_sequence_strategies_pose.py

* Create test_long_sequence_strategies_pose.py

* Update and rename test_long_sequence_strategies_pose.py to test_yarn.py

* Delete tests/peft/test_yarn.py

* Update run_finetune.py

* Update pyproject.toml

* Update pyproject.toml

* Add files via upload

* Update pyproject.toml

* Revise

* Revised

* Revised

* Revised

* update

* update

* update
2024-11-21 16:06:41 +08:00
wawltor
5a343cf93a fixed the init problem in tensor parallel (#9452) 2024-11-21 15:26:41 +08:00
HydrogenSulfate
2b8a77b711 Update modeling_auto.py (#9461)
use paddle.cast instead of Tensor.astype
2024-11-21 15:23:17 +08:00
lvdongyi
872aafa093 [Tokenizer] Fix chat template for Gemma when answer is contained within question (#9462) 2024-11-21 10:15:38 +08:00
waliwali777
5ceb930bc3 Fix auto parallel CI exit -6 (#9460)
* merge two function list

* move env set before func running

* fix

* fix track case result status

* fix
2024-11-20 21:07:04 +08:00
Chang Lu
bd1fd926c5 [AutoParallel] Reconstruct sharding mesh dimension inference logic - Part2 add sharding_mesh_dimension param (#9382)
* add custom sharding_dim

* Update training_args.py

* Update auto_trainer.py

* Update auto_trainer.py
2024-11-20 20:27:14 +08:00
lugimzzz
d74df4d0ef add set_seed (#9429) 2024-11-20 16:10:27 +08:00
YUNSHEN XIE
db7ed0feac 增加benchmark多机任务执行脚本对于异常退出的处理 (#9442)
* 处理多机任务CE case的异常退出,增加对于训练日志更新状态的监控

* update

* Set execution variables for CE cases
2024-11-20 15:39:31 +08:00
Weiguo Zhu
590081a968 [LLM] Add expert parallel (#9368)
* add expert parallel utils

* update gates

* update

* update base methods

* update moe_layer

* update moebase

* add moe_gate and moe_layer for qwen2moe

* add config

* update

* update gate dtype

* update moe gate and layer

* update moe_layer.py

* update

* update

* update token_priority method

* update data type

* remove old moe

* fix moe capacity reduce.Max

* update comment

* lint
2024-11-20 14:57:46 +08:00
Weiguo Zhu
ca1af448f8 [ChatTemplate] Fix chat template when answer is contained within question. (#9444)
* fix chat template

* remove ans generation_prompt

* fix

* remove split test case

* add comments

* update

* revert fix

* fix qwen2 chat_template

* compatible with python 3.10

* support add token and update chat_template for llama3

* revert llama chat_template
2024-11-20 14:56:57 +08:00
Weiguo Zhu
554941fa7a update (#9447) 2024-11-20 14:56:35 +08:00
Chang Lu
d5a90f74ca [AutoParallel] add release_gradients and comm_buffer_size_MB to strategy (#9432)
* add release_gradients and comm_buffer_size_MB to strategy

* Update training_args.py

* add note

* fix codestyle
2024-11-20 13:56:49 +08:00
liym27
79bba4fa35 update conf for sharding overlap in auto_parallel static (#9456) 2024-11-19 21:44:36 +08:00
gongel
619c1b9279 refactor tool of creating pretrain dataset (#9454) 2024-11-19 20:17:25 +08:00
will-jl944
707240627d Fix row parallel lora layers parameters initialization bug (#9427)
* Fix row parallel lora layers parameters initialization bug

* Fix ColumnParallel LoRA layers

* Fix QuantLora param init bug
2024-11-19 17:26:19 +08:00
waliwali777
3fe6aba68e Reduce long duration for the exit -6 re-run process. (#9400)
* Reduce long duration for the `exit -6 re-run` process.

* fix

* Add export env

* Add log colorful
2024-11-19 15:58:51 +08:00
lugimzzz
f21329c279 fix pp no drop last (#9439) 2024-11-19 14:50:13 +08:00
Siming Dai
801dd74002 Update dist_dataloader.py (#9451) 2024-11-19 14:44:22 +08:00
Siming Dai
2ecf7ef484 [DistDataloader] fix eval new_group (#9438) 2024-11-18 21:27:09 +08:00
Weiguo Zhu
04291490f7 fix import in py38 (#9446) 2024-11-18 19:02:39 +08:00
co63oc
d971b2af4c Fix (#9419) 2024-11-18 18:59:18 +08:00
co63oc
a11367af72 Fix (#9434) 2024-11-18 18:58:51 +08:00
Dangweichong
81a2d43c6f [DCU] update dcu paddlenlp_ops (#9433) 2024-11-14 18:58:31 -08:00
Siming Dai
921fc44a4f [Unified Checkpoint] Support sharding_comm_overlap (#9392)
* update
2024-11-14 16:08:10 +08:00
Zero Rains
018b5300c4 [INFER][LLM] Add the AutoModel for inference mode (#9416)
* add the AutoModel for inference mode in dynamic graph

* add the AutoModel for inference mode in static graph

* create AutoInferenceModelForCausalLM class  and polish the code

* fix the return result

* add the confirm_inference_model method

* roback the AutoModel

* modify the description

* update
2024-11-13 23:13:49 -08:00
Liujie0926
c9cfa99f4a [CI]update target_lists_for_llm (#9417)
* update target_lists_for_llm

* add scripts/regression
2024-11-13 19:30:00 +08:00
Dangweichong
09d2c14c47 fix hip paddle_nlp_ops bug (#9418)
Co-authored-by: root <root@localhost.localdomain>
2024-11-13 01:09:05 -08:00
Jianbang Yang
2838e80e9d [XPU] llama swiglu uses Paddle's native swiglu (#9414) 2024-11-13 09:24:57 +08:00
zhangbo9674
10a62c7a36 [AutoParallel] refine log (#9397) 2024-11-11 17:45:04 +08:00
lugimzzz
b5e3f0cccb [LLM]add ktotrainer (#9393)
* add ktotrainer

* fix oom
2024-11-08 16:54:22 +08:00
Liujie0926
5c6279abc3 [CI]fix scripts (#9394)
* fix ci scripts

* [CI]add recursive for submodule

* [CI]fix
2024-11-08 16:53:08 +08:00
Liujie0926
eca4da486f [CI] add recursive for submodule (#9389)
* fix ci scripts

* [CI]add recursive for submodule
2024-11-08 10:28:26 +08:00
risemeup1
140ea48e20 Add submodule (#9385)
* add submodule

* add submodule
2024-11-07 15:41:18 +08:00
Siming Dai
d526be29d2 [Unified Checkpoint] Support empty state_dict saving (#9380)
* fix empty state_dict

* update sharding split_parma
2024-11-07 11:39:41 +08:00
tianyuzhou668
2f0b407d4a [Llama] Support pp + no_recompute_layer. (#9373)
Co-authored-by: 周天宇 <tianyu.zhou@iluvatar.com>
2024-11-06 17:03:51 +08:00
waliwali777
3971fc7c5f [AutoParallel] Fix EXCODE bug of AutoParallel CI (#9355)
* Fix exitcode bug

* Fix `track_case_status` func match bug

* Fix return code

* Fix print_info func with exit -6

* set output format of fail tests
modify verification check failed
2024-11-06 16:18:06 +08:00
gaoziyuan
09778587d6 [LLM INFER] Optimize fuse some kernels in postprocess (#9201)
* optimize fuse some kernels

* optimize fuse some kernels

* fix top_p reject

* fix

* ci

* fix review

* fix
2024-11-05 19:55:12 -08:00
zhangyuqin1998
19a2e1f5aa [Auto Parallel] fix adapt_stale_fwd_patch for to_static mode (#9372) 2024-11-06 10:24:30 +08:00
Siming Dai
85333aa6ad [Trainer] Update assert to warning (#9332)
* mv assert to warning
2024-11-05 14:34:28 +08:00
ShenLiang
9d658a9997 Add check for sharding stage1-v2 using amp master grad (#9333) 2024-11-05 14:33:55 +08:00
wanghuancoder
ab62e477a2 refine dtype use (#9366) 2024-11-05 14:11:16 +08:00
ShenLiang
565a6ab150 Add offload/reload for optimizer (#9359)
* support optimizer state offload (#8715)

* support optimizer offload

* update doc

* [FleetY]offload optimizer state after load optmizer state (#9352)

* add offload optimizer

* fix memory

* [FleetY] Add reload/offload for optimizer (#9356)

* add reload/offload for optimizer

* fix bug

---------

Co-authored-by: Guoxia Wang <mingzilaochongtu@gmail.com>
2024-11-05 10:10:09 +08:00
Weiguo Zhu
55a1bcb6d8 fix (#9363) 2024-11-05 10:06:58 +08:00
Siming Dai
e2cc3d5ae4 [Unified Checkpoint] Fix fp32 dtype for using newest paddle(#9360) 2024-11-04 19:23:50 +08:00
Leo Chen
1aa91be7bf clean print in auto_trainer (#9357) 2024-11-04 17:11:12 +08:00
lvdongyi
cd22b0de17 [Tokenizer] Add BertTokenizerFast, support register new tokenizer (#9353)
* Add , support register tokenizer, fix some typo

* add more tests

* CustomTokenizerFast2->CustomTokenizerFastWithoutSlow

* lint
2024-11-04 16:31:03 +08:00
chen
5217a3b795 [Inference] Append attn FP8 quant (#9328)
* add fp8 gen files to gitignore

* append_attn support fp8 quant

* Unified FP8 Network

* include cuda_fp8.h

* simplify qwen2 network and FusedBlockMultiTransformerFP8

* simplify llama network and code check

* check fp8 params

* code check

* check

* default config for fp8 gemm
2024-11-03 23:34:29 -08:00
waliwali777
582ff5eb2c Add CI testing for A100 and V100 device (#9324)
* Add ci for A100 and V100 device

* Fix device judge

* fix compare of float var

* Add output of test failed

* Fix cal fail test count

* Remove compare_float fun with `!=` to compare

* Fix output of fail tests

* Run  gpt-3_dygraph when related files modified

* add track status( fail tests ) for every case

* Add track status of loss verification failed test

* Move output position of every case

* modify `exit` to `return 0`
2024-11-04 10:55:58 +08:00
JZ-LIANG
66c5d65f18 [AutoParallel] Hang Bugfix for VPP-Sharding (#9336)
* bugfixed
2024-11-01 16:54:27 +08:00
ShenLiang
ba5c2ca330 Add ordered save to avoid OOM (#9347) 2024-11-01 14:52:33 +08:00
Weiguo Zhu
71dafa679f [Tokenizer] Support adding special tokens to Qwen tokenizer (#9344)
* update qwen tokenizer

* add test case
2024-11-01 14:33:33 +08:00
Weiguo Zhu
149cfa8789 [Docs] Add precision alignment doc (#9346)
* add precision alignment doc
2024-11-01 14:32:48 +08:00
Weiguo Zhu
8279b14497 [Tokenizer] Fix Llama3Tokenizer import (#9341) 2024-10-31 17:05:07 +08:00
Weiguo Zhu
483fff4adb Compatible with Tensor.to change to out_of_place. (#9343) 2024-10-31 15:38:30 +08:00
Cheng Yanfei
ce083f0739 [intel_hpu] initial commit for intel_hpu support (#9273)
* add intel hpu device

* add wa for intel hpu

---------

Co-authored-by: Zhai Feiyue <feizhai@habana.ai>
2024-10-31 11:13:21 +08:00
Leo Chen
26b73c2644 align default custom black/white list for dygraph and static graph (#9340) 2024-10-30 23:10:25 +08:00
lvdongyi
ec25cb8c84 [Tokenizer] Support reading Tiktoken tokenizer.model. (#9215)
* add support of tiktoken tokenizer, refactor some code

* add case of built-in tokenizers to handle CI error
2024-10-30 12:03:38 +08:00
Weiguo Zhu
f5f9d8524c Update README.md (#9339) 2024-10-30 11:50:38 +08:00
Siming Dai
78f911afb1 Update load_save_single_card.py (#9337) 2024-10-30 09:48:40 +08:00
Weiguo Zhu
3f1787fdf2 [Docs] Update flashmask (#9330)
* Update flashmask.md

* update link
2024-10-29 19:19:42 +08:00
Leo Chen
ec3973793d fix parameter calculation in auto_parallel mode (#9327) 2024-10-29 16:48:47 +08:00
Yuanle Liu
9575245c7b fix bug (#9335) 2024-10-29 15:20:01 +08:00
Yuanle Liu
f0aa672220 [LLM INFER] add rope_theta for block_multihead_attention (#9334)
* add rope_theta for block_multihead_attention
2024-10-29 15:13:13 +08:00
bukejiyu
975d5c72e4 [Inference] fix paddle cpu docs. (#9299) 2024-10-29 11:29:06 +08:00
Siming Dai
ce3a1ce11e [Unified Checkpoint] update non-merge checkpoint loading, move async_save_info.json location (#9321)
* [Unified checkpoint] update optimizer async save signal

* update async_save_info.json file place
2024-10-28 20:41:59 +08:00
Mangodadada
394aadaf83 fix readme (#9326)
Co-authored-by: huxinye <2392038429>
2024-10-28 20:07:03 +08:00
Mangodadada
2993974626 add flash_attention on model chatglm_v2 (#9296)
* add flash_attention on model chatglm_v2

* add flash attn and consider sequence parallel

---------

Co-authored-by: huxinye <2392038429>
2024-10-28 20:06:27 +08:00
Weiguo Zhu
7e37028bc0 Update QR code (#9325) 2024-10-28 17:51:50 +08:00
idontkonwher
05ae377f92 [METAX] Support llama for MX C550 (#9186)
* [METAX] Support llama for MX C550

* fix typo, add paddlenlp branch, add greedy strategy for demo

* add MXMACA software stack acquisition path
2024-10-28 15:32:17 +08:00
Siming Dai
c9d5673416 [Unified Checkpoint] Add split param and refactor code (#9240)
* [Unified checkpoint] update optimizer async save signal

* update paddlepaddle

* split param

* add save for split param

* fix save split_param

* add load uc split_param

* update uc files

* update uc files

* update split_param loading

* mkdir unified_checkpoint directory

* rename file

* update async handler

* update files

---------

Co-authored-by: gongenlei <gongenlei@baidu.com>
2024-10-28 13:14:11 +08:00
Yuanle Liu
81f5ab5452 update llm infer docs (#9314)
* update llm infer docs

* update
2024-10-25 18:43:08 +08:00
lugimzzz
81ffc78715 [Doc] Add flash mask (#9219)
* add flash mask

* translate

* translate

* update introduction
2024-10-25 16:19:12 +08:00
Yuanle Liu
2e8b220eb8 [LLM INFER] Fix some bugs and chatglm_v2 support block_attn (#9271)
* chatglm2 support block_attn and fix some bugs
* fix ci
* fix more ut error
* update
2024-10-25 15:06:23 +08:00
Lucas
b237ba7868 [XPU], support unified ckpt function (#9312) 2024-10-25 14:54:21 +08:00
Zhong Hui
2bf3d7f27e [TRL] Rename sft trainer. (#9292)
* rename sft trainer.
2024-10-25 14:08:20 +08:00
wawltor
75f44ef747 change the directory legacy to slm (#9311) 2024-10-25 10:52:59 +08:00
gongel
ff7ee8ade8 Fix non-pipelayer to distributed (#9310) 2024-10-24 17:51:50 +08:00
CrystalX
75517304a7 [Unified Checkpoint] Accelerate loading checkpoint by multi-thread (#9034)
* [Unified Checkpoint] speed up loading checkpoint by multi thread

* [Unified CHeckpoint] speed up load by multi-thread

* [Unified CHeckpoint] speed up load by multi-thread

* [Unified CHeckpoint] speed up load by multi-thread

* Unified CHeckpoint] speed up loading checkpoint by  multi-thread

* Unified CHeckpoint] speed up loading checkpoint by  multi-thread

* Unified CHeckpoint] speed up loading checkpoint by  multi-thread

* Unified CHeckpoint] speed up loading checkpoint by  multi-thread

* Unified CHeckpoint] speed up loading checkpoint by  multi-thread

* Unified CHeckpoint] speed up loading checkpoint by  multi-thread
2024-10-24 14:18:16 +08:00
Leo Chen
6211e3d38f clean llama static modeling file (#9301)
* clean llama static modeling file

* update readme

* fix

---------

Co-authored-by: wangnian01 <wangnian01@baidu.com>
2024-10-23 16:42:37 +08:00
Jianbang Yang
0102f311b4 [Tokenizer] Fix TokenizerFast missing clean_up_tokenization_spaces (#9304) 2024-10-23 15:17:23 +08:00
zhangyuqin1998
a564483f67 [Auto Parallel] fix bugs for split_batches_for_accumulation && fix bu… (#9217)
* [Auto Parallel] fix bugs for split_batches_for_accumulation && fix bugs for enable_delay_scale_loss

* add enable_delay_scale_loss flag for auto_parallel

* fix ut

* Update ci_case_auto.sh
2024-10-23 15:16:00 +08:00
Yuanle Liu
31c6b9a670 [LLM INFER] Append attn (#9244)
* refine paddle::empty(), fix memory error, support multi_stream for attention

* fix and rename attention as append_attention

* rename file
---------

Co-authored-by: lizhenyun <lizhenyun@baidu.com>
Co-authored-by: lizhenyun01 <1500424927@qq.com>
2024-10-23 12:06:53 +08:00
lugimzzz
3443b9f097 fix lora sharding v2 (#9300) 2024-10-22 20:37:18 +08:00
Yuang Liu
51f6a4b2fa [XPU] bug fix for xpu_parallel_matmul tensor parallel output. (#9297) 2024-10-22 16:25:42 +08:00
Weiguo Zhu
76a118b808 [FlashMask] Add FlashMask for Qwen2 (#9264)
* add flashmask
2024-10-21 15:05:49 +08:00
Guoxia Wang
220cc95c48 Support attention mask using causal=True for Baichuan 13B (#9268) 2024-10-21 11:10:31 +08:00
Weiguo Zhu
fe8b527a59 [CI] Fix llm/alignment/rm/flashmask path (#9289)
* fix llm/alignment/rm/flashmask

* update
2024-10-19 22:22:43 +08:00
Weiguo Zhu
1770b51ac6 [Tokenizer] Unify tokenizer _pad (#9280)
* add test cases for 3D attention_mask and attn_mask_startend_row_indices

* update attn_mask_startend_row_indices return type
2024-10-18 15:22:23 +08:00
Weiguo Zhu
b62ae984a5 [LLM] Add deepseekv2 (#9250)
* add deepseekv2
* update softmax_scale and attn_weights
---------

Co-authored-by: huxinye <2392038429@qq.com>
2024-10-18 14:39:10 +08:00
Weiguo Zhu
1dc6e18c48 [CI] Skip inference test cases (#9270)
* skip inference test cases
2024-10-18 14:09:03 +08:00
Siming Dai
2b975b1974 [Trainer] fix save_model (#9286)
* bug fix

* bug fix
2024-10-17 23:23:32 +08:00
Weiguo Zhu
5244e615a6 [Tokenizer] Enable padding_side as call time kwargs (#9258)
* enable padding_side as call time kwargs

* [padding_size] Compatible with self._pad without padding_size

---------

Co-authored-by: lvdongyi <lvdongyi1222@gmail.com>
2024-10-17 19:30:23 +08:00
zhangbo9674
5d45695d02 [AutoParallel] Change llama test from sharding stage2 to stage1 (#9281) 2024-10-17 17:45:21 +08:00
Siming Dai
823d69f789 [BugFix] Fix async hang (#9276)
* update async save signal

* fix async save hang
2024-10-17 12:13:43 +08:00
Mangodadada
cf0f478865 [DOC] Add config file for model chatglm2,gemma,yuan (#9139)
* add config file for model chatglm2,gemma,yuan

* fix dpo.md file, add soft link, fix readme.md

---------

Co-authored-by: huxinye <2392038429>
2024-10-16 19:18:04 +08:00
Siming Dai
697a4cc59e [Unified Checkpoint] update async save logic (#9274)
* update async save signal

* fix async save hang
2024-10-16 14:53:20 +08:00
lugimzzz
b090f18a3e change dataset (#9266) 2024-10-16 11:48:18 +08:00
liym27
e9532bc8c2 Fix tests for pass paddle AutoParallel CI (#9267) 2024-10-15 19:35:24 +08:00
Weiguo Zhu
5ad7a9c376 [Unified Checkpoint] Fix generation config save (#9223) 2024-10-14 22:40:03 +08:00
LiYuRio
0e96b0f37e Cherry-pick some PRs from incubate/paddlenlp-fleety (#9253)
* support pp-sharding reshard (#9153)

* support best unbalaced pp scheduler (#9235)

* remove pp hack (#9189)

---------

Co-authored-by: Meiyim <chenxuyi@baidu.com>
2024-10-14 17:00:52 +08:00
Yuanle Liu
3007c7912d [BugFix] fix pir dt2st (#9251) 2024-10-14 14:35:49 +08:00
Siming Dai
d46bc06fd2 [Unified Checkpoint] Support expert parallel (#9055)
* update code
2024-10-14 11:37:08 +08:00
sneaxiy
80916db4cf Cherry-pick some PRs from incubate/paddlenlp-fleety (#9245) 2024-10-12 16:41:48 +08:00
Yuanle Liu
04f3c20f37 [PIR] fix pir open bugs (#9248) 2024-10-12 10:36:58 +08:00
vivienfanghuagood
8a43b0f841 [CI] Reduce the time spent on git downloading third-party libraries (#9246) 2024-10-12 10:35:34 +08:00
Yuanle Liu
156182e715 [INFER] update tune_cublaslt_gemm op and fix some bugs (#9222) 2024-10-11 14:26:10 +08:00
gaoziyuan
f9eb62edc4 [LLM INFER] top_p_sampling_reject support top_p=0 and custom seed (#9202)
* fix top_p reject
2024-10-11 14:22:33 +08:00
zhangyuqin1998
ea37a6971e [Auto Parallel] Adding align mode support (#9150) 2024-10-11 11:52:59 +08:00
Weiguo Zhu
8b2cc08193 [version] update version info (#9241) 2024-10-11 09:41:44 +08:00
Zhong Hui
d2d0ae6aa8 [CI] Fix ci import. (#9239)
Co-authored-by: lugimzzz <zhenglujing@baidu.com>
2024-10-10 20:17:05 +08:00
zhangbo9674
0040a6068f [AutoParallel] Add test for fuse_ffn and fuse_attention_qkv pass (#9203)
* add ut

* add ut

* sovle conflict

* sovle conflict

* fix
2024-10-10 13:16:39 +08:00
Hanyonggong
37c211adf0 [LLM] Add tools for parameters (#9137)
* add tools
2024-10-10 11:19:06 +08:00
Chang Lu
dbd3947542 fix ut (#9228) 2024-10-08 19:21:09 +08:00
LixinGuo
7be935cd9a [CI] Fix auto ci return bug when run in v100 (#9216) 2024-10-08 17:16:19 +08:00
Chang Lu
75f5031dac [AutoParallel] add vpp align and pp amp test (#9176)
* add vpp test

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* add new test

* add new test

* Update ci_case_auto.sh
2024-10-08 15:44:16 +08:00
Guoxia Wang
1fc942924d compatible with flashmask API rename upgrade (#9019) 2024-09-30 11:28:47 +08:00
Wennie396
c2fcc3e0bc [AutoParallel] Move some auto_parallel args into class AutoTrainingArguments (#9155) 2024-09-30 11:02:54 +08:00
Weiguo Zhu
db80bddc50 [Models] Add Llama-3.2 (#9199)
* add llama3.2
2024-09-27 17:36:24 +08:00
LixinGuo
1694d7c00b Fix ci not set no_proxy and modify tests in pir mode (#9205) 2024-09-27 15:34:54 +08:00
Yuanle Liu
0289118c9b [LLM_INFER] Support quantized model from bos and fix docs (#9197)
* llama A8W8 support skip_scale
* support top_k
* qwen2 support skip scales
* merge develop
* add comment
* support quantized model from bos
---------

Co-authored-by: minghaipeng <minghaipeng@baidu.com>
2024-09-27 12:35:39 +08:00
lugimzzz
b2e4db2dcd Add FlashMask reward model (#9154) 2024-09-27 11:26:25 +08:00
Siming Dai
31e47a5a89 [Unified Checkpoint] update async_save_info in develop (#9173) 2024-09-26 16:25:56 +08:00
Weiguo Zhu
f80a051337 Skip dynamic to static test cases (#9196) 2024-09-25 23:49:11 +08:00
zhangbo9674
1b8f37f632 [AutoParallel] Fix ckpt convert bug for sharding v2 (#9179) 2024-09-25 23:48:52 +08:00
zhangbo9674
1ce2642efb [AutoParallel] Add FLAGS_enable_fused_ffn_qkv_pass for llama (#9182) 2024-09-25 23:48:13 +08:00
Ti Zhou
c62390157d [XPU] add xpu support for llama sft (#9152)
Co-authored-by: tizhou86 <tizhou86@users.noreply.github.com>
2024-09-25 16:14:20 +08:00
Zhong Hui
c4d3a2f19d Revert "[Tokenier] Enable padding_side as call time kwargs (#9161)" (#9192)
This reverts commit c5e6db56a3.
2024-09-25 15:43:36 +08:00
lvdongyi
c5e6db56a3 [Tokenier] Enable padding_side as call time kwargs (#9161) 2024-09-24 12:05:22 +08:00
LixinGuo
cd4e81640e [CI] remove run_pretrain_auto_static.py CI when open PIR (#9177) 2024-09-23 17:25:57 +08:00
greycooker
ad14dc4f46 [Trainer] Support skip data intervals (#8989)
* support skip data intervals

* add debug_data arg

* fix loss compute

* remove callback while skip data

* remove debug data

* add callback_handler

* remove debug_data

* fix conflict
2024-09-23 14:59:26 +08:00
Zhong Hui
353d2785a2 [Tools] Rename tool_helpers to fast_dataindex. (#9134) 2024-09-23 14:39:11 +08:00
lugimzzz
bc55104def [LLM][TRL] Support DPO with Pipeline Parallel (#9039)
* support dpo/kto pp
2024-09-20 18:01:57 +08:00
JZ-LIANG
8212b53cba [AutoParallel] enable ci for dp amp clip (#9062)
* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh
2024-09-20 16:51:48 +08:00
chen
c4f7acf454 [Inference] FP8 dual gemm auto-tune and support compile parallelization (#9151)
* fp8

* check

* check

* check

* check

* cutlass fp8

* fp8 chech

* check

* ffn1 tune

* delete

* check

* change file path

* top_p_sampling_reject.cu
2024-09-20 01:23:01 -07:00
Zhong Hui
25a5b4fa1b Update README.md (#9160) 2024-09-20 16:12:47 +08:00
Weiguo Zhu
7deb33c194 [Models] Add Qwen2.5 (#9157) 2024-09-20 15:46:56 +08:00
gaoziyuan
907ad20496 【Inference】Optimize top_p kernel performance (#9132)
* add top_p kernel
* fix code style
2024-09-20 11:52:18 +08:00
Weiguo Zhu
c93bada815 [Tokenizer] Fix decode output with space in decode_token (#9010)
* fix

* fix
2024-09-19 16:31:39 +08:00
lvdongyi
90cef20408 [Tokenizer] Add replace_additional_special_tokens parameter to add_special_tokens (#9144) 2024-09-19 11:35:06 +08:00
LixinGuo
7faad55567 Fix llm ce predict run error (#9149)
* fix llm ce predict run error
2024-09-19 11:29:20 +08:00
Weiguo Zhu
a6cf8826af [Docs] Update LLM docs (#9143)
* sync llm to docs/llm
* update pre-commit config
* update pre-commit config
2024-09-18 19:51:16 +08:00
Ferrebo
0540e97c50 [Fix] freeze shard-reshard (#9067) (#9148) 2024-09-18 16:59:43 +08:00
a31413510
4503dd3000 add multy devices supported models (#9079) 2024-09-18 15:31:57 +08:00
Jingqi Chen
e340457ece [LLM Inference] Qwen2_Moe Support wint4 (#9129)
* support wint4

* fix codestyle
2024-09-14 18:35:51 +08:00
Weiguo Zhu
d90617105a [DOC] Update docs (#9141)
* update doc
2024-09-14 16:02:44 +08:00
lixc
0832b5934b [Inference] Update fakequant (#9140)
* add a8w8(fp8) a8w8c8(int8) quant_type support
* add llama3.1 and qwen2 ptq config
* reformat quantization.md and argument.py
* update prepare data method for ceval ptq
* fix wint4 config bug
* use independent avg/abs_max observer
* rename fp8 quant_type
* update quantization.md
* remove ceval in run_finetune.py
2024-09-14 14:35:45 +08:00
zhangyuqin1998
e9338c24b9 [Auto Parallel] Fix ckpt_converter for auto_parallel (#9136) 2024-09-14 10:19:15 +08:00
zhangbo9674
089a3c3b3f [Benchmark] Fix amp level bug in some gpt tests (#9116) 2024-09-13 16:40:25 +08:00
Zhong Hui
5c1779c8bd [Feature] Add hardware flops for pretraining (#9069)
* fix hardware tflops.

* Support mfu for pretraining.
2024-09-13 14:53:07 +08:00
Ryan
e2f4c33d5e [DOC] Update quick_start.rst (#9127) 2024-09-13 14:33:28 +08:00
Weiguo Zhu
11252bcc89 [Fix] Remove ring_flash_attention warning (#9119)
* fix
2024-09-13 14:25:32 +08:00
wanghuancoder
399490b7b7 fix pir dtype (#9130) 2024-09-13 12:06:10 +08:00
Ruibiao Chen
cd3dc95814 Add fast_ln spmd rules (#9125) 2024-09-13 12:05:24 +08:00
chen
db270d91b7 [Inference]qwen2-a8w8c8 support use_fake_parameter (#9109)
* use_fake_parameter

* fixed qwen2 and llama fake data. support qwen2 multi-card inference

* check
2024-09-12 19:24:19 +08:00
Siming Dai
93a9b2cd8d [Unified Checkpoint] Fix uc lora config, fix release_grads (#9082)
* [Unified checkpoint] update optimizer async save signal
---------

Co-authored-by: gongenlei <gongenlei@baidu.com>
2024-09-12 17:49:21 +08:00
Jingqi Chen
d3302c5515 [LLM Inference] Support Qwen2_Moe Inference with MultiGPU (#9121)
* Support Qwen2-57B-A14B
* Fix codestyle
2024-09-12 13:23:11 +08:00
zhangbo9674
51b54d236f [AutoParallel] Fix add ut (#9120) 2024-09-12 11:03:28 +08:00
chen
3675ea2d90 [Inference] FP8 gemm auto-tune (#9094)
* fp8 cutlass gemm tune

* git ignore third_party

* check csrc/readme.md
2024-09-11 21:21:04 +08:00
duanyanhui
73a3db98d6 [DCU] fix DCU w8a8c8 GEMM shape (#9115) 2024-09-11 21:18:13 +08:00
gaoziyuan
ba9c345ec1 【Inference】fix step kernel (#9122)
* fix step.cu when setting FLAGS_allocator_strategy=auto_growth
2024-09-11 18:51:14 +08:00
Hongwen Xin
af23e2db5c [Bugfix] fix multi-gpu infer (#9107) 2024-09-10 14:42:43 +08:00
lixc
98062936c2 remove ceval from run_finetune (#9100) 2024-09-10 10:54:49 +08:00
JZ-LIANG
33fc7ff1ee [AutoParallel] Enable CI for gradclip (#9059)
* Update ci_case_auto.sh

* Update ci_case_auto.sh
2024-09-10 10:39:54 +08:00
zhangbo9674
2f31866d9c [AutoParallel] Disable UT (#9108) 2024-09-09 19:56:02 +08:00
Tian
d245d0787f [LLM] fix trainer on npu (#9101) 2024-09-06 23:16:27 +08:00
Siming Dai
c90dc87949 [CI] Fix paddlepaddle install (#9102)
* [Unified checkpoint] update optimizer async save signal

* update paddlepaddle

---------

Co-authored-by: gongenlei <gongenlei@baidu.com>
2024-09-06 22:56:48 +08:00
AIbin
2150ae3539 fix use paddle.incubate.jit.inference(model) errors (#9016)
* fix use paddle.incubate.jit.inference(model) errors

* fix jit_inference function

* fix jit_inference function

* fix jit_inference function

* fix jit_inference function

* fix jit_inference function

* fix jit_inference function

* fix jit_inference function

* fix jit_inference function

* fix jit_inference function

* fix jit_inference function

* fix jit_inference function
2024-09-06 17:35:27 +08:00
LixinGuo
ce0c0e73c5 Fix baseline because of PR#8769 (#9092) 2024-09-06 14:31:01 +08:00
yujun
7783744531 [data] update tool_helpers version and add unittest (#9093) 2024-09-06 12:18:19 +08:00
SevenSamon
f4cff9665e [LLM] Add tensor parallel for chatglmv2 (#9014)
* fix_chatglmv2_8k
2024-09-05 20:57:10 +08:00
EnflameGCU
1ef3ec2de8 [GCU] update readme (#9046) 2024-09-05 15:12:07 +08:00
Sonder
235f09f363 [PIR] add pir grad merge test (#9074)
* add test

* change task name

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh
2024-09-05 14:34:23 +08:00
LixinGuo
0854287269 Fix llm predict install error (#9088)
* fix llm predict install error
2024-09-05 14:10:46 +08:00
zhengzhonghui
951e3d45d5 Fix hang when Flag_dataloader_use_file_descriptor=True (#9080) 2024-09-05 11:19:27 +08:00
zhangyuqin1998
8ee99a46b7 [Auto Parallel] fix data stream bug of dist.to_static (#9077) 2024-09-05 09:40:49 +08:00
lixc
70da48252f [Inference] Fix weight_only_int4 bug (#9073) 2024-09-04 16:53:38 +08:00
Hanyonggong
fbbc0a2676 Fix the memory overflow bug of the tune_cublaslt_gemm operator (#9076)
* fix bug

* add cudacheck
2024-09-04 14:25:25 +08:00
Weiguo Zhu
9939f8451c [MLU] Fix Llama attrntion_mask in npu and mlu (#9075)
* fix
2024-09-03 20:47:23 +08:00
ronnywang
4e7fb49f27 [NPU] Fix baichuan2-13b-chat infer (#9070) 2024-09-03 11:19:15 +08:00
Weiguo Zhu
a4fbc5221f [Version] update version info (#9060)
* update version

* update

* update

* update
2024-09-03 09:32:49 +08:00
chen
84469d61e8 [Inference] Qwen2 support fp8 inference (#8954)
* qwen2 fp8

* fp8 check

* fp8 cutlass

* int8 cachekv

* a8w8c8_fp8
2024-09-02 21:02:43 +08:00
chen
a275ab7a47 [Inference] support llama3 a8w8c8_fp8 inference and cutlass_fp8_gemm (#8953)
* fp8

* check

* check

* check

* check

* cutlass fp8

* fp8 chech

* check

* support int8 kv cache

* a8w8c8_fp8

* Copyright check

---------

Co-authored-by: ckl117 <ck117@163.com>
2024-09-02 18:50:53 +08:00
PeiyuLau
a12781f928 Support rms_norm_mlu (#8504) 2024-09-02 16:57:14 +08:00
Sonder
e204b6db31 [AutoParallel][PIR] Fit pir grad merge (#8985)
* fit pir llm grad merge

* fit code style

* add grad merge llama test

* Update run_pretrain_auto.py

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* Update ci_case_auto.sh

* remove test

* Update ci_case_auto.sh

* Update ci_case_auto.sh
2024-09-02 12:39:08 +08:00
lixc
cda9594dce [Inference] Update fakequant script (#9054)
* 1. add a8w8(fp8) a8w8c8(int8) quant_type support
2. add llama3.1 and qwen2 ptq config
3. update quantization.md

* fix load_quant_model bug

* fix load quant bug

* update ll/README.md

* remove useless code

* update quant observer config

* resolve wrong modify

* fix prepare_qconfig

* remove unuse files

* update quantization.md

* reformat quantization.md and argument.py

* update prepare data method for ceval ptq
2024-09-02 10:50:44 +08:00
xuzhang
116841a089 fix bos download (#9023)
* fix bos download

* add test

* update
2024-09-02 10:43:20 +08:00
greycooker
90863b14b2 [Trainer] Add dp degree init (#9056) 2024-08-30 17:00:16 +08:00
Zhong Hui
3ec9a1ad32 Update quantization.md (#9057) 2024-08-30 16:41:29 +08:00
Meiyim
3ee8ab79d8 [Trainer] Fix moe save load (#9045)
* fix `upload signal` under pure dp and dp-moe (#8874)
---------

Co-authored-by: Ferrebo <kebo01@baidu.com>
2024-08-30 11:29:22 +08:00
liym27
312d41c419 [AutoParallel] Add test (#9015) 2024-08-30 11:11:54 +08:00
lixc
e0ba7ef923 [Inference] update fakequant support (#9047)
* 1. add a8w8(fp8) a8w8c8(int8) quant_type support
2. add llama3.1 and qwen2 ptq config
3. update quantization.md

* fix load_quant_model bug

* fix load quant bug

* update ll/README.md

* remove useless code

* update quant observer config

* resolve wrong modify

* fix prepare_qconfig

* remove unuse files
2024-08-29 22:19:19 +08:00
gaoziyuan
c28caf70b0 [Inference] Add cutlass gemm dequant op (#8909)
* change gpu name

* add cutlass gemm_dequant op

* add cutlass gemm_dequant op

* fix format

* fix fused_transformer_layers

* fix layer

* fix layer

* fix format

* fix format

* fix review

* fix review

* fix review

* fix review

* fix review

* fix review

* fix review
2024-08-29 20:58:38 +08:00
Yuanle Liu
a18e220c32 Fix setup.py for llm inference (#9041) 2024-08-29 11:42:00 +08:00
Hongwen Xin
47a95422d8 [Bugfix] fix bias optional (#9037) 2024-08-29 11:33:10 +08:00
lugimzzz
7be1e1663f [llm]support pad to max_length & fix sp bug (#9040)
* add sp hook

* support zero padding pad to max_length

* support finetune pad to max_length
2024-08-29 11:20:25 +08:00
Siming Dai
59568226eb [Unified Checkpoint] Update async save info (#8982)
* [Unified checkpoint] update optimizer async save signal

* [Unified Checkpoint] Update async save info
2024-08-29 11:11:03 +08:00
ShenLiang
ae691e21a0 [Cherry-pick] add comm buffer size (#8963) (#9031)
* add comm buffer size (#8963)

* add doc
2024-08-29 10:24:40 +08:00
ShenLiang
5eb8d034ae Fix checker of nan/inf (#9029)
* fix checker position for nan/inf

* fix checker position for nan/inf
2024-08-29 10:24:13 +08:00
lixc
19927ba5c2 [Inference] Add a8w8(fp8) a8w8c8(int8) quant_type support (#9032)
* 1. add a8w8(fp8) a8w8c8(int8) quant_type support
2. add llama3.1 and qwen2 ptq config
3. update quantization.md

* fix load_quant_model bug

* fix load quant bug

* update ll/README.md
2024-08-28 22:21:56 +08:00
Weiguo Zhu
3e7c5caa4a [Tokenizer] Support for loading added_tokens_decoder (#8997)
* fix added_tokens_decoder load

* fix decode

* fix saving and loading added_token_decoder

* fix mamba

* fix special_tokens_map_file load

* fix gemma tokenizer

* fix llama tokenzier

* revert llama tokenizer

* fix _decode
2024-08-28 20:38:07 +08:00
sneaxiy
c656452634 [Cherry-pick] Add is_distributed field in sharding reshard param_meta (#9028) 2024-08-28 20:05:15 +08:00
wawltor
ae02a3c1a2 fix the recompute for recall model. 2024-08-28 19:29:31 +08:00
wawltor
9b442c8bef Merge branch 'develop' of https://github.com/PaddlePaddle/PaddleNLP into develop 2024-08-28 19:24:50 +08:00
bukejiyu
25a6d4e96b update cpu inference (#8984) 2024-08-28 19:16:09 +08:00
Yuanle Liu
2f567e6bf4 fix llama3 static run (#8849) 2024-08-28 16:09:43 +08:00
Jingqi Chen
34a71c8242 supprot qwen-moe (#8892)
Co-authored-by: yuanlehome <yuanlehome@163.com>
2024-08-28 11:50:00 +08:00
Sunny-bot1
a2f9558a81 llm inference docs (#8976)
* update inference docs

* update

* update

* update

* update

* fix comments

* fix comments

* fix comments

* update inference.md
2024-08-27 22:16:39 +08:00
Hongwen Xin
f6fc7ff64f [Feature] fused mixtral wint4 (#9013)
* [Feature] fused mixtral wint4

* [Refactor] refine code
2024-08-27 17:40:02 +08:00
zhangbo9674
a0609e8c3f Refine checkpoint converter (#9001)
* refine
2024-08-27 16:10:09 +08:00
Yuanle Liu
48820cbc1f Fix step.cu bug (#8995) 2024-08-27 10:58:54 +08:00
Weiguo Zhu
56d293dd77 Fix zero_padding (#9003) 2024-08-26 21:04:22 +08:00
zhengzhonghui
24fa97ee43 Fix qwen model use_casual_mask (#9009) 2024-08-26 19:22:47 +08:00
EnflameGCU
154928a0f5 [GCU] Add gcu llama2-13b readme (#8950) 2024-08-26 17:31:09 +08:00
xiguapipi
3ef7c1ba72 [XPU] Add README.md for llama2-7b (#8979)
* [xpu]add README.md for llama2-7b

* [xpu]add README.md for llama2-7b

* [xpu]rm readme.md

* [xpu]modify README.md for llama2-7b

* [xpu]modify README.md for llama2-7b

* [xpu]modify README.md for llama2-7b
2024-08-26 14:23:36 +08:00
Hongwen Xin
31cc283f07 [Feature] Fused Mixtral support (#8901)
* [Feature] Fused Mixtral support

* [Refactor] add MoeConfig and fix static graph export problem

* [Bugfix] fix small bug

* [Bugfix] fix moe_config bug

* [Bugfix] fix moe_config bug

* [Refactor] refine code

* [Refactor] refine code

* [Refactor] refine code

* [Refactor] match fused moe api change

* [Feature] wint8 support
2024-08-26 11:47:30 +08:00
lugimzzz
9f6b486501 【llm】update docs (#8999)
* update readme

* update readme

---------

Co-authored-by: DesmonDay <908660116@qq.com>
2024-08-26 10:22:08 +08:00
ShenLiang
8e1f6e6a76 [Distributed]Add loss nan/inf checker (#8943)
* add checker

* fix fp16
2024-08-23 16:14:09 +08:00
duanyanhui
1ea1f5079f [DCU] Add DCU inference docs (#8983) 2024-08-23 16:13:43 +08:00
yujun
de1dc17de0 Upgrade tool_helpers to support 32766个dataset. (#8994) 2024-08-23 14:26:58 +08:00
lugimzzz
3c4d157500 update finetune.md (#8990)
Co-authored-by: DesmonDay <908660116@qq.com>
2024-08-23 14:02:48 +08:00
xingmingyyj
aaacb3272f [auto_parallel] Add checkpoint convertor (#8847)
* Add the checkpoint conversion module
2024-08-22 18:11:26 +08:00
LixinGuo
38dd5700a6 Fix pip error in legacy benchmarks (#8978)
* fix pip error
2024-08-22 16:52:29 +08:00
zhangyuqin1998
56dba6d225 [Bug fix] fix skip consumed_samples twice bug (#8980) 2024-08-22 15:13:33 +08:00
winter-wang
cf3a672617 fix the loss base in llama_align_dygraph_dy2st_auto_bs2_bf16_DP2-MP1-PP1 for A100 (#8986) 2024-08-22 14:49:10 +08:00
Mangodadada
dd909d1330 更正run_dpo.py文件路径 (#8952) 2024-08-21 19:03:45 +08:00
Siming Dai
1191a51e91 [Unified checkpoint] update optimizer async save signal (#8975) 2024-08-21 17:12:16 +08:00
winter-wang
5f6998f32d add amp unit test case for auto_parallel ci. (#8966) 2024-08-21 15:14:41 +08:00
Weiguo Zhu
30a2ac6d90 [ZeroPadding] padding to max_length for sequence parallel (#8973)
* fix zero_padding for sequence parallel
2024-08-21 15:09:43 +08:00
zhengzhonghui
d505a97727 Fix qwen benchmark (#8969) 2024-08-21 11:35:43 +08:00
zhangbo9674
fbe1fae140 [Auto Parallel] Support save model file (#8927) 2024-08-21 11:16:09 +08:00
Siming Dai
0136312b74 [Unified Checkpoint] update async save (#8801)
* update async save

* move load_unified_optimizer

* update async save

* tmp

* add config

* update final async save

* add load_non_merge_optimizer

* update unlink func

* update final signal

* update windows for async_save

* fix rng load

* fix unittest

* fix distdataloader, update async_save

* update unlink

* remove dist dataloader

* fix load optimizer oom
2024-08-20 16:41:49 +08:00
Weiguo Zhu
27f8462f42 [CI] Fix (#8793)
* fix ci
2024-08-20 16:22:14 +08:00
Zhong Hui
326cf82153 Enable tensor parallel tests. (#8757) 2024-08-20 16:20:32 +08:00
yujun
bafd7e5c90 fix JambaModelIntegrationTest (#8965) 2024-08-20 14:47:35 +08:00
chen
ecfe0aca35 [LLM Inference] support qwen2 a8w8c8 inference (#8925)
* qwen2-1.5b a8w8c8
2024-08-20 11:43:11 +08:00
Yuanle Liu
71b3be3a51 [LLM Inference] add --use_fake_parameter option for ptq fake scales and fix compute error of total_max_length (#8955)
* update some code

* update

* update

* update

* update tune_cublaslt_gemm demo

* fix step in tune_cublaslt_gemm
2024-08-19 21:04:56 +08:00
yujun
0ec78aa916 [NEW Model] Add jamba (#8517)
* Add jamba
2024-08-19 20:12:21 +08:00
yujun
12107af7a2 [BUG] fix mamba tokenizer (#8958)
* fix

* fix

* fix

* fix
2024-08-19 16:42:49 +08:00
yujun
b08e44509d [NEW Model] Add mamba (#8513)
* add mamba

* update

* do not shift

* update

* push

* mamba 单测pass

* mamba

* update_model_kwargs_for_generation

* fix tests

* test

* test

* add tokenizer test
2024-08-19 13:22:45 +08:00
Siming Dai
8599a53410 Add greedy_zero_padding (#8933) 2024-08-19 11:47:12 +08:00
Weiguo Zhu
d2d4d92fb6 [Tokenizer] Add Fast Tokenizer (#8832)
* add fast tokenizer

* add convert slow tokenizer method
2024-08-19 11:09:42 +08:00
Siming Dai
e8708edf82 [Trainer] Fix distributed dataloader (#8932)
* fix ddloader, fix uc unittest

* update dataloader
2024-08-16 16:28:28 +08:00
winter-wang
277fdb4a5c support amp in pir dy2st mode. (#8485) 2024-08-16 15:39:11 +08:00
Zeyu Chen
e0d2809432 Update README.md 2024-08-16 13:18:19 +08:00
Yuanle Liu
6e12ef3400 [LLM Inference] move llm.utils.utils.py to paddlenlp.utils.llm_utils.py (#8946)
* adjust some code

* update

* update
2024-08-16 12:13:57 +08:00
Yuanle Liu
6d538c7b33 Fix predictor bug (#8947)
* fix bug

* update
2024-08-16 02:43:23 +08:00
Siming Dai
310a7bcb13 [Unified Checkpoint] Fix load best checkpoint (#8935)
* fix load best

* update
2024-08-15 20:43:36 +08:00
Yuanle Liu
c88a971ddf [BugFix] fix predict get_tensor_parallel_mappings (#8939) 2024-08-15 11:30:43 +08:00
zhangyuqin1998
9b76eb2452 [BugFix] fix create_optimizer_and_scheduler for auto_parallel (#8937) 2024-08-15 11:11:42 +08:00
Weiguo Zhu
8f6b001e39 update tokens compute (#8938) 2024-08-14 22:19:02 +08:00
Yuanle Liu
3fff3787ed [LLM Inference] support llama3.1 (#8929)
* support llama3.1

* update
2024-08-14 17:49:58 +08:00
Yuanle Liu
82ea8bc590 fix test_wint8 ut (#8930) 2024-08-14 16:57:46 +08:00
gongel
01bb1f80a2 [Cherry-pick] Fix pipeline eval (#8924) 2024-08-14 15:52:43 +08:00
zhengzhonghui
75c76365fd [TIPC] Set logging_step to 5 with baichuan && qwen benchmark (#8928)
* set logging_step to 5 with baichuan && qwen benchmark
2024-08-14 15:27:44 +08:00
greycooker
85fbe52fcc support json parameter (#8446) 2024-08-14 13:45:21 +08:00
Weiguo Zhu
0cc8554735 [doc] Update README (#8922)
* add yuan2 model list

* update
2024-08-14 10:36:03 +08:00
zhengzhonghui
f069a5350f Update qwen && baichuan benchmark config (#8920) 2024-08-13 12:58:36 +08:00
zhaogf01
30fc639eba [LLM]Update yuan model (#8786)
* add yuan model

* add yuan model settings

* fix conflict

* add readme

* update format

* update readme

* update readme

* update for lint

* update for lint

* update for lint

* update for lint

* add fp16

* update utils

* fix bug

* format

* correct pre-commit

* correct fp16

* delete rearrange

* add pre_train

* auto convert from torch

* support sft lora

* update structure

* fix yuantokenizer pad

* update scripts

* update readme

* update readme

* add pad_token_id

* format

* format

* update readme

* update for review

* update for review

* fix bug

* update to CRLF

* format

* support param convert

* update sft config

* fix modeling

* fix qk fuse&spilt and fix fa

* format

* format

* format

* fix fa dtype

---------

Co-authored-by: drownfish19 <drownfish19@gmail.com>
2024-08-12 16:25:07 +08:00
xiaoguoguo626807
57a42f8aa9 modify dict include none to aviod pir dytostatic bug in while op (#8898)
* modify dict include none

* recover
2024-08-12 14:27:46 +08:00
Yuanle Liu
0a5de127b7 [LLM Inference] Support qwen2 (#8893)
* stage 1

* update

* update

* support qwen2 bf16/wint8

* add qwen2 ptq map

* update

* fix tune_cublaslt_gemm.cu
2024-08-12 14:01:59 +08:00
greycooker
6f3e736ddb 【Fix】modify tensorboard requirements (#8904)
* modify tensorboard requirements

* modify tensorboard requirements

* modify tensorboard requirement
2024-08-12 11:48:59 +08:00
Yuanle Liu
5bc040a157 [LLM Inference] Refactor BlockInferencePredictor (#8879)
* stage 1

* update

* update

* fix ci

* fix ci

* fix ut
2024-08-12 10:08:41 +08:00
ShenLiang
718729921f fix format (#8878) 2024-08-09 16:55:15 +08:00
Zhong Hui
4ebec1d46d [Readme] Update README.md (#8908)
* Update README.md

* Update README_en.md
2024-08-09 13:19:02 +08:00
JZ-LIANG
c5e81094d3 bugfix auto parallel FA (#8903)
Co-authored-by: winter-wang <1030748926@qq.com>
2024-08-09 10:38:28 +08:00
Weiguo Zhu
4860d631e6 [doc] Update readme (#8905)
* update

* update

* remove
2024-08-08 22:13:00 +08:00
Zhong Hui
996198a199 Update run_pretrain.py (#8902) 2024-08-08 18:07:50 +08:00
zhengzhonghui
6f5bb76e96 [Fix] enable_sp_async_reduce_scatter for qwen_72b && llama2_70b (#8897) 2024-08-08 16:55:15 +08:00
Wennie396
fd692a8003 Fix fast_ln InferDtypeFn (#8891) 2024-08-08 16:41:22 +08:00
lugimzzz
2491f5d087 fix zeropadding (#8895) 2024-08-08 16:01:49 +08:00
xiaoguoguo626807
5c5701559e modify Paddlemix qwen dytostatic (#8869)
* modify api for pir

* modify api for pir

* pass none for while

* modify ci test
2024-08-07 17:31:53 +08:00
S M
678843e5bd Fix the issue of P-tuning official sample error (#8884)
* Fix the issue of P-tuning official sample error

* Create codecov workflow.yml

* Delete .github/workflows/workflow.yml
2024-08-07 17:30:07 +08:00
Ben
6235fcd09a Fix the bug with issues code 8641. (#8880) 2024-08-07 11:33:41 +08:00
zhengzhonghui
4cf0806677 Support nested list of dict inputs (#8876) 2024-08-06 17:24:03 +08:00
sneaxiy
dbf395f8bf Cherry pick some changes from incubate branch (#8862)
* Fix sharding reshard bug and support reshard in different partition ways (#8837)

* Fix sharding reshard bug and support reshard in different partition ways

* fix some bugs

* refine codes

* revert some useless codes

* add log

* Fix TP sync (#8846)

* fix sharding reshard compatiblity for wrong master weight name (#8851)

* change print to logger.info

* remove useless f-string
2024-08-06 11:05:07 +08:00
greycooker
c4d1abfbe5 support sft mapdataset (#8840)
* support sft mapdataset

* fix __len__ and __getitem__

* fix judge impl method

* fix mmap

* change variable name
2024-08-05 17:38:53 +08:00
Yuanle Liu
a6a7870761 [Inference LLM] support static c8 (#8833)
* support llama2 static c8

* fix

* fix

* fix

* fix ci

* fix ci

* fix ci

* fix ci
2024-08-05 11:30:04 +08:00
wawltor
680b85e543 Merge branch 'develop' of https://github.com/PaddlePaddle/PaddleNLP into develop 2024-08-01 20:43:42 +08:00
Siming Dai
77480a071d [UC] Fix tie_word_embeddings (#8795) 2024-08-01 19:41:04 +08:00
Siming Dai
12ba7ee237 Add release_grads (#8829) 2024-08-01 19:12:15 +08:00
Siming Dai
d4975e0b45 update_uc_merge (#8856) 2024-08-01 16:16:41 +08:00
zhangbo9674
7c43bc8a6e [AutoParallel] Refine save and load ckpt for auto_trainer (#8828) 2024-08-01 11:47:42 +08:00
Yuanle Liu
d406e56d1a Fix tune_cublaslt_gemm compile bug (#8844)
* fix tune_cublaslt_gemm

* Fix:

* fix
2024-07-31 15:36:05 +08:00
Hanyonggong
99d9bcb481 Add tune_cublaslt_gemm operator by cublaslt gemm algorithm and generate algo cache file (#8799)
* Add tune_gemm feature
2024-07-31 13:22:29 +08:00
yujun
fe7e2fe24e [BUG] Fix build train valid test datasets (#8826)
* train_val_test_num_samples
2024-07-31 11:26:08 +08:00
Weiguo Zhu
e85a68dfa3 [Models] Add llama3.1 (#8824) 2024-07-31 11:05:22 +08:00
GoldPancake
5da5c36522 [DCU] fix llama inference bug on DCU (#8815) 2024-07-29 15:57:10 +08:00
Yuanle Liu
6ea9dc0930 fix pad_token_id bug (#8814) 2024-07-29 13:02:28 +08:00
Zhuoqun Li
ee4944e75c add paddle nv-embed-v1 (#8785)
* add paddle nv-embed-v1

* rename hf_model and use config in models
2024-07-28 15:53:31 +08:00
Guoxia Wang
39632e97ec support Llama3.1 8B 128K generation on single GPU 80GB (#8811)
* support Llama3.1 8B 128K generation on single GPU 80GB

* support llama3 rope

* try to fix _clear

* fix

* fix

* add config
2024-07-28 11:56:39 +08:00
Weiguo Zhu
77c0b0ef9f [Doc] Update README (#8817)
* update readme

* update

* update

* update
2024-07-26 18:53:13 +08:00
Siming Dai
054c3addd9 [MoE] Optimizer parameter broadcast (#8810) 2024-07-26 18:00:06 +08:00
wawltor
53a510a460 Merge branch 'develop' of https://github.com/PaddlePaddle/PaddleNLP into develop 2024-07-26 16:43:11 +08:00
zhangbo9674
e6d74f7f64 [AutoParallel] Refine auto_trainer save load (#8767) 2024-07-26 14:07:22 +08:00
Siming Dai
5fd6dd23c1 add enable_sp_async_reduce_scatter (#8803) 2024-07-25 21:33:14 +08:00
Siming Dai
77f6e98114 [Prediction] Update LLM prediction. (#8778)
* update llama predict

* update qwen predict

* update chatglm predict

* update opt, gpt predict

* update return_numpy=True

* fix tp split

* bug fix
2024-07-25 20:47:41 +08:00
GoldPancake
105e0da074 [DCU] Llama a8w8 inference performance optimization (#8800)
* [DCU] Llama a8w8 inference performance optimization

* keep two cases

* change back
2024-07-24 21:30:23 +08:00
wawltor
320dfc7ee4 Update quantization.md 2024-07-24 19:15:38 +08:00
Yuanle Liu
6f56bd47d5 [Inference LLM] refine some code in llama wint8/4 (#8796)
* delete validate model and fix wint8/4 in llama

* update
2024-07-24 15:36:03 +08:00
Weiguo Zhu
da1eb9c875 fix (#8792) 2024-07-24 09:52:40 +08:00
TranscenderNing
de7d103dc3 vera-pissa method added (#8722)
* vera-pissa method added

* add vera-pissa

* Add vera-pissa and test

* Add vera-pissa and tests and correct the lint format

* Revise according to the review comments and add tests

* Revise according to the review comments and pass tests

* Revise according to the review comments and pass tests 1

* Revise according to the review comments and pass tests 2

* Revise according to the review comments and pass tests 3

* Revise according to the review comments and pass tests 31

* Revise according to the review comments and pass tests 32
2024-07-23 19:48:25 +08:00
yujun
7c18d9d71b [BUG] 额外添加20个样本,防止制作预训练数据的时候超过index (#8789) 2024-07-23 10:50:34 +08:00
Weiguo Zhu
c4efddf48f update version (#8791) 2024-07-22 20:56:27 +08:00
houj04
88d4b19bc6 [XPU] use allgather and fp32 multinomial for XPU (#8787) 2024-07-22 11:21:25 +08:00
Weiguo Zhu
e8e59d069c fix (#8779) 2024-07-22 11:03:21 +08:00
Zhong Hui
57000fa12c Refine savable (#8758)
* mark tensor_parallel_degree savable.

* fix
2024-07-19 14:23:13 +08:00
lszxb
dedf4c5662 fix incorrect token counting in llm/predictor.py (#8769) 2024-07-18 10:51:35 +08:00
Difer
62a18c4ad8 [Trainer] Enable parallel_config to use commas as delimiters. (#8677) 2024-07-17 20:09:25 +08:00
wawltor
e89399a21e fix the ce for the unittest (#8772) 2024-07-17 15:32:14 +08:00
wawltor
89095c34d2 Merge branch 'develop' of https://github.com/PaddlePaddle/PaddleNLP into develop 2024-07-17 13:05:41 +08:00
lszxb
ab72ba7940 fix the missing truncation=True in llm/predictor.py (#8768) 2024-07-17 11:14:39 +08:00
LixinGuo
227ec81e63 add benchmark baichuan2 scripts (#8683)
* remove tsinghua pypi

* modify gpt dateset addr for benchmark

* fix run_benchmark for llama2_70b in auto_parallel

* fix autotunner benchmark error and fix llama2 dy2st benchmark

* fix benchmark dir because of PR#8627

* Update run_benchmark.sh

Update run_benchmark.sh

* fix benchmark dir because of PR#8627

* add qwen N4C32

* fix etcd

* fix qwen N4C32 for per_device_type

* fix benchmark dir and add CUDA_DEVICE_MAX_CONNECTIONS to qwen

* add benchmark baichuan2 scripts

* fix run time

* update baichun2_13b config
2024-07-17 10:55:09 +08:00
lizexu123
5e53db1361 【inference】support load or save Llama2-7b in three patterns (#8766)
* config:

* fix
2024-07-16 20:43:00 +08:00
Weiguo Zhu
5a508e5c4c Fix version show (#8754) 2024-07-15 14:38:41 +08:00
Weiguo Zhu
be957f06fa [NPU] Fix sequence parallel lib import (#8760) 2024-07-15 11:13:48 +08:00
JZ-LIANG
7a1c4394d8 [AutoParallel] update loss for global clip (#8750)
* update loss for global clip

* skip ci
2024-07-12 16:14:29 +08:00
Weiguo Zhu
10d058d2b1 [PaddleNLP 3.0] Update README (#8681)
* update

* update readme

* update

* update

* update

* update

* update

* update

* update

* update README(EN)

* correct broken links in readme

Signed-off-by: Zhang Jun <jzhang533@gmail.com>

* add markdownlint

* update

* add check_spaces

* update

* update readme

* update readme

* update

* update

update readme

* update readmes

* update

* update

* update llm doc index

* update

* add rlhf docs

---------

Signed-off-by: Zhang Jun <jzhang533@gmail.com>
Co-authored-by: Zhang Jun <jzhang533@gmail.com>
2024-07-12 11:06:56 +08:00
Leo Chen
028206b6cb update a100 loss (#8708)
* update a100 loss

* disable test

* enable check
2024-07-11 19:38:31 +08:00
zhangyuqin1998
2f0f8b1628 [Bug fixes] Fix ring attention (#8740)
* fix ring attention

* fix

* fix
2024-07-11 16:52:19 +08:00
Weiguo Zhu
e336e78c33 [LLM] Update sequence parallel linear import (#8706)
* Update sequence parallel linear import

* update lora models

* update lora sequence parallel layer
2024-07-11 12:04:05 +08:00
LixinGuo
c4f99ee07a fix nlp dir and auto_parallel_ci exit -6 (#8744) 2024-07-11 11:19:20 +08:00
zhaogf01
1af227adda [LLM] Add Yuan model (#8654)
* add yuan model

* add yuan model settings

* fix conflict

* add readme

* update format

* update readme

* update readme

* update for lint

* update for lint

* update for lint

* update for lint

* add fp16

* update utils

* fix bug

* format

* correct pre-commit

* correct fp16

* delete rearrange

* add pre_train
2024-07-11 10:42:16 +08:00
ronnywang
a1dbc39aae revert benchmark fix (#8747) 2024-07-10 20:06:38 +08:00
wawltor
04c9b39f22 fix the tipc ce case 2024-07-10 19:48:31 +08:00
jzhang533
324112048d correct broken links in readme (#8741)
Signed-off-by: Zhang Jun <jzhang533@gmail.com>
2024-07-10 16:28:30 +08:00
Weiguo Zhu
1a2502c4b8 [Safetensors] Fix mmap for Windows system (#8734)
* fix mmap for Windows system
2024-07-10 14:33:53 +08:00
lugimzzz
fbe613bbc5 disable lora (#8674)
* disable lora

* lora disable & merge

* fix

* fix unitest

* fix the finetune and predict in llm

---------

Co-authored-by: wawltor <fangzeyang0904@hotmail.com>
2024-07-09 10:53:10 +08:00
Yuang Liu
595c2fbf8f bug fix (#8730) 2024-07-09 10:04:30 +08:00
tianhaodongbd
e6810195d0 Finetune support use_fast_layer_norm (#8717) 2024-07-08 16:52:25 +08:00
zhengzhonghui
bdd2287bf3 fix fast_ln backward (#8719) 2024-07-05 16:30:52 +08:00
lizexu123
d8ddba9244 【inference】support load or save Llama2-7b in three patterns (#8712)
* fix

* fix

* 删除注释

* 恢复+删除

* 删除+恢复
2024-07-05 10:32:03 +08:00
Yuang Liu
e471b1e8af fix xpu gather for unified ckpt (#8710) 2024-07-05 10:18:02 +08:00
zhengzhonghui
70564ba8cd [Benchmark] Enable use_fast_layer_norm for llama2 benchmark (#8714) 2024-07-04 20:35:08 +08:00
zhengzhonghui
fd01043844 [Performance] Add fast_rmsnorm (#8680)
* add fast_rmsnorm
---------

Co-authored-by: Liu Yiqun <liuyiqun01@baidu.com>
2024-07-04 17:00:15 +08:00
Yuang Liu
6d464bfa79 xpu use allgather (#8697)
* xpu use allgather

* xpu use allgather
2024-07-03 17:19:25 +08:00
yujun
85cbadad35 num_samples 向下去整,防止prefrech预取时候超过数据集最大长度... (#8690) 2024-07-03 15:54:31 +08:00
wawltor
cf57f86755 fix the fast tokenizer in the taskflow 2024-07-03 11:24:32 +08:00
Siming Dai
c574d6de5a [Safetensors] Fix safetensors shape (#8702)
* Update sequence_parallel for predict

* Do not save moe_group

* Fix safetensors reading
2024-07-03 11:03:03 +08:00
Ting
af19dc4c4f Add new mistral (#7425)
* mistral model init commit

* code save

* add dump code

* mistral support lora,prefix,multi-gpu

* bug fix

* add flash attention

* mistral sliding windows attention (attention_mask version)

* llm json fix

* bug fix

* ci code save

* mistral ci, attention mask

* remove redundant comment

* remove print

* empty commit

* update

* add init py

* bugfix

* remove swa strategy

* update

* lora support

* update

* add tp cross entropy

* support zero padding

* update README.md
2024-07-03 10:55:11 +08:00
Leo Chen
64efd1ff0c update loss base of auto-parallel tests (#8701)
* clean legacy case

* clean gpt tests in model_zoo

* disable check

* fix loss base

* enable check
2024-07-03 10:49:40 +08:00
gmm
eaa80c985c [benchmark] Change the mirror source for pip (#8699) 2024-07-02 20:36:26 +08:00
lzydev
4a56c68855 change max_steps (#8679) 2024-07-02 19:57:41 +08:00
xiaoguoguo626807
d832282f84 【pir save 】Modiy export llama model file in pir mode (#8689)
* modify model to support llama export json

* modify model to support llama export json

* modify id

* modify full_like None

* modfiy utils

* reply comment
2024-07-02 19:51:11 +08:00
sunrui
79de55278a [Pre-Train] 支持qwen2预训练处理 (#8698) 2024-07-02 17:02:16 +08:00
Jianbang Yang
a53477cddf [XPU] add lora optimization (#8527)
* [XPU] add lora optimization

* fix

* refine
2024-07-02 11:16:47 +08:00
Ting
2723138738 bug fix (#8687) 2024-07-01 15:01:58 +08:00
LixinGuo
be5bb14a8b fix benchmark dir and add CUDA_DEVICE_MAX_CONNECTIONS to qwen (#8678)
* remove tsinghua pypi

* modify gpt dateset addr for benchmark

* fix run_benchmark for llama2_70b in auto_parallel

* fix autotunner benchmark error and fix llama2 dy2st benchmark

* fix benchmark dir because of PR#8627

* Update run_benchmark.sh

Update run_benchmark.sh

* fix benchmark dir because of PR#8627

* add qwen N4C32

* fix etcd

* fix qwen N4C32 for per_device_type

* fix benchmark dir and add CUDA_DEVICE_MAX_CONNECTIONS to qwen
2024-06-28 15:14:09 +08:00
yuguo
5364d5e612 [DCU] high performance LLM train and inference for DCU (#8580)
* [DCU] high performance LLM train and inference for DCU
2024-06-28 15:04:31 +08:00
gongel
a2b8a7835c update version (#8676) 2024-06-28 10:44:16 +08:00
Ting
c86e44774e Sft flash mask (#8664)
* support sft flash mask

* dpo support

* update

* remove dense mask when using flash mask

* bugfix

* support pp

* bugfix

* bugfix

* bugfix

---------

Co-authored-by: gongel <ainlp88@qq.com>
2024-06-28 10:43:42 +08:00
gongel
3ebe938339 Update version (#8675)
* update version

* update pre-commit
2024-06-27 20:56:41 +08:00
Siming Dai
cd5ca827f7 Update export model (#8671)
* Update sequence_parallel for predict

* Do not save moe_group

* update export model
2024-06-27 20:54:10 +08:00
lugimzzz
513e21d1d2 adjust llm readme (#8672)
* fix readme

* update readme

* fix readme

* fix readme
2024-06-27 20:53:30 +08:00
DrownFish19
04c2f2b0ec [PaddleNLP 3.0] Update README.md (#8666)
* update README.md

* update readme

* update readme

* fix

* fix dead link

* update figures

* update

* fix

* update

* update

* update quick start

* update figures
2024-06-27 20:53:16 +08:00
lugimzzz
1182cd553e support flashmask (#8670)
* support flashmask

* support flashmask
2024-06-27 20:52:56 +08:00
lzydev
dae64cc8f5 【AutoParallel】Change benchmark config for llama2-7b (#8667)
* change benchmark config for llama2-7b

* change logging_steps
2024-06-27 20:12:58 +08:00
bukejiyu
69e04c0c04 support llama avx model inference (#8634) 2024-06-27 19:42:47 +08:00
gmm
c6c2cd8a10 [benchmark] fix benchmark script (#8648)
* add llama-7b_auto_dp2mp2pp2 benchmark sh

* add llama-7b_auto_dp2mp2pp2 benchmark script for cinn

* update llama-7b_auto_dp2mp2pp2 benchmark script

* Update run_benchmark.sh

* Update run_benchmark.sh

* fix llama-7b_auto_dp2mp2pp2/benchmark_common

* Update run_benchmark.sh

* Update prepare.sh

* Update prepare.sh

* Update prepare.sh

* Update prepare.sh

* Update prepare.sh

* fix benchmark script

* fix script path for transformer benchmark
2024-06-27 16:37:47 +08:00
Yuanle Liu
faabf870b5 inference support llama3(wint8|4/a8w8) (#8630)
* inference support llama3

* fix
2024-06-27 10:49:59 +08:00
lugimzzz
69be4dbaf8 fix (#8668)
Co-authored-by: zhangjunjun04 <zhangjunjun04@baidu.com>
2024-06-26 20:07:50 +08:00
LixinGuo
80e7ef55ef fix benchmark dir because of PR#8627 (#8649)
* remove tsinghua pypi

* modify gpt dateset addr for benchmark

* fix run_benchmark for llama2_70b in auto_parallel

* fix autotunner benchmark error and fix llama2 dy2st benchmark

* fix benchmark dir because of PR#8627

* Update run_benchmark.sh

Update run_benchmark.sh

* fix benchmark dir because of PR#8627

* add qwen N4C32

* fix etcd

* fix qwen N4C32 for per_device_type
2024-06-26 18:54:52 +08:00
DrownFish19
4e971f82b6 [DOC] Fix dead link (#8662)
* update dead link

* update dead links

* update dead links

* update dead links

* update dead links
2024-06-26 13:42:23 +08:00
Tian
8edb84e543 [LLM][NPU] fix on readme (#8659) 2024-06-26 10:40:36 +08:00
DrownFish19
381949da62 Fix different length for numpy>=1.24.x (#8655)
* fix different length for numpy>=1.24.x

* update numpy version
2024-06-25 20:49:16 +08:00
DrownFish19
7130c185a9 Add License (#8658) 2024-06-25 14:43:30 +08:00
zhengzhonghui
007b653544 fix fast_ln compile error (#8650) 2024-06-25 11:45:10 +08:00
Leo Chen
11a7fd38f5 align llama auto_parallel dataloader with manual_parallel (#8639) 2024-06-25 11:40:25 +08:00
Tian
25d21402d7 [NPU][LLM] add README & reformat llama scripts (#8642)
* [NPU][LLM] add README & reformat llama scripts

* [LLM][NPU] fix readme 0621

* [LLM][NPU] reformat npu scripts
2024-06-22 11:47:41 +08:00
Difer
65e721e788 [LLM] Add sequence_parallel support for qwen (#8558)
* add sequence_parallel for qwen

* add sequence_parallel in qwen pp
2024-06-21 11:13:11 +08:00
lugimzzz
498f709884 [LLM] change llm content (#8627)
* change llm

* fix

* fix

* fix ci

* fix

* fix

* fix

---------

Co-authored-by: zhangjunjun04 <zhangjunjun04@baidu.com>
2024-06-21 10:51:22 +08:00
gmm
34fcced27f 【benchmark】 fix model_zoo path (#8643)
* add llama-7b_auto_dp2mp2pp2 benchmark sh

* add llama-7b_auto_dp2mp2pp2 benchmark script for cinn

* update llama-7b_auto_dp2mp2pp2 benchmark script

* Update run_benchmark.sh

* Update run_benchmark.sh

* fix llama-7b_auto_dp2mp2pp2/benchmark_common

* Update run_benchmark.sh

* Update prepare.sh

* Update prepare.sh

* Update prepare.sh

* Update prepare.sh

* Update prepare.sh
2024-06-20 19:51:27 +08:00
XiangGao
5619cc3286 because PaddleNLP has changed path of model_zoo, we also changed in ci_case_auto.sh and ci_case_dy.sh (#8633) 2024-06-20 14:12:05 +08:00
DrownFish19
da8b9ac70e [LLM] Support prefix tuning and lora for qwen2 (#8601)
* add unittest for qwen2

* update for tie_word_embeddings

* update qwen2

* update for tokenizer set attr to null

* support prefix training

* fix llm unittest

* fix pipeline and sequence parallel

* add pretrain configs

* add lora, prefix tuning, sft config

* fix pp for lora and recompute
2024-06-20 11:47:03 +08:00
DrownFish19
6bfca91b9f [PaddleNLP 3.0] update dataset preprocess (#8629)
* update datasets preprocess

* add symbolic link 'preprocess' for ernie-1.0
2024-06-20 11:45:45 +08:00
Zhong Hui
7318273ada [PaddleNLP 3.0] Refactor/3 part3, move pipelines. (#8619)
* mv pipelines legacy.

* remove ppdiffusers.

* remove unused.

* refine ci.
2024-06-19 20:43:02 +08:00
zhink
347717b8d4 fix npu llama (#8628) 2024-06-19 20:41:50 +08:00
Ting
fde454c2f5 remove fast generation (#8625)
* remove fast generation

* fix ci
2024-06-19 20:17:45 +08:00
Guoxia Wang
9c59aad16f [LLM] support sparse attention for LLAMA (#8592)
* [LLM] support sparse attention for LLAMA

* fix modeling_pp.py and rename attn_mask_start_row_indices

* fix assert
2024-06-19 17:37:54 +08:00
sneaxiy
7dcd1fdc4d Update PaddleNLP to fix PPO (#8618)
* Update PaddleNLP to fix PPO

* fix lint
2024-06-19 17:06:19 +08:00
Zhong Hui
9361a4e510 Fix dead link (#8626) 2024-06-19 16:28:05 +08:00
Yiqun Liu
970b8680d2 Remove delay_scale_loss and release_grads for llama-2 13B's benchmark. (#8623) 2024-06-19 12:54:59 +08:00
gongel
4e16650ae6 [PaddleNLP 3.0] Refactor RLHF (#8617)
* refactor PPO & RM
2024-06-19 11:23:02 +08:00
Zhong Hui
a8d446c7d5 [PaddleNLP 3.0] Refactor, merge examples/language_model model_zoo to legacy/model_zoo (#8614)
* merge examples/language_model model_zoo to legacy/model_zoo
2024-06-19 11:13:28 +08:00
Ting
2f3af3b662 [PaddleNLP 3.0] Repo adjustment (#8605) 2024-06-19 11:11:25 +08:00
Zhong Hui
cd2a70e385 [PaddleNLP 3.0] Refactor/3 part1- remove fast tokenizer. (#8613)
* delete fast_tokenizer.

* delete deploy with fast_tokenizer.

* delete fast tokenizer in tests.
2024-06-18 18:49:32 +08:00
tianhaodongbd
cbd0ab3a09 Finetune support continue_training (#8615) 2024-06-18 16:11:30 +08:00
DrownFish19
307960cf25 [PaddleNLP 3.0] Refactor examples (#8609) 2024-06-18 11:14:21 +08:00
sneaxiy
c134a7f2ae to_json_string兼容性升级 (#8608)
* to_json_string兼容性升级

* fix lint format
2024-06-17 12:22:45 +08:00
Zhong Hui
0844a5b730 [Feature] Optimize config saving. (#8490)
* support not saving training config.

* fix print.

* add llm meta config to run pretrain.

* fix optionals.

* delete duplicate keys.

* tmp

* change tensor_parallel_output to default to true.

* move out fuse_attention_qkv, fuse_attention_ffn

* add to finetune.

* delete print.

* tensor_parallel_output =  true

* fix

* fix

* fix

* fix to dict.

* bug fix.

* add register_nonsaveable_keys.

* apply register_nonsaveable_keys.

* fix ci.

* fix qwen2

* fix all.

* fix.

* fix ci.
2024-06-14 17:31:41 +08:00
ShenLiang
7bf31a39a1 Add main process print (#8604) 2024-06-14 14:42:11 +08:00
yinwei
439f8f3395 [Bug Fix] fix sharding stage1 allgather overlap bug, which needs to forbiden pin memory (#8594)
* forbiden pin memory
2024-06-13 20:38:33 +08:00
zhink
2dc4d7bb0a [XPU] Open ir pass (#8598) 2024-06-13 20:27:55 +08:00
Zhong Hui
8e24341bf0 Fix dataset with empty char. (#8469)
* fix dataset with empty char.

* revert file links.
2024-06-13 17:11:44 +08:00
Guo Sheng
4bca376b24 Clean ppo main script (#8596) 2024-06-13 15:07:12 +08:00
NeroLoh
77a7693a58 [xpu] change xpu setup.py to paddlenlp_ops (#8595)
Co-authored-by: neroluo <neroluo@github.com>
2024-06-13 14:47:45 +08:00
Guo Sheng
bf6d4e70f6 Add Pipeline Parallel for PPO training and support generation with InferenceModel (#7953)
* Add Pipeline Parallel for PPO training.

* Move new_ppo_trainer.py to ppo_trainer.py

* Fix padding among batches of accumulation steps in _prepare_pipeline_inputs_func.

* Fix hcg using in TP generation

* Try to support generation in PP. And allow extra training args passed from main from_pratrined.

* Support PP generation.

* Fix PP eval by unify prediction_step

* Fix reward value showing error cased by BF16 dtype when eval

* fix all

* Make non-PipelineParallel models use the same loss layer with PipeModel to unify.

* add offload.

* Use create_loss to unify Pipe and non-Pipe usage.

* Add eval mode and offload level.

* merge

* support tp+pp

* fix data split.

* Fix position_ids in generation/eval/train.

* fix data group.

* add tp rank guard

* Support rollout label data both with target length or source+target length.

* Move metric calculation to rl_step to avoid comm.

* fix pad

* fix create group.

* no print

* Suppport inference model generation.

* fix compatible for no eval model.

* fix pp sync.

* remove debug info

* Refacor PPO training using StepTrainer.

* Open PolicyTrainer loss logging postprocess. More StepTrainer docs.

* more timer.

* fix bugs.

* Add EMA and PPOMetric

* add tests

* add unit test for rank guard.

* Fix reshard zero3 and reshard infer.

* Revert #7818 for llama and remove position_ids for gen/train/eval to align.

* Move reload/clean/data_group to comm_utils and use guard to decorate them.

* Offload sync and other data reuse fix.

* Clead code

* Update README

* Update ppo_trainer

* format code

* Fix make_position_ids by 4d causal mask.

* Fix nested_broadcast_tensor_with_empty import

* Update eval with make_attention_mask

---------

Co-authored-by: Zhong Hui <zhonghui.net@gmail.com>
Co-authored-by: gongenlei <gongenlei@baidu.com>
2024-06-13 14:33:56 +08:00
zhink
3d777c1c27 [XPU] xpu devices support llama-7b basic mode inference (turn on BlockAttention) (#8588)
* xpu devices support llama-7b basic mode inference (turn on BlockAttention)
2024-06-13 11:10:51 +08:00
NeroLoh
5ba7a94d52 [xpu] add xpu custom ops support for llama2-7b (#8515) 2024-06-12 20:17:31 +08:00
Zhong Hui
2b557e2feb [CI] Enable test with re-try. (#8590) 2024-06-12 19:33:18 +08:00
Difer
525eef76f0 [CE] Fix autotuner resume case (#8259) 2024-06-12 16:14:03 +08:00
LixinGuo
ef84facad7 [CE] Fix autotunner benchmark error and fix llama2 dy2st benchmark (#8587)
* fix autotunner benchmark error and fix llama2 dy2st benchmark
2024-06-12 16:12:56 +08:00
DrownFish19
5bdf75105e [LLM] Fix Qwen2 (#8584)
* fix output_router_logits

* fix with __future__
2024-06-12 14:03:37 +08:00
DrownFish19
4609d07a54 [LLM] support Qwen2 (#8338)
* add Qwen2Moe

* update default config

* update QWen2Moe modeling

* update modeling

* update ckpt name

* support same prefix model name for auto modeling

* update qwen2moe testing

* update qwen2moe modeling and config

* update qwen2moe import

* fix mlp hidden_size

* update qkv bias convert

* update modeling init_weight

* update _get_name_mappings

* update _get_name_mappings and _init_weight

* add tokenizer

* update modeling

* update modeling

* update  tokenizer

* update modeling and tokenizer

* fix index_add_ error

* fix

* update comments

* update lora weights

* add todo

* update Copyright

* update Moe to MoE

* update comment

* update Copyright

* update readme and json

* update __init__.py

* add qwen-1.5

* update QWen to Qwen

* update Qwen2MoE to Qwen2Moe

* update readme

* update qwen2moe sft and lora json

* update qwen2moe base name

* update qwen2

* update

* update readme

* update readme

* update readme
2024-06-11 20:24:42 +08:00
lugimzzz
909be01bf9 add llama & qwen dpo (#8474)
* add llama&qwen dpo

* add

* add dpo

* fix bug

* add
2024-06-11 14:33:47 +08:00
ShenLiang
547d29c7e9 Add async save for optimizer (#8557) 2024-06-11 14:22:14 +08:00
Zhong Hui
eaf8cb13a4 [CI] Fix ci pyproject.toml (#8541)
* Update pyproject.toml
2024-06-11 11:48:08 +08:00
Zhong Hui
fe5b6fd900 fix test_long_sequence_strategies (#8568) 2024-06-11 11:11:19 +08:00
sneaxiy
bcacc6aa21 [Cherry pick] Sharding reshard function enhancement (#8544)
* fix bug of sharding format (#8483)

* Optimize the speed of set_state_dict (#8532)

* fix sharding reshard save (#8535)

* Fix ignore_data_skip bug when timer is enabled (#8536)

* Save parameter shape and dtype when using sharding reshard (#8543)

* save parameter shape and dtype

* refactor

* format pre-commit

---------

Co-authored-by: ShenLiang <2282912238@qq.com>
2024-06-11 10:23:28 +08:00
Ghost Screaming
162d8d31c8 [AutoParallel] Add benchmark for llama-7b-dy2st. (#8559)
* [AutoParallel] Add benchmark for llama-7b-dy2st.
2024-06-07 14:40:05 +08:00
Zhong Hui
f89c91d960 [FIX DDP] fix ddp (#8549)
* enable trainer tests.
2024-06-07 14:37:38 +08:00
Galaxy1458
4e3f60dbc5 Update llama_npu_opt_lora.sh (#8562) 2024-06-06 20:58:13 +08:00
ronnywang
8887ed5ed6 fix llama export (#8561) 2024-06-06 16:52:24 +08:00
lzy
0e0c9b4c92 Update generation_utils.py (#8502)
* Update generation_utils.py

* Update generation_utils.py
2024-06-06 15:18:13 +08:00
zhengzhonghui
d06b3279d4 add fuse_attention_ffn support for qwen (#8526) 2024-06-06 14:47:34 +08:00
Zhong Hui
79e8b6eefd Update modeling.py (#8548) 2024-06-06 14:45:30 +08:00
Siming Dai
66ad506a67 Update sequence_parallel for predict (#8551) 2024-06-06 13:10:26 +08:00
sneaxiy
5a6d0fa98e fix memory leak bug (#8546) 2024-06-06 11:21:47 +08:00
gmm
b0a8cdddc8 【benchmark】 add llama-7b_auto_dp2mp2pp2 benchmark script for cinn (#8423)
* add llama-7b_auto_dp2mp2pp2 benchmark sh

* add llama-7b_auto_dp2mp2pp2 benchmark script for cinn

* update llama-7b_auto_dp2mp2pp2 benchmark script

* Update run_benchmark.sh

* Update run_benchmark.sh

* fix llama-7b_auto_dp2mp2pp2/benchmark_common

* Update run_benchmark.sh
2024-06-06 11:12:38 +08:00
ronnywang
87edf28f9a support fused weights for export_model (#8554) 2024-06-06 09:58:50 +08:00
greycooker
d98d722de3 del codev (#8555) 2024-06-06 09:08:55 +08:00
zhangyuqin1998
4cb8b6d053 Add RingFlashAttention for context parallel (#8383)
* Add RingFlashAttention for context parallel

* update, using sep_group

* using sep group

* fix

* fix

* update

* fix
2024-06-05 22:01:40 +08:00
ShenLiang
91936bdaae [Cherry-pick] Add release grad & sharding format & decorate_exclude_layers (#8545)
* fix bug of sharding format (#8483)

* Add release grad for SD (#8478)

* add decorate_exclude_layers

---------

Co-authored-by: westfish <westfish@126.com>
2024-06-05 21:56:57 +08:00
Xuanang Chen
1cf780e4d7 add mteb evaluation (#8538)
* add mteb evaluation

* add mteb evaluation

* add mteb evaluation

* add mteb evaluation
2024-06-05 20:41:22 +08:00
Zhong Hui
3c21f0ae56 Update run_ci.sh (#8552) 2024-06-05 20:22:45 +08:00
Zhong Hui
f36ed75f4f update source. (#8540) 2024-06-04 20:48:24 +08:00
asr-sheep1
4c9a3f5ded fused_ln:Added implementation for the HIP platform (#8472) 2024-06-04 16:55:51 +08:00
tianhaodongbd
cb8a229794 [BugFix][NPU] fix llama attn_mask astype error (#8528) 2024-06-04 16:31:45 +08:00
Zhong Hui
f8cdd3dcb0 fix eval. (#8529)
* fix eval.

* fix
2024-06-04 11:30:39 +08:00
yinwei
0087c4a801 update code (#8519) 2024-06-03 13:34:39 +08:00
Zhong Hui
2286799c01 [Safetensors] Fix fast safe open slice. (#8512)
* fix more case.

* fix slice.

* fix error slice.
2024-06-03 11:19:01 +08:00
wawltor
fd2a39ee04 Update README.md (#8524) 2024-06-03 10:21:05 +08:00
Ferrebo
440c093867 [fix] Broadcast optimizer state using broadcast_dp without shard-reshard. (#8522) 2024-06-03 09:55:03 +08:00
yinwei
e71540bfc6 Add Sharding V1 broadcast and allgather overlap optimize (#8499)
* update

* update is_casual_mask to use_casual_mask

* update by environment

* add constraint

* add pretrain and finetune enviroment

* update

* update

* Update finetune_generation.py

update use_casual_mask env

* update

* lint code

---------

Co-authored-by: zhengzhonghui <zhengzhonghui@baidu.com>
Co-authored-by: lizhiyu <1528794076@qq.com>
2024-05-31 16:10:16 +08:00
Ferrebo
ac7145dae4 [fea] moe support (#8498)
Co-authored-by: kebo01 <kebo01@baidu.com>
2024-05-31 14:43:36 +08:00
Galaxy1458
60c661546b Update merge_lora_params.py (#8514)
* Update merge_lora_params.py

* Update merge_lora_params.py

* Update merge_lora_params.py
2024-05-31 11:05:25 +08:00
Zhong Hui
92aa9f1767 Update model_utils.py (#8509) 2024-05-30 11:31:27 +08:00
Tian
d8adc2b9d1 [LLM] disable part of MC2 in lora (#8505) 2024-05-29 13:18:33 +08:00
ming1753
c1cfe631df modify block_multihead_attention api (#8456)
* modify block_multihead_attention api

* add param to blha

* modify fused_transformer_layers

* fix bug
2024-05-28 18:52:56 +08:00
Ghost Screaming
85ba5735c3 [AutoParallel] Support qwen for auto_parallel (#8312)
* run 4096

* support 3d semi auto run of qwen model

* [AutoParallel] Add qwen auto parallel.

* Delete useless files.

* Fix code style problem.

* Fix problems.

* Polish code.

* Add CI-cases.

* Add bf16 ci testcase.

* Fix some problems.

---------

Co-authored-by: pangengzheng <pangengzheng@baidu.com>
Co-authored-by: pangengzheng <pangengzheng.baidu.com>
2024-05-28 10:12:39 +08:00
zhangyuqin1998
d4edd19194 Fix rng_state in llm models (#8396) 2024-05-27 14:30:23 +08:00
Zhong Hui
773497e2e6 quick fix from pretrained. (#8486) 2024-05-27 12:51:20 +08:00
lzydev
d8e1a6b2b6 【AutoParallel】Add split_backward for vpp (#8479)
* add split_backward for vpp

* polish

* add test cast

* polish

* update test case

* change the config

* polish
2024-05-27 10:54:27 +08:00
LixinGuo
a90f16353d fix run_benchmark for llama2_70b in auto_parallel (#8484)
* remove tsinghua pypi

* modify gpt dateset addr for benchmark

* fix run_benchmark for llama2_70b in auto_parallel
2024-05-24 16:51:23 +08:00
Tian
0cd8fe7ee5 Revert "Support Sharding Overlap (#8473)" (#8491)
This reverts commit 7aaa788069.
2024-05-24 15:28:09 +08:00
yinwei
7aaa788069 Support Sharding Overlap (#8473)
* update

* update is_casual_mask to use_casual_mask

* update by environment
2024-05-24 10:17:21 +08:00
yinfan98
c6f4159d9c [Ops] RoPE kernel support theta input (#8440)
* [RoPE] feat: support theta

* Update modeling.py

* [RoPE] feat: support theta for qwen
2024-05-23 11:26:21 +08:00
EnflameGCU
621118e487 fix rotary_emb for llama (#8470) 2024-05-22 20:44:25 +08:00
Lucas
70bffa8df3 [LLM] fix bug when loss is None in llama modeling.py (#8459) 2024-05-22 13:58:25 +08:00
ronnywang
87e4c4fa87 [NPU] support npu llama2-13B export & inference (#8442)
* [NPU] support npu llama2-13B export & inference

* move csrc_npu to csrc/npu
2024-05-20 22:15:10 +08:00
Zhong Hui
9064078e8d Fix CI tests. (#8471) 2024-05-20 19:29:07 +08:00
zhangbo9674
b36b6a01a6 Add llama2-70b for test_tipc (#8455) 2024-05-17 20:56:30 +08:00
Liujie0926
5d4ce560ef [benchmark]Add llama2 auto (#8424)
* fix ci requirements

* add llama2_auto benchmark

* fix

* update config

* Add ips log for per card
2024-05-17 16:12:49 +08:00
w5688414
9381e9fe78 [bugfix] fix erniedoc (#8393)
* fix erniedoc

* revert
2024-05-17 16:10:50 +08:00
EnflameGCU
d9dcd9a797 [GCU] Support llama for GCU (#8445) 2024-05-17 15:26:21 +08:00
Galaxy1458
7f13396332 update (#8448)
* update

* add llama-npu-opt-script

* Update dev_opt_lora.sh

* Update dev_opt_ppt.sh

* Update dev_opt_lora.sh

* Update dev_opt_ppt.sh

* Update dev_opt_sft.sh

* Rename dev_opt_lora.sh to llama_npu_opt_lora.sh

* Update dev_opt_ppt.sh

* Rename dev_opt_ppt.sh to llama_npu_opt_ppt.sh

* Update llama_npu_opt_lora.sh

* Update and rename dev_opt_sft.sh to llama_npu_opt_sft.sh

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* update

* Update fusion_ops.py

* update

* update
2024-05-17 12:52:56 +08:00
Zhong Hui
daf2f3ae6b fix load rng compatiblity. (#8450) 2024-05-17 11:15:39 +08:00
zhangbo9674
ebe397ea52 Support fused_attention_qkv for auto_parallel llama (#8432)
* add

* add

* add

* add

* add
2024-05-16 18:37:30 +08:00
Zhong Hui
562229c1da Fix/test gpu (#8452)
* fix safe open.

* fix online ci.
2024-05-16 17:15:33 +08:00
Zhong Hui
21eb6bdcac Fix CI bugs (#8430)
* fix bugs

* swith test to python 3.10

* skip test.

* update python version.

* fix bugs

* fix gradio

* test.

* fix all
2024-05-16 13:13:54 +08:00
NINGBENZHE
5170664dbf fix npu sft ckpt load bug and no FA bug (#8438)
Co-authored-by: NINGBENZHE <zhenwenqi@huawei.com>
2024-05-15 19:58:52 +08:00
Liujie0926
5da340e038 Add scripts for unittest (#8433) 2024-05-15 14:46:21 +08:00
Galaxy1458
11aba32ace Update llama_npu_opt_lora.sh (#8439) 2024-05-15 10:12:49 +08:00
Yuanle Liu
6902c3e179 delete csrc/generation/reset_need_stop_value.cc (#8413) 2024-05-14 21:09:15 +08:00
Galaxy1458
05acad574e [NPU]Custom fusion operator unification (#8431)
* update

* add llama-npu-opt-script

* Update dev_opt_lora.sh

* Update dev_opt_ppt.sh

* Update dev_opt_lora.sh

* Update dev_opt_ppt.sh

* Update dev_opt_sft.sh

* Rename dev_opt_lora.sh to llama_npu_opt_lora.sh

* Update dev_opt_ppt.sh

* Rename dev_opt_ppt.sh to llama_npu_opt_ppt.sh

* Update llama_npu_opt_lora.sh

* Update and rename dev_opt_sft.sh to llama_npu_opt_sft.sh

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* add funsion ops

* update

* Update fusion_ops.py

* update
2024-05-14 13:47:45 +08:00
Tian
53ad2da1a8 [LLM] add assertion for enable_stage1_overlap in lora mode (#8425) 2024-05-13 15:29:43 +08:00
Galaxy1458
17fb497af4 add npu-llama-opt0-script (#8401)
* update

* add llama-npu-opt-script

* Update dev_opt_lora.sh

* Update dev_opt_ppt.sh

* Update dev_opt_lora.sh

* Update dev_opt_ppt.sh

* Update dev_opt_sft.sh

* Rename dev_opt_lora.sh to llama_npu_opt_lora.sh

* Update dev_opt_ppt.sh

* Rename dev_opt_ppt.sh to llama_npu_opt_ppt.sh

* Update llama_npu_opt_lora.sh

* Update and rename dev_opt_sft.sh to llama_npu_opt_sft.sh
2024-05-13 13:59:53 +08:00
Zhong Hui
474aaaaf30 fix llama3 eot. (#8371) 2024-05-13 13:24:15 +08:00
zxcd
d9f555e85f Adapter new type promotion rule for Paddle 2.6 (#8421) 2024-05-13 11:15:44 +08:00
Zhong Hui
fe6277fa93 Fix safe open. (#8422) 2024-05-13 11:00:34 +08:00
Siming Dai
6bd2b0d9da fix distdataloader, fix eval with dp group (#8420) 2024-05-13 10:46:56 +08:00
Tian
f27fdb41a3 [LLM] relocate tensor_parallel_output to avoid conflict (#8419) 2024-05-11 17:22:39 +08:00
gongel
29d40e2da1 last ckpt should be model done when afs (#8402) 2024-05-11 14:30:44 +08:00
zxcd
99fbc418f2 Fix type promotion problem. (#8414)
* fix type promotion problem.
2024-05-11 11:42:30 +08:00
Tian
c6e5459703 [Distributed] metric calculation supports tp logits (#8370) 2024-05-10 21:47:40 +08:00
zhangbo9674
ac117a108d Refine position_ids for auto parallel training of llama (#8363)
* fix

* fix

* fix
2024-05-10 19:36:21 +08:00
wanghuancoder
16ef8f414c pre copy pinned data to gpu (#8386) 2024-05-10 16:09:53 +08:00
Zhong Hui
9146c1e492 fix compatible with npu. (#8409) 2024-05-09 21:16:23 +08:00
DrownFish19
2619f17029 [LLM] Fix fuse or split with same key (#8378)
* fix fuse or split with same key

* fix

* fix eps

* update format
2024-05-09 17:51:32 +08:00
Siming Dai
a13975886e [DistDataloader] Update implementation, add nested.py (#8380)
* Fix sharding overlap bug

* [DistDataloader] Update implementation, add nested.py

* Fix pipeline

* add first try

* update dataloader

---------

Co-authored-by: lugimzzz <zhenglujing@baidu.com>
2024-05-09 17:51:06 +08:00
Leo Chen
46f49dfa03 fit for llama3 for auto_parallel (#8395)
* fit for llama3

* add run scripts
2024-05-09 16:52:15 +08:00
w5688414
c02712e197 [bugfix] fix uie (#8379)
* fix uie

* fix windows bug
2024-05-09 14:24:42 +08:00
w5688414
eeafb21acf Fix fast tokenizer import error (#8367) 2024-05-09 14:21:11 +08:00
Galaxy1458
6b3875c0dd update (#8399) 2024-05-09 13:09:31 +08:00
Zhong Hui
d6ac1bd5da [Performance] Optimize unified checkpoint save/load speed. (#8204)
* opt unified checkpoint save/load speed.

* fix bug.

* add fast safe open API.

* mix file open and mmap.

* fix

* add test for read fast read tensors.

* fix

* fix tests.

* remove profile log.

* fix

* fix ci
2024-05-08 20:50:18 +08:00
Zhong Hui
2f3faff947 fix init (#8377)
Co-authored-by: lugimzzz <zhenglujing@baidu.com>
2024-05-08 20:14:35 +08:00
Zhong Hui
0f458750b9 Revert "update" (#8389)
* Revert "update (#8359)"

This reverts commit ae0bea9e85.

* Update modeling.py

* fix

---------

Co-authored-by: lugimzzz <zhenglujing@baidu.com>
2024-05-08 19:00:00 +08:00
Liujie0926
829e7f03a5 fix llama2 benchmark (#8376) 2024-05-08 15:11:35 +08:00
Kunbo Ding
a85a9a9a1c [BugFix] Update truncate in distributed training (#8362)
* Remove truncate

* update truncate

* update truncate
2024-05-08 15:08:01 +08:00
wanghuancoder
18e5cee909 refine benchmard bert ips stat (#8361)
* refine benchmard bert ips stat

* refine

* refine
2024-05-08 14:00:24 +08:00
w5688414
ae0450a63e [paddle-pipelines] Update offline ann (#8353)
* Update offline ann

* update offline_ann.py
2024-05-08 10:48:44 +08:00
Tian
9f3cf822c6 [LLM] fix lora target modules on llama (#8372) 2024-05-07 18:54:01 +08:00
Galaxy1458
ae0bea9e85 update (#8359)
* change llama/modeling.py to opt npu performence

* update

* update

* Update modeling.py

* add judge

* update

* update

---------

Co-authored-by: Wang Huan <wanghuan29@baidu.com>
2024-05-07 16:29:31 +08:00
Yiqun Liu
09a0ce7278 Disable eval and predict for llama-2 benchmark. (#8366) 2024-05-07 14:35:50 +08:00
Sijun He
fdcabf8e5f Update README.md 2024-05-06 12:09:11 +08:00
w5688414
3aa92ce269 Update llm docs requirements (#8336)
* Update llm docs

* Update requirements.txt

* try to fix
2024-04-30 15:01:15 +08:00
Galaxy1458
1c781d8e57 change llama/modeling.py to opt npu performence (#8342)
* change llama/modeling.py to opt npu performence

* update

* update

* Update modeling.py

* add judge

---------

Co-authored-by: Wang Huan <wanghuan29@baidu.com>
2024-04-30 14:33:37 +08:00
Leo Chen
e7de0fa5ca add eliminate_transpose arg (#8339) 2024-04-30 14:03:24 +08:00
Jianbang Yang
ba9d9bd53c [XPU] llama add xpu support (#8282)
* [XPU] llama add xpu support

* fix

* use try import

* fix

* refine

* refine

* refine

* refine
2024-04-29 16:20:11 +08:00
zhangbo9674
62b58a3f0c [Pre-Train] Add num_hidden_layer for pretraining (#8288) 2024-04-29 14:54:12 +08:00
zhangbo9674
db52319a0c fix bug (#8329) 2024-04-28 20:57:17 +08:00
Southpika
71cc40463b [Tokenizer]Add Chat template (#8226)
* add jinja template

* add in cfg

* add system

* add notes

* fix apply chat template

* add generation flag

* update jinja ut

* fix error

* add syntax error check

* fix syntax error

* refresh codev

* refresh codecov

* update special token map in render

* update save

* add multi round chat ut

* use new api

* rm pdb

* add split ut

* fix des

* fix ut
2024-04-28 19:46:22 +08:00
Siming Dai
7c3ab53193 Fix sharding overlap bug (#8333) 2024-04-28 16:37:56 +08:00
Zhong Hui
ea2926c105 [BugFix] Fix gpu ci (#8337)
* fix test_synced_gpus

* fix all ci
2024-04-28 10:12:07 +08:00
Xuanang Chen
cb9ba2d185 textfeature_queryinput (#8331) 2024-04-26 18:55:48 +08:00
w5688414
a37f53d6e0 cherry pick paddlenlp 2.8 (#8323)
* cherry pick paddlenlp 2.8

* Update README
2024-04-26 16:00:41 +08:00
Ruibiao Chen
ae06f0cb66 [DEV] Support sync params in tensor parallel config (#8311)
* [DEV] Support sync params in tensor parallel config

* Update code
2024-04-26 15:10:01 +08:00
w5688414
6ed54d8cdc fix try import (#8332) 2024-04-26 14:01:54 +08:00
Tian
de149078f8 [Distributed] fix lora (#8325) 2024-04-25 21:23:39 +08:00
DrownFish19
f29a7b905f [LLM] Support fuse attention q, k, v weights (#8202)
1. add use-interface & fuse action

1.1. modify 1., code order

2. switch to name_mapping

3. solve tp branch

3.2 follow hui, handel qkv separately

3.3 handle pdparams

3.4 from torch

3.5 abandon low_cpu_mem_usage

3.6 solve shard branch

* 3.6.1 solve shard branch after rebase develop

* code clean

* remove debug comment

* Redefine fuse and split functions

* Redefine fuse and split functions

* comment and fix

* update method

* update QKV fuse and split

* support fuse weights in multi-files

* add precision compare

* simplify function call

* support use_fast_ffn

* clean modeling and configuration

* add test for gpt and opt

* fix tp_actions get

* add fast_ffn test

* add Qwen2Moe

* Revert "add Qwen2Moe"

This reverts commit 113b8838a7.

* add test for split

* update doc

* update filter_dict_keys

---------

Co-authored-by: Zii <ziangqin.baidu@gmail.com>
2024-04-25 16:11:39 +08:00
zhangbo9674
1a73b76afa fix (#8321) 2024-04-24 20:59:01 +08:00
lzydev
af3041c2ff 【AutoParallel】Add llama2 UT for auto-parallel (#8300)
* add llama UT

* add llama UT

* update data

* instatll external ops

* update data

* update data
2024-04-24 19:24:51 +08:00
wanghuancoder
273c593fd5 benchmark llama worker=1 (#8305) 2024-04-24 17:28:49 +08:00
Liujie0926
277f45bfbe [dist CI]fix (#8283) 2024-04-24 15:42:01 +08:00
Liujie0926
d22bded11d [benchmark]update llama2_ips (#8322) 2024-04-24 15:41:42 +08:00
w5688414
1ffa290841 [paddle-pipelines] Update mkdocs (#8310)
* Update mkdocs

* Update mkdocs configuration

* migrate paths

* change root path

* try to fix

* revert

* Update memory.md

* restore agent.md path

* fix path error

* Add index.md

* Update README.md

* Update README.md
2024-04-24 11:27:59 +08:00
Yuang Liu
eaca5b29b0 bug fixer (#8314) 2024-04-24 10:35:17 +08:00
Tian
bc91dc620f [Distributed] [CustomDevices] Adapt SP on lora && polish MC2 APIs (#8303)
* [Distributed] adapt sequence parallel on LoRA (#8235)

* [Distributed] [CustomDevices] adapt lora sp && polish MC2 APIs
2024-04-23 23:18:11 +08:00
Zhong Hui
98588af263 Support llama-3 (#8307)
* support llama-3

* Add llama-3 tokenizer

* fix for llama3
2024-04-23 19:18:52 +08:00
w5688414
e67fd7881d [paddle-pipelines] Add pipelines documentation (#8308)
* Add pipelines documentation

* Update pipeline docs

* remove rss module

* Update docs

* Update site url
2024-04-23 11:06:29 +08:00
w5688414
40398976f6 [paddle-pipelines] faq semantic search question answering reamde (#8292)
* Update dense qa readme

* Update readme

* Update semantic search readme
2024-04-21 16:01:31 +08:00
Leo Chen
3bb4bb751e add a100 test ground truth (#8249)
* add a100 test ground truth

* add requirements

* cache is_a100 result

* update

* update

* update sp allclose

* fix check_result

* add ground truth for llm_gpt_dygraph
2024-04-18 19:38:20 +08:00
Yiqun Liu
909ff315d5 Add p2p_comm_overlap for Llama-2-70b benchmark. (#8276) 2024-04-18 16:21:21 +08:00
Tian
beb433a9ae [LLM] add memory stats to logger of trainer (#8269) 2024-04-17 10:22:44 +08:00
Southpika
c3ec984db7 [Bug Fix]Fix merge parameters in pp (#8239)
* update merge pp

* update des

* renew
2024-04-16 20:16:12 +08:00
Liujie0926
07908243ee update paddlenlp (#8267) 2024-04-16 16:48:53 +08:00
wanghuancoder
ee88c12457 use tensor.shape bug not paddle.shape(tensor) (#8260)
* use tensor.shape bug not paddle.shape(tensor)

* refine

* refine
2024-04-16 14:22:10 +08:00
sneaxiy
f658fa7a89 fix sharding <100 limitation (#8146) 2024-04-16 14:21:49 +08:00
zhangbo9674
1ef7503861 fix (#8265) 2024-04-15 15:43:23 +08:00
Sijun He
f4a8f4cb7e Update tests.yml (#8268) 2024-04-14 15:49:03 +08:00
Siming Dai
3566381385 [BugFix] Try except sequence parallel utils (#8189)
* try except sp

* fix sp import
2024-04-12 22:19:48 +08:00
Southpika
3515e32923 [LLM]Support Gemma model (#8082)
* add model

* add cfg&tokenizer

* update weight share

* rm useless notes

* rm pdb

* add cfg

* fix version

* fix

* fix des

* fix des

* update url

* fix some logic

* add it model

* update_cfg

* add modeling ut

* add link

* fix typing

* fix typing

* add init

* add tokenizer ut

* fix small bug

* add alibi

* add addedtoken str

* add special attr

* add tp ut

* merge

* apply api change

* rm hard code cfg

* fix ut

* fix ut

* add zero padding

* upload bf16 safetensors model

* fix

* add gemma in sft data convert

* add gemma in sft data convert

* add gemma tokenizer

* fix des

* rm fast tokenizer

* update sft cfg

* cherry-pick pp from develop

* add cfg
2024-04-12 16:04:20 +08:00
lugimzzz
0d055448c3 add scaling (#8256)
* add scaling

* add scaling

* add scaling

* format
2024-04-12 11:18:13 +08:00
Liujie0926
662feb1692 [dist]pip requirements-dev.txt (#8258)
* pip requirements-dev.txt

* fix
2024-04-11 21:07:18 +08:00
Kunbo Ding
62d5609c3d Fix timer for NPU&XPU (#8261)
* Fix timer for NPU&XPU

* Fix NPU/XPU timer
2024-04-11 19:05:31 +08:00
w5688414
84615ea086 Fix gpt download bug (#8253) 2024-04-11 14:06:34 +08:00
w5688414
814e9c4724 Add DeBERTa model (#8227)
* Add DeBERTa model

* trigger unitest

* Add hf mirror

* fix unitest

* Update deberta v2 model

* Update debertav2

* Update deberta config

* Update deberta docs

* Update docs

* support stabledropout

* refine tokenizer and comments

* fix tokenizer

* try to fix connection error

* Update deberta unitest

* Add deberta doc

* removev useless comments

* Add deberta contents.rst
2024-04-11 11:47:32 +08:00
yujun
9b89f45d6c [BUG] fix to_static (#8194)
* fix

* 限制huggingface hub版本
2024-04-11 11:17:32 +08:00
Lu Qi
2900f78002 [LLM] Optimize llm/GPT3 performance (#8172) 2024-04-11 11:15:18 +08:00
Ting
a6d3a2857b Pissa (#8250)
* single gpu pissa impl

* fix

* scale update

* raise error in mp

* update pissa config

* add pissa config
2024-04-11 11:00:45 +08:00
Tian
bd25e0cd62 [LLM] add decay steps option for finetuning (#8251) 2024-04-10 21:32:00 +08:00
liym27
98a4b84bdc [AutoParallel] support GPT for auto_parallel (#8160)
* add modeling_auto.py

* add run sh

add run_pretrain

modify llama test loss

* comment llama

comment llama

* update

* fix
2024-04-10 19:47:48 +08:00
tianhaodongbd
79cb8b6acd fix llama fa bug (#8237) 2024-04-09 18:40:32 +08:00
Yuang Liu
c1aad028c2 bug fix (#8238) 2024-04-09 17:34:48 +08:00
Zeyu Chen
70f4a6fcf8 Rename ernie-tiny to ernie-3.0-tiny 2024-04-09 15:35:47 +08:00
zhangbo9674
220d867d16 fix (#8234) 2024-04-09 15:29:35 +08:00
gongel
a5f69e4543 add checkpoint_done to last model (#8223) 2024-04-08 14:56:20 +08:00
NINGBENZHE
ae7dc15a62 add mc2 & finetune fused (#8139) 2024-04-03 20:20:24 +08:00
Tian
2273ee7812 [Distributed] Support pp non batch comm (#8097) (#8222)
* add disable_non_batch_p2p_comm to pipeline_parallel_config
2024-04-02 11:45:23 +08:00
zhangbo9674
7b493a8e8b Support sharding for auto_trainer (#8164)
* add

* fix

* refine code

* refine

* fix

* fix

* fix

* refine
2024-04-01 10:23:14 +08:00
w5688414
4d661bc34b remove ._static_mode for static model (#8214) 2024-03-29 18:05:46 +08:00
wuhuachaocoding
50b449104f update for npu. (#8210) 2024-03-29 16:26:58 +08:00
w5688414
57b22e7052 [Paddle-Pipelines] Add matryoshka representation learning (#8165)
* Add matryoshka training

* Update README.md

* Update modeling.py

* reformat trainer
2024-03-28 14:59:14 +08:00
lzydev
6b8f7f918a change the dtype of initializing the model (#8199) 2024-03-27 20:43:57 +08:00
yujun
acfa7f29b5 关闭从hf下载和aistudio下载的单测. (#8198) 2024-03-27 18:00:06 +08:00
lzydev
4d49a3e8a2 【AutoParallel】Change llama in auto-parallel (#8151)
* change llama in auto

* change ci

* polish
2024-03-26 20:42:57 +08:00
Zhong Hui
89bff208da save rng state not seed. (#8185) 2024-03-26 16:48:44 +08:00
WAI-clear
6b5099ada2 add long sequence strategies (#8076)
* test

* remove test.txt

* add long sequence strategies

* long sequence V1

* draft

* draft

* draft new

* add long sequence stratiges

* add long sequence strategies new

* fix format

* fix conflict

* fix format

* fix error

* fix error

* fix format

* fix format

* fix format

* fix format

* close @slow

* fix test

* fix error

* modify try_catch

* fix format

* fix format

* fix format

* add bloom_alibi

* fix error

* add dynamic_to_static

* add dynamic_to_static
2024-03-26 09:42:01 +08:00
wuhuachaocoding
a0457d14d5 adapt npu FA. (#8171) 2024-03-25 16:50:47 +08:00
Lu Qi
a5d87f5d1a [BugFix] Fix FusedLinearWithGradAdd usage (#8178) 2024-03-25 15:44:47 +08:00
Guoxia Wang
a33a4f341a fix read-data timer when ignore_data_skip=False and skip_profile_timer=False (#8177) 2024-03-25 14:56:22 +08:00
yujun
d577e19b5e [LoRA] add quick_lora (#8106)
* quick_lora

* add use_quick_lora

* update

* update

* update

* update

* When lora and use_quick_lora are enabled, recompute_use_reentrant must be set to True to prevent any potential errors from occurring.

* update code

* update
2024-03-25 13:56:58 +08:00
Haohongxiang
feb69cf7c2 add arg (#8168) 2024-03-22 17:02:31 +08:00
w5688414
f005084a87 [Paddle-pipelines] Add pytorch retrieval model tutorials (#8159)
* Add pytorch retrieval model tutorials

* Update doc

* fix unitests

* Update docs

* Update torch2paddle tutorial
2024-03-21 16:00:51 +08:00
gongel
4d35236aba Json parsers supports raise error (#8163) 2024-03-21 14:28:21 +08:00
yinwei
a092775a52 Replace Sequence Parallel to Paddle Sequence Parallel (#7966)
* sp support overlap
* add mixtral sp
2024-03-21 14:05:59 +08:00
wuhuachaocoding
8f2b19d9fd support mc2 for mp lora. (#8161) 2024-03-21 12:13:56 +08:00
Zhong Hui
ac57ad7c77 Squashed commit of the following: (#8157)
Merge remote-tracking branch 'origin/develop' into bugfix/sample_generate
    Update Makefile
    Update Makefile
    remove paddle as require.
    fix  https://github.com/PaddlePaddle/Paddle/issues/62860
    fix test_sample_generate bug.
2024-03-20 20:36:00 +08:00
Siming Dai
b6dcb4e19e [Unified Checkpoint] Fix tie_weights save and load (#8137)
* fix unified checkpoint tie_weight

* unify static2struct_name_mappings

* fix chatglm model

* fix trainer

* fix attr

* simplify code

* add single card config save
2024-03-19 21:54:33 +08:00
Liujie0926
99802de4ee add auto_pir case (#8144) 2024-03-19 17:39:37 +08:00
zxcd
d46a96e320 Adapter new type promotion rule for Paddle 2.6 (#8079) 2024-03-19 15:07:59 +08:00
Ting Liu
7370d72e5b add rslora & lora+ (#8111)
* add rslora & lora+

* remove print

* reformat

* update

* fix bug

* add rslora+ ci

* remove magic number

* update

* empty

---------

Co-authored-by: lugimzzz <zhenglujing@baidu.com>
2024-03-19 13:02:02 +08:00
lugimzzz
1cd270a155 text classification (#8110) 2024-03-18 14:26:33 +08:00
ShenLiang
57791863fc fix config bug (#8128) 2024-03-18 10:17:18 +08:00
Liujie0926
1b373a8ec7 [benchmark]add skip_memory_metrics for ce_gpt (#8132)
* add skip_memory_metrics

* add skip_memory_metrics for autotuner
2024-03-18 10:07:18 +08:00
zhengzhonghui
d83bd5ef3c [AutoParallel] unify llama model (#8127)
* [AutoParallel] unify llama model

* attention_mask can be None
2024-03-15 16:33:11 +08:00
lzydev
c406d90545 【AutoParallel】Add strategy with more options (#8114)
* add strategy

* polish
2024-03-14 16:53:21 +08:00
Ting Liu
880d2ea68d qwen init bug fix (#8120) 2024-03-14 14:47:22 +08:00
Zhong Hui
5fdc3c2126 Update trainer.py (#8117) 2024-03-14 13:56:44 +08:00
Siming Dai
0a39fbffd1 [Trainer] Change num_train_epochs default value (#8113)
* change num_train_epochs default value

* update docs
2024-03-13 20:38:31 +08:00
Liujie0926
e145bfc97a [dist benchmark]add llama2 with autotuner (#8108)
* benchmark scripts

* update case device

* test

* Revert "test"

This reverts commit 75bf72c7ee.

* update

* Update CE_meta-llama-Llama-2-7b_pretrain_bs32_bf16_autotuner.sh

* fix

* update

* add top1 case

* fix

* add 13b/70b autotuner

* update autoconfig

* remove enable_stage1_tensor_fusion

* update ips

* add top1 config
2024-03-13 14:10:33 +08:00
Liujie0926
8f9734df29 update llm_gpt_recompute_bs32_bf16_MP2-SD4-stage1 loss_base for Paddle#62500 (#8107) 2024-03-13 14:09:56 +08:00
骑马小猫
acacb470c2 [Bug fixes] convert min_new_token -> min_new_tokens (#7883)
* convert min_new_token -> min_new_tokens

* fix f-string linting

* update warning log testing
2024-03-12 20:02:28 +08:00
LOVE-YOURSELF-1
646a42919d Download----fix new bug (#8088)
* fix new bug

* resolve bug

* modified locks_path

* fix None bug

* Update bos_download.py

* Update tokenizer.py

* skip

---------

Co-authored-by: yujun <50394665+JunnYu@users.noreply.github.com>
Co-authored-by: yujun <573009727@qq.com>
2024-03-12 19:02:51 +08:00
PeiyuLau
196db7ee2f dist dataloader: add cuda compilation check (#8099) 2024-03-12 17:46:09 +08:00
ShenLiang
60b9755f70 [BugFix]Rm overlap limit in dp & pp (#8089)
* rm overlap in dp & pp

* fix bug in comm overlap
2024-03-11 18:51:59 +08:00
greycooker
6fd186da24 [BugFix] fix test tensorboard callback (#8066) 2024-03-11 16:17:00 +08:00
gongel
557c794655 add log (#8058)
Co-authored-by: gongel <gongel@qq.com>
2024-03-11 11:51:36 +08:00
ShenLiang
d48dc75f7c paddlenlp/trainer/training_args.py (#8051) 2024-03-11 10:43:39 +08:00
Sonder
67964cf583 [Distributed] Add dp_gradient_sync_after_accumulate (#8045)
* add dp_gradient_sync_after_accumulate

* recover run_pretrain_auto_static.sh

* recover

* use gradient_sync_after_accumulate

* change name under DP_OPTIMIZATION

* add doc for data_parallel_config

* update notes

* add note and recover codes

* add note
2024-03-08 17:36:35 +08:00
LOVE-YOURSELF-1
95c8b24f7c Download重构 (#8020)
* download

* modified file

* modified from_pretrained

* modified config

* modified download

* test_tokenizer

* Delete tests/transformers/from_pretrained/run.sh

* Update test_tokenizer.py

* Update tokenizer_utils_base.py

* test_model

* test_model

* test_model

* Remove comments

* Remove comments

* add requirements

* update bos download

* Update test_model.py

* clear unused import

* modified bug tokenizer_utils_base.py

* change safetensors

* modified load generation config

* add requestion

* 更新

* modified error

* fix bug

* add \n

* Update __init__.py

* add requestion

* modified download

* 重测

* Update test_tokenizer.py

* Update requirements-dev.txt

* Update requirements.txt

* delete from_pretrained

* make superior

* Update run_pretrain_trainer.py

---------

Co-authored-by: yujun <573009727@qq.com>
2024-03-08 16:41:40 +08:00
Ruibiao Chen
b504a7370c Support hybrid_parallel_topo_order for auto parallel Llama (#8011)
* Support hybrid_parallel_topo_order for auto parallel Llama

* Set order in hybrid_configs

* Update get_mesh_with_dim

* Update loss for CI baseline

* Fix CI errors

* Update loss

* Update loss

* Update loss

* Update loss

* Update loss
2024-03-08 11:48:18 +08:00
cyber-pioneer
93aa4bc9ca fit cinn and pir flag in predictor (#8071) 2024-03-07 17:07:11 +08:00
Siming Dai
e34cbe98e3 [Unified Checkpoint] Fix lora unittest (#8070) 2024-03-07 16:14:29 +08:00
liuzhenhai93
dd8a46c81d unify_criterion_inputs_dynamic_and_static (#8053)
* unify_criterion_inputs_dynamic_and_static

* polish

---------

Co-authored-by: liuzhenhai93 <liuzhenhai@baidu.com>
2024-03-07 10:54:28 +08:00
Liujie0926
972542b19b fix ci scripts (#8063) 2024-03-07 10:06:00 +08:00
zhang junjun
fb0ddb5252 Revert "Fit pir flag in predictor (#8048)" (#8065)
This reverts commit 5df6e7d1d4.
2024-03-06 20:58:19 +08:00
lugimzzz
67f31c6e55 update pp (#8059)
* update pp

* Update paddlenlp/transformers/model_utils.py

Co-authored-by: Zhong Hui <zhonghui.net@gmail.com>

---------

Co-authored-by: Zhong Hui <zhonghui.net@gmail.com>
2024-03-06 19:26:06 +08:00
cyber-pioneer
5df6e7d1d4 Fit pir flag in predictor (#8048)
* locate llama2 while

* fit pir flag

* fix code

* add cinn flag
2024-03-06 16:01:03 +08:00
greycooker
32d8b3f4a0 [BugFix] Fix Test wandb callback bug (#8056) 2024-03-06 13:17:11 +08:00
Yiqun Liu
092c84502c Optimize the log and enable to print the number of tokens each second. (#7853)
* Optimize the log and enable to print the number of tokens each second.

* Update the prompt message of logging.

* Add is_pretraining to switch whether calcaulating and printing in tokens.

* Add the interval_samples_per_second back.
2024-03-06 10:39:06 +08:00
Ruibiao Chen
e3cb5d239b Fit sharding optimization for auto parallel llama (#8021)
* Fit sharding optimization for auto parallel llama

* Add args enable_allreduce_avg_in_gradinent_scale

* Fix CI errors
2024-03-05 14:17:42 +08:00
wawltor
4b1c54b559 fix the index_dataset with old data format (#8049) 2024-03-04 19:38:59 +08:00
lzydev
17cc16964e 【AutoParallelism】fix dataloader bug and add ci for static (#8014)
* fix dataloader bug and add ci for static

* change dy2st ci

* disable fused_rms_norm

* disable pir-executor

* add loss on V100

* polish

* polish

* delete dy2st ci

* delete dy2st ci
2024-03-04 14:19:45 +08:00
co63oc
77a23d1275 Fix _cache_founf_inf (#7997)
* Fix

* Fix

* Fix
2024-03-04 10:36:02 +08:00
Ruibiao Chen
a5749005bc Add SwiGLU for auto Llama (#8038) 2024-03-02 18:36:59 +08:00
zhang junjun
b7bfb262a4 [CI] fix test ptuning (#8040) 2024-03-01 15:32:02 +08:00
Siming Dai
462ebaa9b3 [Mixtral] Add mixtral moe (#7803)
* Add mixtral moe

* fix mixtral moe

* add mixtral lora config

* fix load balancing loss

* add sft scripts

* add unittest
2024-03-01 14:13:00 +08:00
wawltor
0d564905dd support the loss mask for the pretrain (#8034) 2024-03-01 13:05:14 +08:00
lzydev
dff7dcc4ff init model using float32 (#8033) 2024-03-01 10:42:33 +08:00
DrownFish19
b72f35256c [DATA] Remove repeated chars during preprocessing (#7739)
* add remove_repeated_chars

* update max_repeated_len
2024-02-29 12:42:12 +08:00
Siming Dai
6f45e95cc4 [Unified Checkpoint] Support peft model (#7691)
* fix qwen merge tp concat

* support peft unified checkpoint

* add prefix numpy save

* add single node peft

* fix peft distributed load

* add single node optimizer load

* support peft tensor parallel for unified checkpoint

* add prefix from_pretrained from safetensors

* add lora and prefix safetensor name

* fix typo

* fix params that is not enough to save per worker

* fix lora pp tp split

* add peft uc tests

* fix master_weight is None

* add ptuning uc tests

* fix tensor copy blocking

* unify lora and ptuning

* fix load_best_model

* fix index json name

* remove ptuning unittest
2024-02-29 11:02:24 +08:00
Difer
37e85e695d add autotuner buffer check ce case (#7993)
* add autotuner buffer check ce case

* fix some errors

* fix some errors

* fix some typo error
2024-02-28 14:34:58 +08:00
SebastjanPrachovskij
5bab940a22 Add SearchApi integration (#7936) 2024-02-28 11:21:08 +08:00
Siming Dai
db490623ae [DOC] Add unified_checkpoint doc (#7961) 2024-02-26 14:43:24 +08:00
Liujie0926
28b9eb84c1 [AutoConfig]add N2C16 (#7915)
* add N2C16

* fix

* update N2C16_gbs to 16

* fix env

* fix

* fix

* update

* fix env set

* fix

* fix bug

* update
2024-02-26 14:11:39 +08:00
Difer
e8d6233c5c [AutoConfig]add N1C8_resume (#7950)
* add N1C8_resume

* fix some errors
2024-02-26 10:17:17 +08:00
Zhang Ting
6a6a9fe8d6 support GQA (#7906)
* fa and fuse rope support gqa/mqa

* add tests for llama with GQA

* rename test

* add test

* remove test

* remove comments

* fix dtype
2024-02-23 10:29:23 +08:00
yujun
9931d65cd1 fix (#7992) 2024-02-22 15:54:54 +08:00
yujun
2edcd08622 [Trainer] ignore_save_lr_and_optim (#7978)
* ignore_save_lr_and_optim

* 只对finetune的测试开启ignore_save_lr_and_optim
2024-02-22 11:36:59 +08:00
lzydev
b2be2fc191 【AutoParallel】Add semi autoparallel amp (#7985)
* add semi-autoparallel amp

* support amp in semi-auto

* change loss base

* polish
2024-02-21 16:05:04 +08:00
Haohongxiang
5c9c8d3cb4 [model_zoo/gpt-3] Fix bugs from PR-61236 which cleared paddle.jit.dy2static.utils_helper (#7989)
* fix bugs

* add try import to support develop and release
2024-02-20 20:30:11 +08:00
sneaxiy
4eb6f0a4dc add swiglu operator (#7967) 2024-02-20 17:50:25 +08:00
Siming Dai
7e643ada4c fix multi-node same output json written (#7977) 2024-02-19 11:41:14 +08:00
NINGBENZHE
394a3e2898 add npu fused and fix AICPU (#7976) 2024-02-07 11:10:09 +08:00
w5688414
7b9cb9bc9e Update text matching (#7973) 2024-02-06 14:37:40 +08:00
Siming Dai
b312959a77 [Unified checkpoint] Turn off unified checkpoint when using sharding stage3 (#7969)
* turn of uc when sharding stage3

* fix
2024-02-06 11:26:45 +08:00
Zhong Hui
a33ab3781f skip some trainer test. (#7949) 2024-02-05 18:05:11 +08:00
Leo Chen
8d6e81339a rename files and add readme for llama auto_parallel (#7944)
* rename files and add readme for llama auto_parallel

* rename files and add readme for llama auto_parallel

* fix ci
2024-02-01 13:10:41 +08:00
Yuang Liu
c0c64fa1e5 gqa fuse attention qkv (#7890)
* gqa fuse attention qkv

* add annotation for the fusion
2024-02-01 11:50:02 +08:00
Haohongxiang
3a704ea0bc [Auto Parallel] Support semi-auto trainer and fit Llama2 training (#7885)
* support semi-auto trainer and fit Llama2 training

* support shard_dataloader in dynamic semi-auto

* rewrite traning loop

* refactor traning loop

* refine args of auto trainer

* broadcast loss

* add auto ci cases
2024-01-31 18:51:57 +08:00
Kunbo Ding
44bfeb01f8 fix timer device (#7939)
fix timer device
2024-01-31 16:13:34 +08:00
greycooker
0d6fc1ecbf Trainer add wandb and tensorboard (#7863) 2024-01-31 15:01:09 +08:00
Kunbo Ding
6e0ac44080 RuntimeTimer for the toolkit (#7913)
* RuntimeTimer for the toolekit

* RuntimeTimer for the toolekit

* reformat

* fix timer and load checkpoints

* remove reset
2024-01-29 22:16:02 +08:00
Kunbo Ding
9a31322910 [Improvement] fix logger level (#7903)
* fix logger level

* fix training args logger level
2024-01-29 20:44:32 +08:00
Liujie0926
5951179b32 [CE]add gpt sharding_v2 case (#7914)
* add sharding_v2 case

* update run_mode to device_num

* fix

* fix
2024-01-29 16:33:51 +08:00
Zhong Hui
a86de1b546 trainer refactor (#7909) 2024-01-29 14:35:41 +08:00
Ting Liu
2a5e5a624b add qwen benchmark (#7758)
* add qwen benchmark

* update qwen benchmark scripts

* qwen 7b benchmark

* arg change

* fix wrong args

* fix args

* update
2024-01-29 11:05:58 +08:00
Zhong Hui
688adb81e3 [RELEASE] Update README.md (#7834) 2024-01-26 15:57:38 +08:00
Liujie0926
879a853d25 [AutoConfig]add benchmark scripts (#7897)
* add auto_tuner

* fix

* update log_file

* update json

* close eval/predict

* fix run_mode

* update

* fix

* Revert "fix"

This reverts commit e526c8680b.

* Revert "update"

This reverts commit 9cbd773e9b.

* update prepare

* Revert "Revert "update""

This reverts commit 811b6a4ff4.

* Revert "Revert "fix""

This reverts commit 32cc005265.

* update finetune prepare

* update

* add

* update sft/lora steps

* update json

* update

* add benchmark

* update years

* update a100
2024-01-26 15:42:59 +08:00
Tian
95c0dd4593 [LLM] fix llama precision on custom devices (#7895) 2024-01-26 15:34:53 +08:00
Tian
1f82403063 [CustomDevice] fix loading rng state on custom device (#7894) 2024-01-26 15:34:00 +08:00
Ernestina
cdfa8614ac [Hackathon 5th No.73] ToT (#7660)
* Hackathon TASK73 ToT

1. finish meta/llama2 version

* update readme tutorial

* modify according to Lint

* modify according Link

1. resolve one unused variable

* Delete LICENSE

* Update LICENSE

* black format

* isort format

* Update search_crosswords-dfs.ipynb

* update files formats

* Update LICENSE

* Update LICENSE

* Update LICENSE

* Update LICENSE

* delete test data

* delete some unnecessary files

1. delete some unnecessary files according to comments.

* add paddlenlp-llama2

1. add llama2 in paddlenlp

* fix one bug

* fix outputs bug

1. format data structure

* delete meta/llama2

* modify according to comments

1. add acknow into readme
2.change png into url in readme
3. add all the models supported by paddlenlp

* change according to comments

* Delete .gitignore

* Create .gitignore

* Move directory

* Add tree of thoughts scripts

* add first dir

* add note

* Update README.md

add test results of facebook/llama-2-7b-chat and llama-2-13b-chat

* Update requirements.txt

delete unnecessary packages

* Update demo.py

add Ernie

* Update .gitignore

delete pyproject.toml

* Update run.py

add Ernie

* Update __init__.py

add Ernie

* chat templates

* add Ernie

* Update llama.py

兼容Ernie

* Update bfs.py

兼容Ernie

* Update models.py

兼容Ernie

* Update run.py

* format style

* format style

* format style

* format style

* format style

* format style

* format style

* format style

* 删掉重复的“测试结果”

* 删除Ernie的token,设置环境变量解决

* format style

* format style

* 删除注释掉的代码

---------

Co-authored-by: root <root@tutu-win.localdomain>
2024-01-26 15:00:34 +08:00
Zii
3a42280eeb [CE] Add Qwen into CE process (#7887)
* add qwen & baichuan into CE

* add Qwen & Baichuan into CE, cleaned for PR

* add only Qwen into CE, cleaned for PR

* dd only Qwen into CE, open switch_ir_optim, cleaned for PR

* add only Qwen into CE, keep switch_ir_optim open, add ce script
2024-01-26 14:24:21 +08:00
Ruibin Cheung
13fd6555e8 [Bug Fix] fix allreduce tensor dtype (#7876)
* [Bug Fix] fix allreduce tensor dtype

Reason: some CCL not support bool dtype

* update int8 to int32
2024-01-25 10:59:22 +08:00
lzydev
ca7944418e support bf16 loss in static (#7874) 2024-01-24 20:37:31 +08:00
Lu Qi
eafa066020 update (#7882) 2024-01-24 13:00:27 +08:00
lzydev
b456110689 【AutoParallel】Support 'master_grad' in Llama in static auto-parallelism (#7658)
* add master_grad

* add llama_fp16_test

* polish

* merge develop
2024-01-24 11:13:48 +08:00
骑马小猫
b50db1ce70 [Bug Fixes] update chatglm1 tokenizer (#7870)
* update chatglm1 tokenizer

* update additional_special_token

* add is_training tag

* fix linting
2024-01-23 23:23:12 +08:00
Wu Chencan
2a8d1380fa [LLM]support QWenVL second part (#7808)
* add qwenvl second part

* improve code & add comments

* add qwenvl test

* update qwenvl tests

* remove print
2024-01-23 11:04:25 +08:00
RichardWooSJTU
4a9c76655e revert benchmark codes (#7871) 2024-01-22 20:50:55 +08:00
wawltor
2ac42ca498 Update ppo_main.py (#7881) 2024-01-22 20:03:59 +08:00
wawltor
7a5fbe7a5b Update reward_main.py (#7880) 2024-01-22 20:02:52 +08:00
Guo Sheng
d4de12c763 Add PPO training. (#7305)
* Add reward model and training.

* Make reward training runable

* Add eval in reward training.

* For result alignment.

* training setting.

* PPO alignment with Beaver

* Align training with Beaver.

* Clean ppo_trainer.py and debug print.

* Move score models from paddlenlp to example and add AutoModelForScore.

* Remove eval.py, eval_score.py.
Fix AutoModelForScore and update reward training usage.

* Update ppo_trainer.py after merge with develop.

* Make PPOTrainer support reference/reward Trainer optionally.

* Complete README.

* Add unittest test_load_from_custom_arch for AutoConfig

* Add test_synced_gpus.py for generation.

* Add more test cases in test_synced_gpus.py

* Support tensor parallel.

* Add require_gpu to test_synced_gpus.py.
2024-01-22 19:20:28 +08:00
Zhong Hui
e3fc63a250 cherry pick empty cache. (#7868) 2024-01-22 16:25:57 +08:00
yinwei
fcb532a43a [CE] Add CE for Hybrid Parallism (#7817) 2024-01-22 15:04:32 +08:00
骑马小猫
082dc52f20 [Improvement] fix ops improting in utils (#7865)
* fix ops improting in utils

* update the reset_stop_value importing

* update the error msg of import paddlenlp_ops

* rename error -> warning
2024-01-22 13:29:35 +08:00
greycooker
283c535a50 fix_trainer_argparser (#7860) 2024-01-22 12:24:54 +08:00
zhang junjun
c1ccafaca8 [CI] add ci approval pipelines (#7859)
* [CI] add ci approval pipelines

* update

* update

* update
2024-01-19 15:06:14 +08:00
Haohongxiang
16d3c49d2b [Auto Parallel] Support dynamic semi-auto training in Llama2 model (#7851)
* update

* add ci

---------

Co-authored-by: liuzhenhai93 <liuzhenhai93@outlook.com>
2024-01-18 16:31:59 +08:00
骑马小猫
915fa43712 [New Features]add ranks testing for test_predictor (#7800)
* add ranks testing

* update gpus testing
2024-01-18 15:33:11 +08:00
DrownFish19
48c1313da9 [unified checkpoint] fix checkpoint names (#7795)
* fix(unified checkpoint): add config save

* fix(unified checkpoint): name change

change master weigths name to model weigths name when SKIP_SAVE_MODEL_WEIGHT

* fix(unified checkpoint): model weights load

when skipping model weighs save and saving master weights as model weights, unified checkpoint needs choose the model weights to load into master weights.

* test(unified checkpoint): add test cases

To test file list and file name when skip_save_model_weight=1

* test(unified checkpoint): add enable_all_options

* fix(unified checkpoint): fix last ckpt save

* fix(unified checkpoint): unified config format
2024-01-17 17:17:26 +08:00
DrownFish19
5a01362b4a [unified checkpoint] Fix last checkpoint save (#7854)
* fix(unified checkpoint): fix last ckpt save

* fix(unified checkpoint): unified config format
2024-01-17 17:16:05 +08:00
周周周
cf907fc683 Support 5.2 bloom (#7846)
* initial commit

* remove debug code

* remove debug code

* modify predictor.py

* remove print

* remove rope_emb in bloom

* format

* add test
2024-01-17 10:33:10 +08:00
Zii
e4bd6c344e [LLM] fix Qwen-7b-Chat precision issue (#7823)
fix qwen-7b0chat model batch inference precision issue
add Qwen-7B-Chat to PaddleNLP unit test
2024-01-16 17:49:23 +08:00
ZeyuTeng96
c9d22dba87 [text_classification_retrieval_based] fix bug of evaluate.py (#7844) 2024-01-16 12:17:27 +08:00
ZeyuTeng96
04142e3ca8 [faq] fix bug of evaluate.py (#7840) 2024-01-12 23:07:46 +08:00
ZeyuTeng96
2a5dba9591 [semantic_indexing] fix bug of evaluate.py (#7843) 2024-01-12 23:06:47 +08:00
骑马小猫
b44f88857e [Bug fixes] update chatglm tokenizer (#7797)
* update chatglm tokenizer

* update chatglm2 tokenizer

* update chatglm2 tokenizer

* update max & src slider

* add chatglm2 tokenizer
2024-01-12 21:51:39 +08:00
Shenghe Wang
8bc06b0ce8 fix the bug of reading files (#7836) 2024-01-12 16:21:19 +08:00
ZeyuTeng96
a1d1aee6ff [neural search][fix bug of evaluate.py] (#7832)
* [fix][fix bug of evaluate.py]

* Update evaluate.py

* Update evaluate.py
2024-01-11 17:16:25 +08:00
Siming Dai
ee4b9dde93 [Pretrain] Fix eval during pretrain (#7827)
* add unified checkpoint training args doc

* fix eval during pretrain

* fix
2024-01-11 17:11:55 +08:00
liuzhenhai93
f039d097d3 fused rms spmd (#7830) 2024-01-11 16:44:22 +08:00
lugimzzz
4069f22c01 fix lora (#7824) 2024-01-11 11:06:22 +08:00
Ruibin Cheung
abb0d3c91f [Bug Fix] fix paddle multipy_fwd_func warning message (#7818) 2024-01-11 10:51:45 +08:00
RichardWooSJTU
c5d8d5bb2d [LLM] Support block_attention/cachekv quant for llama (#7649)
* support blha and cache kv quant

* lint

* fix unit test

* fix infer when blha is on

* code refine

* add docs and fix ops

* merge blha read res in predictor

* finish docs

* add docs and unittest

* add unittest

* migrate read res
2024-01-10 22:23:38 +08:00
greycooker
5a32534df2 Trainer support simultaneously parse JSON files and cmd arguments. (#7768)
* add parse_json_file_and_cmd_lines

* change unit test file path

* Change the way the JSON file is determined

* Merge parameter parsing judgment branches and add comments.

* remove the special handling of output_dir

* Add remaining_args warning
2024-01-10 15:15:48 +08:00
lugimzzz
5c2bf81130 [llm]support qlora pp (#7801)
* supprt qlora pp

* fix scale dtype
2024-01-10 11:48:17 +08:00
Yuanle Liu
75e898146a delete useless code for write_cache_kv.cu (#7812) 2024-01-10 10:43:37 +08:00
骑马小猫
3056226df1 fix br gradio (#7788) 2024-01-09 20:45:41 +08:00
Zhang Ting
d51edd0c1b pipeline parallel benchmark (#7759)
* pipeline parallel benchmark

* add seed setting

* fixed
2024-01-09 20:16:53 +08:00
Siming Dai
dab175b58b [Pretrain] Fix eval during pretrain (#7806)
* fix eval during pretrain
2024-01-09 15:56:38 +08:00
tianhaodongbd
fc6ab70e8e [CE] Add MP2-SP2-pp4-vpp2-SD2-stage1-mbs2-acc8 ce (#7774) 2024-01-09 15:08:18 +08:00
yinwei
393ac18789 [CE] Add CE for Distributed Hybrid Parallel (#7782) 2024-01-09 14:07:55 +08:00
Wu Chencan
37b4fe0285 [INFER][LLM] Support qwen in fined grained dybatch v1 (#7644)
* init qwen inference model

* fix name

* fix hidden dim

* fix dtype

* fix length

* fix attention_mask

* fix up & gate dtype bug

* fix ffn1 weight

* modify codes

* remote unused variable

* remove unused code

* add qwen weight only

* format with black

* format with isort

* fix dtype

* add qwen inference model in static graph

* add qwen unittest

* format with black

* print log

* remove print

* set safetensors usage False

* remove tests

* Empty-Commit
2024-01-09 11:16:52 +08:00
yujun
97f6158e76 slow (#7798) 2024-01-08 18:38:02 +08:00
DrownFish19
487428b399 Fix shared weights sync for PipelineLayer (#7772)
* fix shared weights sync

* fix typo
2024-01-08 15:59:12 +08:00
qingzhong1
ff1e91088a [Paddle-Pipelines] update faiss (#7793)
* update faiss

* update faiss

* update faiss
2024-01-08 15:48:09 +08:00
lugimzzz
079f0674b6 fix (#7781) 2024-01-08 11:45:02 +08:00
w5688414
17acf221b4 Update convert_files_to_dicts_splitter (#7748) 2024-01-05 17:26:13 +08:00
Siming Dai
4437198aa8 fix dist dataloader eval (#7777) 2024-01-04 22:16:41 +08:00
yujun
f93e7da733 [DONE] aistudio, hf hub, bos update download (#7608)
* try fix

* fix hf download bug ...

* update config download bug

* fix

* add subfolder

* update

* 优先级,先本地,再builtin,再aistudio,再hf hub,再bos

* 更新chattemplate文件检索路径

* update

* fix subfolder && add tests

* fix

* update

* fix tokenizer_config_file_dir_list

* subfolder test

* fix from_pretrained() load hf sharded model

* 更新逻辑

* update use_safetensors

* update

* fix resolve_weight_file_from_hf_hub

* 更新bos旧的下载方式

* update download from hf hubgit add .

* update logging

* update

* 关闭代理

* update

* update

* fix image process

---------

Co-authored-by: CrazyBoyM <ai-lab@foxmail.com>
Co-authored-by: Ke Bai <35400185+CrazyBoyM@users.noreply.github.com>
2024-01-04 20:00:22 +08:00
DrownFish19
7d789a8194 Fix unified_checkpoint bug (#7770)
* fix use_unified_checkpoint defined

* add n1c2 test into ci_case.sh

* move test_unified_checkpoint to tests

* add tests/trainer into testpaths

* remove unifiedcheckpoint case from ci_case.sh
2024-01-04 19:42:05 +08:00
骑马小猫
04dc6251fb [New Features] support dynamic src_length (#7740)
* support dynamic src_length

* revert max_position_embedding

* update doc

* update flask_server

* update max_length control

* update request flask_server

* fix max-position-embeddings

* update error message

* update predictor length init
2024-01-04 17:21:02 +08:00
JZ-LIANG
70c92e5c4e [AutoParallel] Add Sequence Parallel for Static LLaMA (#7746)
* sp for static llama

* sp for static llama1

* code style

* change script
2024-01-04 17:05:37 +08:00
Zhong Hui
5c7efcc3d2 [Release] Update release.yml to release tags (#7765)
* Update release.yml to release tags

* Update release.yml

* Update release.yml
2024-01-04 12:27:39 +08:00
Liujie0926
895a81635b [benchmark]close skip_memory_metrics for ips (#7732)
* update mem from B to MB

* fix ft

* fix pretrain

* Revert "update mem from B to MB"

This reverts commit 044a88c49a.
2024-01-03 19:38:11 +08:00
Zhong Hui
f7207940b3 Change version to 2.7.0 (#7764) 2024-01-03 12:02:53 +08:00
Zhong Hui
34b381ecd0 [DOC] Update trainer.md (#7761)
* Update trainer.md

---------

Co-authored-by: DrownFish19 <DrownFish19@gmail.com>
2024-01-02 21:12:01 +08:00
Zhong Hui
0a23bbbbb1 [CE] Delete gpt for sequence classification (#7757) 2024-01-02 19:55:23 +08:00
zhang junjun
a2e5cf5693 Add codecov check (#7760)
* [CI] set codecov status check

* update

* [CI] adjust codeocov target
2024-01-02 19:41:10 +08:00
zhaoyingli
38f792e0d9 [AutoParallel] Auto Trans PP to VPP (#7747)
* [AutoParallel] Auto Trans PP to VPP

* update pp scheduler config

* add comment
2024-01-02 17:52:33 +08:00
Siming Dai
5f5cb52e1b Add unified checkpoint training args doc (#7756) 2024-01-02 17:24:39 +08:00
lugimzzz
a6968b7692 [llm]support lora merge (#7733)
* support lora merge

* add finetune

* support bf16 and lora merge

* update

* add lora merge

* version adatpt

* update

* fix

---------

Co-authored-by: root <root@bddwd-inf-k8s-a100-a12ni6-0399.bddwd.baidu.com>
2024-01-02 16:15:41 +08:00
骑马小猫
1982091ba8 [Improvement] support system prompt in training dataset (#7667)
* update system prompt

* support system prompt

* add context system prompt docs

* update chat-template readme
2024-01-02 14:54:52 +08:00
Siming Dai
6ddb4b1ae4 [Pretrain] Fix llama max_seq_len settings # (#7745) 2024-01-02 14:51:32 +08:00
WAI-clear
48bee12c49 [BugFix] Fix qwen matrix alignment (#7473) 2024-01-02 11:35:01 +08:00
w5688414
fb8f2bec6a [bloom] Add kv cache support for flash attention & fix bugs (#7735)
* Add kv cache support for flash attention

* Update chatglm flash attention version check

* Add test for flash attention

* Fix unitest bug

* Add flash attention to predictor

* Add flash attention2

* Add flash attention unitests

* fix prefix decoder

* remove unused comments

* Update unitest

* Update unitest
2023-12-29 20:27:47 +08:00
liuzhenhai93
fda20a7e97 sharding reshard 兼容老版本 (#7734)
* polish

* polish

---------

Co-authored-by: liuzhenhai93 <liuzhenhai@baidu.com>
2023-12-29 16:39:12 +08:00
qingzhong1
6e9d46571a update processing (#7743)
* update processing

* modify pdf

* modify pdf

* modify pdf

* modify pdf

* update pdf
2023-12-29 14:51:06 +08:00
Chang Xu
b055be6f62 Support AWQ & GroupWiseQuant for LLMs (#7688)
* Support AWQ & GroupWiseQuant for LLMs

* add docs

* add docs

* upadte
2023-12-29 11:54:00 +08:00
啊biu
a55039cc16 Update Install_windows.md (#7707) 2023-12-28 22:35:13 +08:00
啊biu
d5c807b724 Update semantic_search.yaml (#7708) 2023-12-28 22:34:24 +08:00
sneaxiy
5de7e57211 Add mp delay_scale_loss function (#7713)
* add mp delay_scale_loss function

* remove useless codes
2023-12-28 20:29:47 +08:00
DrownFish19
1e9b5a876a [unified checkpoint] Update unified checkpoint (#7730)
* replace with unwrap_optimizer

* remove dist.barrier(group=tp_group) for distributed_gather

* add warning when loading model weights as master weights

* update paddle.cast

* Revert "replace with unwrap_optimizer"

This reverts commit 3fd6a58954.

* add unwrap_optimizer

* convert is_unified_checkpoint to is_unified_checkpoint

* update
2023-12-28 13:06:37 +08:00
qingzhong1
d1e51e2f40 modify pdf (#7738) 2023-12-28 11:47:19 +08:00
yujun
dca0575ef4 update fasttokenizer readme (#7684) 2023-12-27 20:58:43 +08:00
qingzhong1
29a94d397a [Paddle-pipelines] update pdf (#7737)
* update pdf

* update pdf

* update pdf

* update pdf

* update pdf

* update pdf
2023-12-27 20:00:57 +08:00
周周周
57504e7118 去掉内部关于tgt_attention_mask的一些修改 (#7696)
* commit

* 删掉一些东西
2023-12-27 13:20:20 +08:00
Zhong Hui
228bd14dc0 fix lr. (#7729) 2023-12-26 20:50:06 +08:00
DrownFish19
4f15ac0719 [Unified Checkpoint] Add unified checkpoint config (#7574) 2023-12-26 19:44:39 +08:00
骑马小猫
b3961f26db [Bug fixes] update input_spec for forward (#7648)
* update input_spec for forward

* update opt casting
2023-12-26 17:59:04 +08:00
Haohongxiang
942865f52b [Trainer] Support release gradients for develop branch (#7594)
* support release gradients for develop branch
2023-12-26 16:14:21 +08:00
pangengzheng
b541fc2563 Fix sep compatible (#7721)
* run 4096

* fix get sep attr if paddle do not support sep

* polish

---------

Co-authored-by: pangengzheng <pangengzheng.baidu.com>
2023-12-26 13:22:03 +08:00
骑马小猫
96d12d459e [Improvement]support base-port & flask-port (#7668)
* support base-port & flask-port

* update flask_port
2023-12-26 12:14:49 +08:00
骑马小猫
e5eefa7753 use singlthread to do prediction (#7720) 2023-12-26 11:40:50 +08:00
zhouzj
7640804279 fix lora from pretrained. (#7714)
* fix lora from pretrained.

* updates.

* fix comments.

* fix comments.
2023-12-26 11:11:42 +08:00
Zhong Hui
d97016ec84 [BugFix] Fix gpt (#7716) 2023-12-26 10:51:07 +08:00
Haohongxiang
79d1d5b42d [BugFix] Fix seed bugs (#7715) 2023-12-26 10:50:38 +08:00
xiaoxiaohehe001
28158b9735 fix_wint (#7692) 2023-12-25 20:53:38 +08:00
zhaoyingli
9b6138af24 remove chunkid annotation (#7703) 2023-12-25 19:06:33 +08:00
Zhong Hui
fe3485f58b delete model zoo gpt2. (#7702) 2023-12-25 17:48:39 +08:00
yujun
ebd6964c50 [BUG Fix] update IntervalStrategy, update lora conv2d init, update logger.warning (#7705)
* 强制关闭

* 更新初始化.

* update warn -> warning
2023-12-25 13:50:36 +08:00
yujun
d6e71605a2 [LLM PDC] merge some llm pdc code into develop (#7694)
* 自定义cuda kernel支持更多arch

* llm gradio添加subtile

* 更新trainer_callback

* 确保模型文件顺利保存,使用checkpoint_done进行判断

* 添加FLAG_LLM_PDC环境变量,兼容task_name_or_path和intokens参数

* 修改finetune pretrain文件

* update

* update

* update
2023-12-22 11:56:31 +08:00
yinwei
838c7ed938 [CE] Fix ce bug (#7686) 2023-12-22 11:13:42 +08:00
zhaoyingli
68abb819e2 mv refined recompute to run_pretrain_auto (#7701) 2023-12-22 10:41:28 +08:00
Zhong Hui
2da0237e5e [PreTraining] Unify pretraining scripts (#7700) 2023-12-21 20:49:49 +08:00
Ting Liu
f584cdb159 Support torch safetensors load (#7690)
* support torch safetensors load
* fix dtype bug
2023-12-21 19:03:11 +08:00
zxcd
0577cd298f fix dtype (#7697) 2023-12-21 16:13:59 +08:00
Zhong Hui
3ef9c78d10 [DOC] Add pretraining docs and report pretrain performance. (#7437) 2023-12-21 15:47:02 +08:00
liuzhenhai93
c9586cc28e Pp reshard develop (#7629)
* polish

* tested

* polish

* polish

* polish

* follow_comment

---------

Co-authored-by: liuzhenhai93 <liuzhenhai@baidu.com>
2023-12-21 10:24:12 +08:00
co63oc
b02c7162a1 Fix typos (#7687) 2023-12-20 20:37:35 +08:00
MayYouBeProsperous
47c9185fe1 fix bugs (#7673) 2023-12-20 19:49:42 +08:00
Liujie0926
d4b0e4d869 [CI]update for llm_gpt (#7631)
* fix

* update for llm_gpt

* fix

* fix

* fix

* fix

* fix

* fix

* update case

* fix

* update base

* add Flag

* update loss base

* fix cache
2023-12-20 16:26:03 +08:00
yujun
f54f272675 PEFT lora support Conv2D (#7680) 2023-12-20 11:55:29 +08:00
zhang junjun
0f437bd07c [CI] set codecov status check (#7647)
* [CI] set codecov status check

* update
2023-12-19 20:27:51 +08:00
pangengzheng
99e2dd1e71 Support sep (#6994)
* run 4096

* support sequence segment parallel

* polish

* format

* format

* format

* inplace reshape

* format

* run llama with sep

* llama sep

* run sh

* llama converge

* llama align first loss between dp and sep

* support non fuse_qkv and non flash attn to use sep, all align first loss with dp

* support rope emb

* align the first loss of dp and sep for modelzoo gpt3

* sep support local_seed for dropout

* support tp(with sequence parallel) and sep hybrid parallel

* run seq_len scalable test

* do not build attention mask in advance when use flash attention

* polish run

* run benchmark

* test gpt1.3B performance

* clean codes

* run gpt and llama

* code style

* add unittest

* enable test when gpu_num>1

* code style

* fix sep test

* fix test

* code style

* polish

* fix

* polish test

* check tp and sp

* run script

* check compatible

* rename

* fix test

* polish

* fix bug

* rename

---------

Co-authored-by: pangengzheng <pangengzheng.baidu.com>
2023-12-19 20:02:32 +08:00
tianhaodongbd
1fcde9d5ae [CE] Add ce sharding stage3 and ce mp sharding stage1 (#7639) 2023-12-19 16:23:01 +08:00
骑马小猫
9715b6af0d fix tokenizer decode-tokens (#7681) 2023-12-19 16:21:56 +08:00
Ting Liu
445638a4ab llm doc update (#7478)
* llm doc update

* pic update

* doc update

* update pic

* doc update

* requirement update

* doc update

* update

* update

* update

* update

* update

* update

* update

* add zero padding

* update

* update

---------

Co-authored-by: lugimzzz <zhenglujing@baidu.com>
2023-12-19 15:13:48 +08:00
lugimzzz
805350b5f6 [llm]Qlora fix (#7645)
* bug fix

* fix

* fix
2023-12-19 13:16:50 +08:00
Haohongxiang
e78007e2c4 [Llama2] Fix setting seeds of distributed training for Llama model with Auto Parallel (#7643)
* fix seeds of auto llama

* update loss of ci cases
2023-12-19 11:42:13 +08:00
yinwei
1757c5d52d [BugFix] Add CE for mp2-sp2-pp2-dp2 (#7678) 2023-12-19 11:33:25 +08:00
zhink
6299680263 fix cache kv len (#7679) 2023-12-19 10:31:43 +08:00
MayYouBeProsperous
dba73aa484 【Hackathon 5th No.64】PaddleNLP套件模型接入动转静训练功能 (#7576)
* fix

* add to_static for Trainer

* fix

* codestyle
2023-12-18 19:18:22 +08:00
MayYouBeProsperous
4c94b94c74 add --to_static (#7656) 2023-12-18 18:58:07 +08:00
xysheng-baidu
5c7d7b1c6a add ce_mp8 model (#7665) 2023-12-18 17:11:06 +08:00
Ruibiao Chen
5e69cfc1d4 Improve flash-attn mask calculation for auto llama (#7670) 2023-12-18 15:40:43 +08:00
Siming Dai
3c8e0b42bb [BugFix] Fix qwen merge tp concat (#7675) 2023-12-18 12:51:19 +08:00
yinwei
0568d98b22 [CE] Add ce for mp2-pp2-sp2-dp2 (#7664) 2023-12-15 16:43:18 +08:00
yinwei
e221595791 [CE] Add CE test for stage2 (#7544) 2023-12-15 15:43:01 +08:00
Sonder
5106809e5d [AutoParallel] add pipeline.auto_parallel_profiler to auto_config (#7343)
* update

* update

* Fix init weight for llama modeling auto

* update

* add support for Llama2

* recover codes

* remove training_args

* fix

* remove test config

* use guard

* change var name

* add import

* fix import error

* fix import error in run_pretrain_auto.py

---------

Co-authored-by: chenruibiao <chenruibiao@baidu.com>
2023-12-15 13:53:16 +08:00
zxcd
b90cf05930 fix dtype (#7619) 2023-12-14 15:36:33 +08:00
niuliling123
45afa73a5f update for seed (#7653)
* update for seed

* update
2023-12-14 14:13:03 +08:00
niuliling123
6235b8994a [Trainer] Update for seed (#7651) 2023-12-14 12:42:34 +08:00
zhaoyingli
a73a7bf15c [AutoParallel] add resume_from_checkpoint and vpp for llama (#7601)
* [AutoParallel] add resume_from_checkpoint and vpp for llama

* add clip

* polish modeling_auto.py

* polish code

* tiny fix

* add vpp ci for llama

* fix ci script

* update loss_base
2023-12-13 17:09:33 +08:00
骑马小猫
1bfe864587 disable chat-template in tipc (#7633) 2023-12-13 16:59:30 +08:00
zhang junjun
83acdd365c [CI] add coverage status checks (#7635)
* [CI] add coverage status checks

* update

* update

* update

* update

* fix
2023-12-13 14:36:08 +08:00
骑马小猫
d5a9dda0e8 fix chatglm2 training for chat-template (#7637) 2023-12-13 14:03:39 +08:00
DrownFish19
b51de6d774 [GPT] Support SharedLayer with different prefixes for pipeline parallel (#7598) 2023-12-12 20:52:11 +08:00
DrownFish19
24b6d70204 [FG] Fix fast generation (#7630)
* fix paddle header file path

* fix paddle header file path
2023-12-12 19:52:44 +08:00
niuliling123
9bff2a029b [Trainer] Remove args in set_seed function (#7592) 2023-12-12 19:42:45 +08:00
ShenLiang
e5175a7af5 [BugFix]Add local seed for gpt in flash_attn (#7626)
* add local seed for gpt

* add local seed for gpt

* add local seed

* fix bug seed in embedding
2023-12-12 17:58:34 +08:00
Haohongxiang
a4ed7ac6f5 fix grads acc in llama auto (#7625) 2023-12-12 10:53:15 +08:00
yinwei
0a58a1a5f8 [GPT] Bug Fix, to fix pp sp layernorm grad sync (#7613) 2023-12-12 10:50:47 +08:00
Siming Dai
ac7114f331 [Unified Checkpoint] Add dynamic load unified checkpoint (#7487)
* initial commit

* add merge tp for optimizer

* add sharded index for unified optimizer

* rename optimizer state dict key

* change param name

* optimize merge optimzer tp speed

* optimize save speed

* nested copy state dict

* fix bug

* fix filename

* add ckpt check, add dispatch table creationg

* fix sharding group index json

* remove dist_gather, use paddle.distributed's gather instead

* add dynamic load

* support dynamic load, not feasible currently

* add check_unified_optimizer

* add dynamic load optimizer

* fix loading optimizer with sharding group

* add unittest for n1c8 dynamic

* add unittest for n2c4 dynamic

* refine unittest, add dynamic convert test

* fix distributed_send_recv bug

* fix optimizer params
2023-12-12 10:33:23 +08:00
MayYouBeProsperous
e6acb0e5bc add to_static for electra (#7575)
* add --to_static for electra

* remove comment

* Update run_pretrain.py
2023-12-11 17:30:38 +08:00
Siming Dai
a866ae4337 [Qwen] Support Qwen flash attention 2 with attention mask (#7624)
Support qwen fa2 with attention_mask
2023-12-11 17:22:55 +08:00
Haohongxiang
675ee05c74 [LlaMA] Fix llama final norm in pp modeling (#7615) 2023-12-11 15:46:20 +08:00
Liujie0926
2c71b215b7 【benchmark】add max_mem_reserved for llm benchmark (#7538)
* 【benchmark】add max_mem_reserved for llm benchmark

* update

* add arg for case

* update gpt-3/moe/bert mem

* update mylog

* fix

* fix

* fix

* update for skip_memory_metrics

* update ce_gpt

* fix
2023-12-11 15:25:17 +08:00
骑马小猫
4f630fe6cc [Bug fixes]Refactor chat template intergration test (#7618)
* remote llama chat-template intergration test

* update qwen chat-template
2023-12-11 11:01:26 +08:00
Siming Dai
ae5c1a9c97 add auto_cast enable=False for paddle.outer (#7617) 2023-12-11 10:49:40 +08:00
Haohongxiang
dd6e4f146c [Llama2] Add uts for llama in semi-auto mode (#7588)
* Add uts for llama in semi-auto mode

* update uts

* update uts

* fix target paths

* update
2023-12-08 17:43:51 +08:00
tianhaodongbd
344f0029ab [CE] Add ce_gpt-gpt345_dp1 && dp8 && SD8_stage1 (#7484)
---------

Co-authored-by: niuliling123 <sdust_niull@163.com>
2023-12-08 17:09:17 +08:00
Zhong Hui
a8d0942e1e [Trainer] Add memory info in log (#7587) (#7607)
* add memory info
2023-12-08 14:13:03 +08:00
骑马小猫
e7d67410bc open ci testing (#7606) 2023-12-08 13:21:41 +08:00
Zhong Hui
9c279f7e10 [Trainer] Remove dp group with group_sharded_parallel checks. (#7507) 2023-12-08 11:46:57 +08:00
Ruibiao Chen
a74916d8b6 Fix post_init bug for run_pretrain_auto (#7604) 2023-12-08 11:13:26 +08:00
gmm
8aa96d27ec 【benchmark】add max_mem_reserved for benchmark (#7488)
* add max_mem_reserved for benchmark

* add max_mem_reserved for benchmark

* add max_mem_reserved for benchmark

* add max_mem_reserved for benchmark

* fix

* fix

* fix

* fix
2023-12-07 16:21:20 +08:00
zxcd
1fd95e5e56 [GPT] Fix dtype (#7595) 2023-12-07 11:25:43 +08:00
Haohongxiang
b05873629e [Auto Parallel] support arg for enabling fused_linear_param_grad_add pass (#7589) 2023-12-06 13:16:33 +08:00
骑马小猫
810edc2acc [Improvement] update eos-token-id (#7584)
* update eos-token-id

* complete the eos-token-id codes

* update streamer pre-tokens

* change streamer

* update predictor
2023-12-05 21:00:26 +08:00
Yuanle Liu
1e34cb0fa6 [LLM] inference model use new executor (#7467) 2023-12-05 20:20:32 +08:00
Ting Liu
0f1abea5b7 Chat gradio (#7581)
* chat gradio

* bug fix

* bug fix
2023-12-05 19:53:37 +08:00
Liujie0926
6a3efc33f5 [gpt-3]Fix dynamic_prepare for CI (#7550)
* fix data download

* fix auto_benchmark timeout
2023-12-05 15:26:26 +08:00
骑马小猫
9a0cbcd556 disable CUDA_DEVICE_MAX_CONNECTIONS for ce (#7586) 2023-12-05 12:04:50 +08:00
JZ-LIANG
aa44c6ed9f annotation update (#7486) 2023-12-05 11:38:58 +08:00
zxcd
6d41cbcd87 remove astype for probs, all dtype should same with scores. (#7577)
* dtype should same with scores.

* fix
2023-12-05 11:09:52 +08:00
niuliling123
f3607d5239 [Trainer] Update set_seed in trainer_utils.py (#7528) 2023-12-05 10:50:24 +08:00
Siming Dai
ca0e45bef6 [Dist Dataloader] Fix dist dataloader sampler (#7579)
* fix distdataloader sampler
2023-12-04 21:11:17 +08:00
xysheng-baidu
8ed33e9a42 [LLM] Fix mp parameter initialization (#7534) 2023-12-04 19:56:33 +08:00
Ruibiao Chen
7234321697 Set flash_attn mask to None in LlamaPretrainedModelAuto (#7566) 2023-12-04 18:51:43 +08:00
blueoom
74bb39b51b load_from read file with encoding utf8 (#7558) 2023-12-04 10:59:30 +08:00
骑马小猫
1a7e7d4572 [Bug fixes]fix intergration test (#7569)
* remove intergration test

* update llama2 chat-template
2023-12-04 10:58:02 +08:00
Leo Chen
f377693ebe init fp32 model and then cast to fp16 when use amp-o2 (#7546) 2023-12-04 10:57:42 +08:00
lugimzzz
d4a8d4ab15 fix qat (#7565) 2023-12-03 22:28:25 +08:00
xuzhang
2f21556a0f fix clip image processor (#7540)
* fix clip image processor

* support CLIPTextTransformer fp16

* revoke
2023-12-01 15:18:50 +08:00
lugimzzz
0faa701fb0 [PEFT]add qlora (#7416)
* add qlora(wip)

* add state convert

* add qlora

* update

* fix

* fix

* update

* update

* fix
2023-12-01 15:11:51 +08:00
lugimzzz
0dc4b48bd9 [llm]update data loading (#7557)
* update data

* update

* remove error raise

* fix
2023-12-01 13:55:07 +08:00
yujun
2bc6d8df77 确保静态图导出的时候使用的是1D tensor (#7555) 2023-12-01 07:31:27 +08:00
Ruibiao Chen
46d7534825 [AutoParallel] Fix init weight for llama modeling auto (#7491)
* Fix init weight for llama modeling auto

* remove _init_weights in LlamaPretrainedModelAuto
2023-11-30 19:38:46 +08:00
Wang Bojun
665731a40d add scale dtype test for weight quantize (#7552)
* add scale dtype test ofr weight quantize

* fix code style
2023-11-30 14:09:09 +08:00
yujun
5500d093d5 删除tipc中对于paddlemix的依赖 (#7543) 2023-11-30 10:15:12 +08:00
w5688414
057b429d15 Fix fp16 o1 bugs (#7548) 2023-11-29 08:02:39 -06:00
w5688414
5eb2eae1c7 [Paddle-pipelines] remove redundant requirements, upgrade to 0.6.2 (#7518)
* remove redundant requirements

* Upgrade to 0.6.2

* Update txt text processing

* fix ci error

* recover markdown
2023-11-29 01:15:35 -06:00
骑马小猫
be318c565a fix pyyaml installing under py310 (#7526) 2023-11-27 20:04:18 +08:00
Yiqun Liu
48bb1c05cb [Llama] Hotfix recompute in PP for benchmark. (#7479) 2023-11-27 15:01:09 +08:00
yujun
84ec87bf7f rm sd ldm benchmark (#7434) 2023-11-27 14:51:13 +08:00
lzydev
1b6e00782d add refined-recompute config (#7519) 2023-11-27 11:04:39 +08:00
Ting Liu
3081e2e35b remove useless import (#7517)
* remove useless import

* remove import
2023-11-27 09:19:41 +08:00
DrownFish19
e8d3b630ba [Unified checkpoint] Add unified optimizer loader (#7441)
Add unified optimizer loader

---------

Co-authored-by: DesmonDay <908660116@qq.com>
Co-authored-by: Zhong Hui <zhonghui.net@gmail.com>
2023-11-24 19:05:00 +08:00
骑马小猫
db1a79a69d [Bug fixes] remove qwen 14b-chat special token testing (#7514)
* fix chat_template qwen 14b-chat ci

* remove eos_token_id from ChatTemplate
2023-11-24 01:47:17 -06:00
Ting Liu
8d626c570c Gradio multi (#7508)
* code save

* rm sharememory, port exchange

* single gpu support

* code refinement

* gradio unittest
2023-11-24 01:29:09 -06:00
Siming Dai
be99faba2d [Trainer] Fix dist gather (#7513)
* remove dist_gather, use paddle.distributed's gather instead

* fix gather
2023-11-24 01:26:20 -06:00
zhouzj
7b36d571df Fix lora save (#7504)
* add method for saving scale in TP mode

* fix save mode in PP mode

* fix channel-wise's import

* fix bugs

* fix bugs

* fix bugs
2023-11-24 01:11:47 -06:00
骑马小猫
42764a5389 [Bug fixes]disable predictor testing (#7496)
* disable predictor testing

* disable inference-model testing

* disable gradio logit-compare
2023-11-23 20:25:37 +08:00
Siming Dai
f625c87717 Remove dist_gather, use paddle.distributed's gather instead (#7509) 2023-11-23 17:57:18 +08:00
w5688414
d181e352e5 Fix attention_score -nan bug (#7501) 2023-11-22 07:24:32 -06:00
Siming Dai
bf9d5bfa39 fix sharding index json (#7499) 2023-11-22 05:54:08 -06:00
Zhong Hui
14ab8d7b40 [Trainer] Fix pp config usage. (#7443) 2023-11-22 19:03:08 +08:00
骑马小猫
d4faef6d6a [Improvement] add context_data support for chat_template rendering (#7480)
* add context_data support for chat_template rendering

* update method name

* add chat_template_with_context_data file
2023-11-22 14:42:05 +08:00
tianhaodongbd
4645ddcf4a [Trainer] Support sharding stage 3 for main grad (#7319) 2023-11-22 10:50:56 +08:00
tianhaodongbd
628db887c9 [Trainer] Support dp for main_grad (#7293) 2023-11-22 10:49:58 +08:00
Zhong Hui
13b478606a [BugFix] Update trainer.py (#7492) 2023-11-21 18:26:16 +08:00
Siming Dai
d148cfee94 [Unified checkpoint] Add unified optimizer (#7373)
* initial commit

* temp commit

* add merge tp for optimizer

* add sharded index for unified optimizer

* rename optimizer state dict key

* change param name

* optimize merge optimzer tp speed

* optimize save speed

* nested copy state dict

* simplify code

* polish code

* fix bug

* fix filename
2023-11-21 01:23:06 -06:00
Zhong Hui
f136a4453c [Unified Ckpt] Add unittest for unified checkpoint. (#7392)
* init test for save/load

* fix warmup_steps.

* add unittest for unified checkpoint.

* reset script back.

* fix pp with sharding.

* remove some code.
2023-11-21 00:33:10 -06:00
Zhong Hui
c1b2fb35bc [LLM] Fix alibi in pipeline parallel for baichuan-13b (#7433) 2023-11-21 11:23:22 +08:00
JZ-LIANG
e56f928bcc [AutoParallel] Sequence Parallel Optimization Pass Config (#7409)
* annotation for sp

* hack of shard of

* remove redundent comm

* remove redundent comm

* add yaml

* sp default disenable

* bugfix

* sp optimization as default
2023-11-21 10:49:13 +08:00
DrownFish19
5477d46647 [GPT] Add sequence parallel for GPT (#7311)
* Add sequence parallel
2023-11-21 10:48:32 +08:00
Liujie0926
8e30689be5 [gpt-3]Add pir ci (#7471)
* add pir case

* update
2023-11-20 14:44:25 +08:00
zhaoyingli
d42afd342f update bsz for pretrain auto (#7474) 2023-11-20 10:10:56 +08:00
Haohongxiang
637fa55570 [Llama] Support hybrid strategy and recompute in llama auto version (#7458)
* support hybrid strategy and recompute in llama auto version

* remove redundancy codes
2023-11-17 16:40:45 +08:00
WAI-clear
de211d9ef6 Add load multi torch bin slices logic (#7445)
* test

* add load multi torch bin slices logit

* add safetensor/bin multi splices load

* add safetensors/bin multi slice files load
2023-11-17 16:37:56 +08:00
Ruibiao Chen
a36b70280a Log ips in auto Llama (#7459)
* Log ips in auto Llama

* Update code

* Update code
2023-11-17 14:51:14 +08:00
骑马小猫
757478946e use old_executor (#7464) 2023-11-17 14:04:00 +08:00
Yuanle Liu
0749e96550 [LLM] Inference use new executor and remove top_p_sampling custom op (#7432)
* inference use new executor

* delete custom op [top_p_sampling]

* update testing utils

* update chatglm2 config

* disable chatglm2 test temporarily

* update chatglm2 d2s

* test llama lora chat-template testing

---------

Co-authored-by: wj-Mcat <1435130236@qq.com>
2023-11-16 17:25:54 +08:00
Liujie0926
17a7f8ec44 [gpt-3]add new_exec_pp benchmark (#7457) 2023-11-16 16:55:59 +08:00
Liujie0926
2f5024a9e8 [CI]update gpt-3 scripts (#7350)
* update gpt-3 ci

* fix

* fix path

* fix

* fix

* update

* add case

* fix loss

* revert loss

* update

* fix

* update log_path

* fix

---------

Co-authored-by: PaddleCI <paddle_ci@example.com>
2023-11-16 16:29:39 +08:00
zhaoyingli
10d57f0b34 [AutoParallel] Support Llama (#7394)
* [AutoParallel] Support Llama

* Update training_args.py

* support dp

* revert modeling_auto

* support recompute

* rm comment

* rm print

* rm print
2023-11-16 11:02:14 +08:00
w5688414
10ff94a752 [retrieval benchmark] fix dynamic oom bug (#7449)
* fix dynamic oom bug

* Update benchmark

* Add comments

* remove max_length

* remove comments
2023-11-15 10:47:51 -06:00
骑马小猫
5202d5ba59 update chat-template readme (#7442) 2023-11-15 00:41:58 -06:00
w5688414
90ab47d86b remove tsinghua pip (#7435) 2023-11-14 23:37:21 -06:00
周周周
f01da97880 [llm] support GQA in chatglmv2 (#7412)
* support GQA in chatglmv2

* support new paddlenlp chatglmv2

* modify to test
2023-11-15 10:41:40 +08:00
骑马小猫
0731766c01 [New features] Add chat template for training (#7241)
* complete chat-template

* update chat-template

* fix lint

* update tokenizer

* update from_pretrained method

* update from_pretrained args

* update test

* encode chat-inputs

* add test_data testing code

* update chat_template

* update qwen conversation

* complete qwen finetune with chat-template

* update argument

* update chat-template

* support inference with chat-template in predictor.py

* update predictor

* update use_chat_template inference

* update chat-template pr

* update chatglm chat-template finetune

* update THUDM test_template

* add constrains between chat_template and eval_with_do_generation

* add position_ids to tokenized_result

* update chat-template

* update src_length

* update truncation

* update np.bool
2023-11-14 00:17:26 -06:00
zhang junjun
5524c5895b Add llm ci report (#7418)
* [CI] fix llm tests

* Add llm ci report

* update

* update

* update
2023-11-14 10:22:45 +08:00
w5688414
8d5abb607d [paddle-pipelines] Fix retrieval benchmarks (#7420)
* Fix retrieval benchmarks

* Update readme
2023-11-13 02:13:23 -06:00
骑马小猫
a16cbb3485 revert chatglm2 config (#7410) 2023-11-13 02:12:59 -06:00
RichardWooSJTU
e0643cc501 [LLM] Support ptq inference (#7224)
* re submit ptq inference

* add unittest

* fix readme and code refine

* fix ut name

* fix ut name

* fix wint8

* turn on auto tune flags in benchmark

* fix review

* fix review

* adapth quantization_config

* fix ci

* test
2023-11-13 16:11:52 +08:00
Ting Liu
92134e1847 add chatglm2 legacy checkpoints convert script (#7419) 2023-11-09 22:51:54 -06:00
Leo Chen
8d5fef01e2 support pir fuse pass (#7393) 2023-11-10 10:52:12 +08:00
w5688414
2cbf68d918 Update fa2 comments (#7415) 2023-11-09 09:30:10 -06:00
Siming Dai
76e92c12c4 fix bug (#7414) 2023-11-09 20:44:13 +08:00
Ting Liu
d45f7c4a3b convert chatglm2 to fuse qkv (#7379)
* chatglm2 remove fuse qkv

* fix lint
2023-11-09 05:48:10 -06:00
Sijun He
40c9c56e0f Update requirements.txt (#7408) 2023-11-08 23:45:42 -06:00
Siming Dai
e877ad1406 [Trainer] Fix dist dataloader with no mp group (#7407) 2023-11-09 13:11:28 +08:00
WAI-clear
0771a88328 fix qwen matrix dimmention alignment (#7402) 2023-11-09 10:36:50 +08:00
liuzhenhai93
111b381146 Develop sharding reshard (#7399)
* format

* tested

* format
2023-11-09 10:01:20 +08:00
Ting Liu
65ec3686b3 support torch safe tensor convert (#7383)
* support torch safe tensor convert

* code refinement

* if statement adjust

* skip clip & bart unitest

* skip clip & bart unitest

* close bart serialization save

* gradio-fix
2023-11-08 17:24:33 +08:00
lugimzzz
6db372605e add neft (#7382) 2023-11-07 20:39:53 -06:00
骑马小猫
254414e024 [Function optimization] update llama ce script (#7192)
* update llama ce script

* add bloom & chatglm ce testing

* add bloom/chatglm ptuning ce scripts

* update llama ce scripts

* update test_predictor

* code save

* fix typo

* remove testing model

* update config file

* remove testing model code

* disable chatglm testing

* merge, fix yaml

* update chatglm2

* add chatglm2

* lint fix

* add chatglm2 ce shell

* run_ce arg update

* add debug print

* update llama ce script

* update test_predictor

* reduce the src_length and max_length

* remove chatglm2 config

---------

Co-authored-by: wtmlon <wtmlon@foxmail.com>
2023-11-07 10:40:40 +08:00
JZ-LIANG
40fe6644c0 [Semi-Auto] Sequence Parallel for Auto Mode (#7301)
* annotation for sp

* hack of shard of

* remove redundent comm

* remove redundent comm

* add yaml

* sp default disenable

* bugfix
2023-11-06 20:55:28 +08:00
w5688414
7841869d4b [baichuan2 13b] Fix alibi bug (#7376)
* Fix alibi bug

* Fix alibi 2.5.2
2023-11-06 05:07:49 -06:00
lugimzzz
c5259814a8 [PEFT]add qatlora mp (#7288)
* add qatlora mp

* support qat lora tp
2023-11-06 01:34:37 -06:00
lugimzzz
dd41947ae2 add peft save_to_aistudio (#7364) 2023-11-03 03:22:09 -05:00
lzydev
c013ccb080 【AutoParallelism】add "refined_ops_patterns" in recompute strategy (#7349)
* add refined_ops_patterns in recompute strategy

* modify the yaml file

* add sr

* fix yaml file"
2023-11-02 20:25:20 +08:00
Ting Liu
fc2bf9cc6e Qwen support position_ids (#7359)
* qwen add position ids

* qwen add position ids

* bug fix

* bug fix
2023-11-02 20:02:30 +08:00
w5688414
5a50bdd212 [Fix llm bugs] Add use cache & version check (#7357)
* Add use cache

* Add version check

* Update flash attention

* Update warning msg

* Update use_cache
2023-11-02 11:51:26 +08:00
Haohongxiang
fd527884d6 support pure single-card modeling for auto_parallel (#7348) 2023-11-02 11:35:32 +08:00
Ting Liu
20a6afed9f freeze gradio version (#7355)
* freeze gradio version

* freeze gradio version
2023-11-02 10:01:10 +08:00
lugimzzz
b98b64b093 fix peft load_best_model_at_end & resume from checkpoint (#7360) 2023-11-01 10:01:05 -05:00
Leo Chen
849ebff85c add parallel seed control (#7347)
* add parallel seed control

* update
2023-11-01 20:33:48 +08:00
Zhong Hui
f15ca845d4 [Trainer] Support broadcast optimizer in dp group and fix unified checkpoints (#7256)
* add sharded save

* fix unified ckpt with dp.

* fix with load dp.

* fix bugs for pure pp. add miss keys check.

---------

Co-authored-by: DesmonDay <908660116@qq.com>
2023-10-31 21:15:28 +08:00
Ting Liu
4fb915b697 Add qwen baichuan ci (#7324)
* add qwen alibi-baichuan ci

* attention mask fix

* add tiktoken requirement

---------

Co-authored-by: 骑马小猫 <1435130236@qq.com>
2023-10-31 16:16:47 +08:00
LokeZhou
0407095860 [Other]TopPProcess add bfloat16 input (#7337)
* TopPProcess add bfloat16 input

* fix sorted_indices cast
2023-10-31 16:12:55 +08:00
lugimzzz
f0566e8b47 [aistudio] add save to aistudio hub (#7338)
* add save to aistudiohub

* fix according to comments
2023-10-31 14:38:59 +08:00
Siming Dai
0c05adc015 [CI] Add qwen pretrain test (#7330)
* add qwen pretrain test

* rm model_type
2023-10-31 12:03:16 +08:00
xiaoxiaohehe001
13efd366ad [LLM] Support fuse_gpt wint8/4. (#7304)
* support_gpt_wint

* support_gpt_qkv_unfuse
2023-10-30 14:15:32 +08:00
lugimzzz
fe8cdf0d79 [quant] add QuantizationConfig (#7314)
* add

* add quantization config

* update

* fix

* fix

* add quantization_config
2023-10-27 18:06:24 +08:00
Chang Xu
e7b53f6d27 Support Fast PTQ (#7282) 2023-10-27 11:18:06 +08:00
Siming Dai
02c98858f0 Optimize qwen model with fused_rope, fused_rms_norm and core_attn recompute (#7307)
* add fused_rms_norm, fused_rope

* add core_attn
2023-10-27 10:39:59 +08:00
骑马小猫
bae323a940 [Bug fixes] update inference doc (#7299)
* update inference doc

* update table matri

* remove temp-doc
2023-10-27 08:23:58 +08:00
Ruibiao Chen
770bfacee0 Support setting allreduce_matmul_grad_overlapping and enable_send_recv_overlap in auto_config (#7297) 2023-10-26 13:08:44 +08:00
w5688414
5d2c290426 [llm benchmark] Add flash attention 2 (#7057)
* Add flash attention

* Add chatglm flash attention

* format llama

* Update flash attention

* Fix casual low precision bug

* Update finetune generation config

* Add seed config

* Update FA2

* Update attention

* update llama

* Update casual config

* Update alibi config

* rm is casual parameter

* Update bloomz config
2023-10-25 23:21:14 -05:00
lugimzzz
513f763ec7 fix recompute (#7235) 2023-10-25 17:22:51 +08:00
Zhong Hui
60fd6bec50 Support qwen pretrain. (#7275)
* Support qwen pretrain.

* add missing files.

* fix

* Support fuse rms norm

* add new config.

* refine

* fix

* auto model support from config.
2023-10-24 21:40:59 +08:00
Siming Dai
4b8600615b Modify dist dataloader (#7286) 2023-10-24 17:49:11 +08:00
wawltor
5359c0e2f9 Add qwen flash attention (#7289)
* support the flash attention for the qwen

* support the attention mask for the qwen

* fix the return softmax in fa

* update the use_flash_attention to use_flash_attn

* disable flash attn for the qwen test

* delte some unused code
2023-10-24 10:54:36 +08:00
骑马小猫
22d6bd5fe4 update inference doc (#7296) 2023-10-24 09:46:33 +08:00
lugimzzz
ddb60e5757 [llm]fix weight only quantization (#7252)
* fix quantization

* fix

* fix

* json
2023-10-23 06:46:54 -05:00
骑马小猫
7dd7f1739e [Bug fixes] disable ir_optim under bfloat16 (#7292)
* disable ir_optim under bfloat16

* delete pass

* update predictor

* trigger cic
2023-10-23 17:07:03 +08:00
骑马小猫
4476448af0 [New features] update llm docs (#7290)
* update llm docs

* update inference doc

* update inference

* update inference doc
2023-10-23 17:04:32 +08:00
Ting Liu
639215adaf readme update 14b (#7291)
* readme update 14b

* fix
2023-10-22 21:51:02 -05:00
Yichen Zhang
d9f260356b [GPT] Replace reshape with set_dynamic_shape api to set dynamic shape to a tensor (#7281) 2023-10-20 16:31:37 +08:00
Yiqun Liu
e398018e20 [Trainer] Polish the setting of dist_strategy. (#7214)
* Polish the setting of distributed strategy.

* Avoid redundant cast.

* Optimize benchmark command for better overlap.
2023-10-20 11:12:18 +08:00
xiaoxiaohehe001
2f2816753e [LLM] Support chatglm/bloom wint8/4. (#7207)
* chatglm_bloom_wint

* add_wint4_test

* delete_wint4_test

* update bloom wint8

---------

Co-authored-by: wj-Mcat <1435130236@qq.com>
2023-10-19 18:53:03 +08:00
周周周
9db7022c09 [llm]support chatglmv2 in fined FT (#7253)
* support chatglmv2 in fined FT

* support chatglmv2 in fined FT

* commit

* final commit

* final commit

* final commit

* comment ChatGLMForCausalLM
2023-10-19 18:39:39 +08:00
cyber-pioneer
f9021f8f7f [PIR][Prim] support PIR train (#7276)
* support PIR train

* polish code
2023-10-19 15:16:17 +08:00
Zhong Hui
f9d8e73f0c [Trainer] Add unified checkpoint for hybrid parallel. (#7238) 2023-10-18 18:40:23 +08:00
骑马小猫
d152fdb035 add docs for chat-template (#7270) 2023-10-18 04:56:34 -05:00
lzydev
90f44a97f3 fix error in dropout of hybrid_model (#7269) 2023-10-18 16:17:17 +08:00
zhaoyingli
af0d26ada3 update shard tensor for pp (#7167)
* update shard tensor for pp

* rm shard_op

* rm shard_op
2023-10-18 14:51:39 +08:00
骑马小猫
00ab0e1c4b [Bug fixes] update lru_cache usage (#7260)
* update lru_cache usage

* trigger cla
2023-10-18 14:09:48 +08:00
Leo Chen
27c4c89385 add flash attention for auto gpt3 (#7135)
* add flash attention for auto gpt3

* remove transpose
2023-10-18 11:51:02 +08:00
Siming Dai
faf3e3c90c Fix fp32 dist dataloader (#7261) 2023-10-18 11:32:14 +08:00
Siming Dai
86f24edb24 Support zero dataset splits for pre-training (#7259)
* support empty splits

* fix split

* fix dd

* modify func name
2023-10-18 10:40:52 +08:00
xiaoxiaohehe001
c39c6280fe fix_bloom_precache (#7249) 2023-10-17 21:06:24 +08:00
骑马小猫
671775be9d [New Features] add chat-template for inference (#7219)
* complete chat-template

* update chat-template

* fix lint

* update tokenizer

* update from_pretrained method

* update from_pretrained args

* update test

* add skip warning for chat-template file

* update chat-template by comment
2023-10-17 03:38:36 -05:00
周周周
9d9e60dca6 when < 11.6 (#7250) 2023-10-17 14:27:00 +08:00
Siming Dai
dd9bec075c Support fp32 dtype for dist dataloader (#7240)
* support fp32
* add todo
2023-10-16 16:57:08 +08:00
lugimzzz
edcd54d861 remove warning (#7234) 2023-10-15 22:21:13 -05:00
Sijun He
70e750c02c Fix subfolder default argument in model download (#7220)
* styles

* remove print
2023-10-13 05:43:23 -05:00
骑马小猫
25dcba99d1 [New Features] Add prefix allowed token (#7210)
* use model_type to control model-intialization

* add prefix_constrained logit processor
2023-10-13 01:45:07 -05:00
骑马小猫
6f03ec69fe [Bug fixes] Fix export model validate pdmodel (#7201)
* use model_type to control model-intialization

* update output_path for validate_pdmodel

* update export rank_index

* trigger cla
2023-10-13 11:16:03 +08:00
Siming Dai
b0fa9c42aa [Trainer] Support iterable dataset with dist dataloader (#7208) 2023-10-12 19:52:27 +08:00
Zhong Hui
6140ad2497 Update README.md (#7184) 2023-10-12 19:38:17 +08:00
Ting Liu
0a66a2e6a5 adjust gradio unittest assert (#7205) 2023-10-12 19:30:27 +08:00
xiaoxiaohehe001
43a6829740 bloom_precache (#7204) 2023-10-12 14:55:09 +08:00
DrownFish19
dc6e0d901c fix tokenizer decode (#7195) 2023-10-12 14:42:41 +08:00
Siming Dai
c9db29cecf fix_shard_size (#7202) 2023-10-12 14:40:49 +08:00
RichardWooSJTU
64f00f084f [LLM] Reconstruct fused transformer layers (#7186)
* reconstruct fused_transformer_layers

* delete origin class

* code refine
2023-10-12 14:07:53 +08:00
Ting Liu
d0c85dfa3c bloom chatglmv1/2 llm unittest (#7165)
* bloom chatglmv1/2 llm unittest

* resolve empty return
2023-10-12 14:06:22 +08:00
Sijun He
74eb855568 Update README.md 2023-10-11 08:06:56 -05:00
Siming Dai
1f708035ea Add max_shard_size arg (#6835)
* add max_shard_size arg

* rm max_shard_size

* move to 1024

---------

Co-authored-by: daisiming <daisiming@baidu.com>
2023-10-11 20:48:58 +08:00
骑马小猫
be39ed1abb use batch_size = 3 (#7191) 2023-10-11 05:22:14 -05:00
lugimzzz
11e7735f75 [PEFT]support pp + lora (#7198)
* support pp lora

* update
2023-10-11 04:47:28 -05:00
xiaoxiaohehe001
d1e060fa88 support_prealloc (#7194)
Co-authored-by: liuzichang01 <liuzichang01@baidu.com>
2023-10-11 01:56:10 -05:00
骑马小猫
cfd8d391da add opt __init__.py (#7193) 2023-10-11 14:27:24 +08:00
xiaoxiaohehe001
ddf845b7c3 [LLM] Fix error when config.bs is more than input bs. (#7187)
* bs_slice

* fix_bloom

* support_bloom

---------

Co-authored-by: yuanlehome <yuanlehome@163.com>
Co-authored-by: liuzichang01 <liuzichang01@baidu.com>
2023-10-10 22:02:54 -05:00
Kunbo Ding
dc32055c98 [README] fix README in model_zoo/ernie-1.0/preprocess (#7188)
* [README] fix README in model_zoo/ernie-1.0/preprocess

* [README] fix README in model_zoo/ernie-1.0/preprocess
2023-10-11 10:27:50 +08:00
Kunbo Ding
aafadd2581 Add share-folder for distributed training (#7068)
* add share_folder for data_cache_path

* remove pdb

* fix README

* fix share_folder

* update README

* update README
2023-10-10 20:55:53 +08:00
骑马小猫
2ce561bacc [New Features] add llama ce scripts (#7118)
* add llama ce scripts

* update llama ce-predictor

* update predictor

* update test_predictor

* update ce scripts

* update ratio

* update run_ce.sh scripts

* update ce scripts

* update llama ce scripts

* update prepare.sh script

* update convergence keyword

* revert requirements
2023-10-10 16:07:43 +08:00
Ting Liu
27d67d49c2 gradio ui support streaming (#7086)
* gradio ui support streaming

* update

* remove hard code values

* add gradio unitest

* add comment

* add pytest timeout requirement

* add requirement, enlarge port range

* enlarge port scan range

* port range adjust,

* add gradio requirement
2023-10-10 14:09:20 +08:00
骑马小猫
226c6c03fa [New features] Add precache predictor test (#7137)
* use model_type to control model-intialization

* add llama precaches predictor

* update pre-cache config

* remove print

* revert max_length
2023-10-09 21:40:22 -05:00
Sijun He
13502f9a46 Support AI Studio download (#7146)
* styles

* fix subfolder

* remove print
2023-10-09 08:05:49 -05:00
DrownFish19
674587652f [GPT-3] Fix attention and past_key_values (#7088) 2023-10-09 19:05:42 +08:00
骑马小猫
5fe0cfc344 [BugFix] fix readthedocs (#7175)
* fix readthedocs

* update recommonmark
2023-10-09 04:58:27 -05:00
骑马小猫
34e5744ef8 [Bug fixes] Fix experimental llama set_state_dict (#7142)
* use model_type to control model-intialization

* fix llama set_value dtype
2023-10-09 04:31:11 -05:00
Ruibiao Chen
26fdd47c39 Enabel FLAGS_new_executor_micro_batching in AutoEngine (#7168) 2023-10-09 14:28:23 +08:00
xiaoxiaohehe001
0ba34f68f4 support_chatglm_precache (#7109) 2023-10-09 14:16:46 +08:00
lugimzzz
16353f4172 [llm]support lora for quantizationlinear (#7138)
* support quantizationloralinear

* Version compatible

* add comment

* add mp quantization lora

* fix

* fix

* fix
2023-10-08 22:11:31 -05:00
Zhong Hui
68bb39dc90 [GPT] Fix bugs (#7141)
* fix gpt-3

* refine

* remove gpt-3.

* fix ci

* fix

* fix ci
2023-09-28 10:37:52 +08:00
lugimzzz
0db85f7d7f [llm]add quantization tensor parallelism (#7099)
* add quantization mp

* update

* follow comments

* fix

* fix shape

* update
2023-09-27 01:11:38 -05:00
wanly young
685d12bf1a [DistDataLoader]bgroup null judge fix (#7122)
* group null judge fix
* fix all
2023-09-27 11:16:26 +08:00
Siming Dai
6c11dea23e [BugFix] Fix tp load and gpt pp model (#7129)
* fix gpt pp model
* fix tp load
2023-09-26 13:11:52 +08:00
骑马小猫
3cf31e8b29 [New Features] Add test predictor for llm (#7115)
* use model_type to control model-intialization

* add test_predictor

* update inference  & no inference

* update comment

* update test_assert
2023-09-25 22:26:47 -05:00
Zhong Hui
0b73e12232 remove load state as np. (#7120) 2023-09-25 22:26:11 -05:00
Zhong Hui
c1157e5a2a Update trainer.py (#7123) 2023-09-25 02:10:59 -05:00
Zeyu Chen
9c3f8a4256 Update README.md 2023-09-24 11:12:42 -05:00
Zeyu Chen
cc293601a9 Update README.md 2023-09-23 21:22:27 -05:00
Zhong Hui
51835e8ead [LLM] Unify pipeline model with PretrainModelPipe (#7095)
* unify pipeline model with PretrainModelPipe.
2023-09-22 17:58:19 +08:00
zhang junjun
cdc7382c1a [CI] fix llm tests (#7117) 2023-09-22 17:30:05 +08:00
Tian Zheng
060fbf2ff0 [NVIDIA] Add stage2 NCCL kernel overlap (#7092)
* add stage2 comm overlap

* Make stage2 overlap optional
2023-09-22 17:22:56 +08:00
ZZK
73a20bd663 fix benchmark compute statistics (#7098)
* fix args.benchmark and compute statistics

* revert warmup times

* fix cachekv shape and force to use fleet exectuor

* fix merge conflict

* update total_max_length

* add enable memory optim

* fix multi predictor in fleet runner

---------

Co-authored-by: xiaoxiaohehe001 <hiteezsf@163.com>
Co-authored-by: wj-Mcat <1435130236@qq.com>
2023-09-22 16:02:11 +08:00
Yuang Liu
a99cc55960 [Trainer] Support master grad for sharding stage 2. (#7075) 2023-09-22 10:49:15 +08:00
Yiqun Liu
748e69d162 Polish the benchmark scripts and add test for N4C32. (#7105)
* Polish the benchmark scripts and add test for N4C32.

* Update the setteing of pipeline_parallel_config.

* Add the missing comma and rename all the benchmark filename.
2023-09-22 09:30:47 +08:00
骑马小猫
48596fee6b [Bug fixes]fix chatglm2 d2s (#7110)
* fix chatglm2 d2s

* open chatglm2 d2s
2023-09-21 07:12:06 -05:00
w5688414
bcf4427ef9 [Paddle-Pipelines] Add top_k support (#7103)
* Add top_k support

* Update prompts
2023-09-21 03:57:42 -05:00
周周周
17a3d34d6e support opt-2.7 (#7010)
* first commit

* first commit

* remove somen redunant code

* commit

* commi all

* remove my useless code

* make paddlenlp/transformers/opt/modeling.py revert origin

* uopdate # Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.

* remove some unsed symobl in experimental/transformers/opt/modeling.py

* commit

* commit

* fix a bug in generation_utils

* add model_kwargs[past_kv_length]

* add opt in predict.py

* support more batch

* use state_dict.pop && encoder_max_seq &&

* remove ids_remove_padding

* remove self.past_key_value_length

* remove repeate self.hidden_size = config.hidden_size

* do not use past_kv_length

* remove encoder_max_seq
2023-09-21 14:41:40 +08:00
Yuanle Liu
af28006018 [LLM] Support gpt3 fine grained dybatch v1 (#7080)
* support batch_size=1

* support batch_size > 1

* update

* support to_static

* add benchmark for dybatch_preprocess

* fix code style

* fix code style

* fix comment

* update
2023-09-20 20:51:12 +08:00
w5688414
d3c2e4c9c0 Fix function log reptition bug (#7097) 2023-09-20 05:46:08 -05:00
qingzhong1
8a11e7e330 [Paddle-pipelines] Add HNSW support for BES (#7021)
* add hnsw

* update elasticsearch

* update elasticsearch

* update es
2023-09-20 05:30:39 -05:00
w5688414
633db301e6 [Paddle-Pipelines] Add stream output (#7087)
* Add stream output

* Update

* Fix chat bug

* revert

* Add free chat stream support

* Update prompts

* Reformat function calling logic
2023-09-20 05:28:32 -05:00
骑马小猫
a150627577 [New Features] add llm pretrain & lora & sft & prefix_tuning testing scripts (#7056)
* add chatglm finetune

* add llm ci scripts

* add llama llm testing

* update llm testing

* revert chatglm sft-arguments

* revert chatglm sft-arguments

* update llm testing
2023-09-20 04:57:00 -05:00
Chang Xu
d2524ab9ab Support WikiText & Lambada (#7079)
* Support WikiText & Lambada

* Support WikiText & Lambada

* update
2023-09-20 10:56:00 +08:00
Wennie396
f18dcc8868 align config between dy/st and add memory profiler for dy (#6982)
* align config between dy and st

* add memory profiler for dy

* comment tiny fix

* delete config 'vocab_size_divisible_unit' when get_model
2023-09-20 10:50:57 +08:00
lugimzzz
c6e0f7862f [llm]add quantize (#7027)
* add quantize

* fix bug

* bug fix

* fix saving

* bug fix

* fix and add unitest

* update paddle version

* update following comments

* support prefix

* Update paddlenlp/transformers/model_utils.py

* update

* fix

---------

Co-authored-by: DesmonDay <908660116@qq.com>
Co-authored-by: Sijun He <sijun.he@hotmail.com>
2023-09-19 21:41:48 -05:00
Sijun He
06b25e3933 limit to 1 function call per round (#7084) 2023-09-19 21:09:32 +08:00
Shijie
5748b69242 [LLM] Fix synchronized memcpy in GPT (#7008) 2023-09-19 16:53:49 +08:00
Zhong Hui
a435f30770 [README] Update OpenWebText2.md (#7078) 2023-09-19 16:53:14 +08:00
Wennie396
321faf3052 add if-else use_new_executor branch (#6897)
* add if-else use_new_executor branch

* no pre-commit reformat

* add () for use_new_executor

* align old executor and new executor loss

* fix outs[loss].shape == () can't get value by outs[loss][-1]

* tiny format fix

* restore the way loss is calculated by new exe

* old executor doesn't have to / accumulate_steps

* dataloader_from_generator add param num_workers=1
2023-09-19 15:40:41 +08:00
Zhong Hui
27e25e6c59 [README] Update llama readme and add tool_helpers as requirement (#7069) 2023-09-19 14:16:28 +08:00
Sijun He
98fbee3074 changes (#7070) 2023-09-18 21:57:27 -05:00
骑马小猫
06764efe6c update paddlenlp_ops (#7071) 2023-09-18 21:57:06 -05:00
zhang junjun
bd3ce88429 [CI] fix-llm-tests (#7066)
* [CI] fix-llm-tests

* update

* Update ci_case.sh
2023-09-19 10:06:00 +08:00
骑马小猫
9c1fe1cfc3 update layername of chatglm (#7073) 2023-09-18 08:36:14 -05:00
Sijun He
40011aed35 Update README.md (#7072) 2023-09-18 07:31:23 -05:00
lugimzzz
da02adde36 [llm]fix bloom tensor parallelism (#7065)
* fix bloom tp

* add comment
2023-09-18 07:16:07 -05:00
Yuang Liu
3bd4bc3daf fuse rope udpate (#6957)
* fuse rope udpate

* remove full level rope

* update

* change to bool value

* update

* update name
2023-09-18 18:10:45 +08:00
Zhong Hui
223909073c [SetUp] Fix set up with pip install -e (#7062)
* fix pip install -e

* fix time
2023-09-18 16:58:23 +08:00
Sijun He
5db3d2a992 Support decode_token for stream generation (#7063)
* styles

* comments
2023-09-18 03:51:17 -05:00
zhang junjun
b732896390 [CI] add_llm_ci_ipipe (#7050)
* [CI] add_llm_ci_ipipe

* update
2023-09-18 16:49:42 +08:00
骑马小猫
7f09a411e9 update inference-model generation-utils (#7059) 2023-09-18 03:02:44 -05:00
w5688414
de6953debb [Paddle-Pipelines] Add function calling examples (#7051)
* Add function calling examples

* changes

* add log console

* update fnction_calling

* update fnction_calling

* update fnction_calling again

* reformat

---------

Co-authored-by: Sijun He <sijun.he@hotmail.com>
2023-09-18 02:55:56 -05:00
骑马小猫
d7c39ae2da fix hard-code model-prefix (#7048) 2023-09-15 09:06:29 -05:00
Zhong Hui
11dfdac938 [Trainer] Support show paddlenlp commit id (#7047)
* support install with git commit
* support trainer for paddlenlp commit id.
2023-09-15 17:55:38 +08:00
骑马小猫
c4242f3d94 [New features] refactor llm ci testing (#7046)
* add llm ci testing

* update pretrain testing

* convert slow -> default
2023-09-15 17:13:27 +08:00
Sijun He
dee37d8983 raise error if TP > 2 for ChatGLM2 (#7041)
* raise error for tp > 2

* lint
2023-09-15 02:37:33 -05:00
Ting Liu
26255bb4da fix beam search topk bug (#7044)
* fix beam search topk bug

* topk fix

* comment add
2023-09-15 02:31:00 -05:00
qingzhong1
4ac1c3f0eb add BAAI/bge-small-zh-v1.5 model (#7036)
* add BAAI/bge-small-zh-v1.5

* update parallel_retriever.py

* add bge
2023-09-15 02:03:42 -05:00
骑马小猫
9a80fec89b [Bug fixes] Fix typo (#7039)
* use model_type to control model-intialization

* fix typo
2023-09-14 07:22:39 -05:00
骑马小猫
998a041665 [Bug fixes] Fix generate d2s (#6971)
* use model_type to control model-intialization

* fix generation d2s

* enable llama d2s testing

* update generate d2s

* update is_encoder_decoder

* max_length -> max_new_tokens
2023-09-14 04:28:48 -05:00
Ting Liu
fe71c6801f fix cache select bug (#7026)
* fix cache select bug

* update

* lint fix

* fix bug
2023-09-14 00:53:21 -05:00
Sijun He
fd2bed541f changes (#7029) 2023-09-13 22:53:21 -05:00
骑马小猫
7e09afcc0c [Benchmark]change N2C16 -> gbs=64 (#6902)
* change N2C16 -> gbs=64

* update gbs=64 configuration

* update gbs field

* update sharding_degree -> ssharding_parallel_degree

* update llama scripts

* update llama benchmark scripts

* update llama N2C16 scripts

* change N2C16 script name

* update N1C8

* update N1C8 script

* update llama benchmark training strategy

* update N2C16 scripts

* update llama new benchmark training strategy

* update run_benchmark

* update max_step -> max_steps

* update tensor_parallel_config

* update benchmark script

* update base_batch_size

* update training_args

* change order or split

* update default tensor_parllel_config value

* change fp16 -> bf16

* revert requ-dev.txt

* update requirements-dev.txt
2023-09-14 11:31:38 +08:00
Siming Dai
1ef5b94a18 [TensorParallel] Support naive split for lazy safetensors (#7018) 2023-09-14 10:41:19 +08:00
w5688414
6e6301e544 Add embed_documents for ParallelRetriever (#7025) 2023-09-13 08:51:42 -05:00
Ting Liu
405b64c608 fix chatglmv1/2 beam search bug (#7017)
* fix chatglmv1/2 beam search bug

* group beam search fix bug
2023-09-13 07:06:44 -05:00
zhang junjun
97b22f3e6d [CI] add_llm_unittest (#6913)
* [CI] add_llm_unittest

* fix lint

* update

* update

* update

* fix lint

* update

* fix finetune output

* fix lint

* fix predict

* update
2023-09-13 17:44:45 +08:00
lugimzzz
dcad8b0e3d [llm]update tipc setting (#6990)
* update setting

* delete

---------

Co-authored-by: DesmonDay <908660116@qq.com>
2023-09-13 03:15:27 -05:00
qingzhong1
fc0e7e16bd add mulprocessing (#7019) 2023-09-13 16:04:24 +08:00
骑马小猫
83e0b4703a [Bug fixes] fix inference dybatch d2s (#6998)
* fix inference dybatch d2s

* remove encoder-output
2023-09-13 01:53:09 -05:00
laixinyi
a43138bb4b fix T5 readme (#6659)
Support megatron dataset for T5
2023-09-13 11:17:26 +08:00
DrownFish19
d9f1b76773 [GPT-3] fix gpt3 config (#7006)
* fix gpt3 config

* update

* update

* update
2023-09-13 10:39:46 +08:00
ZZK
4a7665dbd1 Fix benchmark bug (#7002)
* fix bug

* fix wint4 convert
2023-09-12 08:21:49 -05:00
xiaoxiaohehe001
f5607336ca [LLM] support bloom dybatch (#7003)
* support_llama

* support_llama

* delete_loss
2023-09-12 08:20:48 -05:00
Sijun He
e49842c816 chatglm2 beam search fix (#7012)
* chatglm2 beam search fix

* changes

---------

Co-authored-by: 刘汀 <wtmlon@foxmail.com>
2023-09-12 07:02:56 -05:00
WangZhen
45d4ee804f Fix bert error in SOT (#6942)
* Fix bert error in SOT

* Format code

* Format code
2023-09-12 19:23:44 +08:00
DrownFish19
d83032de04 [GPT-3]fix fluid for stride_check (#6999)
* fix fluid for gpt

* fix

* update FG CMakeLists.txt

* fix

* update FasterTransformer link
2023-09-12 19:19:44 +08:00
Sijun He
07902f6bd6 Add new models to LLaMA README.md (#6985)
* Update README.md

* changes

---------

Co-authored-by: 刘汀 <wtmlon@foxmail.com>
2023-09-12 06:12:24 -05:00
w5688414
834213c8e6 [Paddle-Pipelines] Update chatpaper UI for fitting aistudio (#7011)
* Update chatpaper UI

* remove unused comments

* remove unused comments
2023-09-12 06:06:12 -05:00
zhaoyingli
b6ad73037f add fusedpass config in yaml (#6986) 2023-09-12 17:33:06 +08:00
w5688414
be61dcefc1 [Paddle-pipelines] remove ui requirements (#6992)
* remove ui requirements

* restore typing_extensions==4.5

* Update requirements

* remove st-annotated-text

* Add ui requirements to readme

* Update
2023-09-12 01:37:33 -05:00
ZZK
264de97e23 Fix fluid to base (#6989)
* fix fluid to base

* revert generation utils

* remove inspect
2023-09-12 10:12:40 +08:00
Siming Dai
77673c19f4 [BugFix] Fix load shard state_dict log (#6991) 2023-09-11 22:50:43 +08:00
liuzhenhai93
660185439a [GPT-3] ppfleetx sep support (#6962)
Co-authored-by: liuzhenhai93 <liuzhenhai@baidu.com>
2023-09-11 19:51:27 +08:00
DrownFish19
60df8dfcf0 Support megatron dataset for ernie-1.0 (#6653)
* fix modeling_pp error

* enable recompute for GPTDecoderLayerPipe

* add data impl for ernie-1.0

* support load megatron dataset for ernie

* fix doc_idx

* update

* format code

* fix

* formated

* fix

* update README.md

* update README.md and train bash

* add import in paddlenlp/data

* update

* update README.md

* update

* update readme

* update

* update

* update data download links
2023-09-11 19:04:44 +08:00
骑马小猫
6e82c908cc [Bug fixes] Fix gradio br newline display (#6980)
* use model_type to control model-intialization

* fix newline in gradio-ui display
2023-09-11 03:09:48 -05:00
Sijun He
033d859b1f max_new_token -> max_new_tokens (#6984)
* max_new_tokens

* default max new tokens
2023-09-11 03:09:20 -05:00
xiaoxiaohehe001
d758792e31 [LLM] support llama precache. (#6975)
* llama_precache

* update predictor

---------

Co-authored-by: wj-Mcat <1435130236@qq.com>
2023-09-11 02:48:55 -05:00
Chenghao Liu
5e250ee158 [Minor Fix] Urgent compatibility fix for “model_zoo/gpt-3” as “paddle.fluid” is already deprecated in Paddle upstream (#6964) 2023-09-11 10:36:34 +08:00
ZZK
fa0ea00bbf Support Weightonly in LLM Inference (#6799)
* add dyquant transformer

* add dyquant modeling

* add quant config

* Remove quant utils

* add arguments for quant type

* Refine arguments

* refine

* fix weight attr

* fix attr

* fix random seed attribute

* fix dy2static error

* remove redundant print

* merge weightonly layer to fused_transformer_layer

* merge dyquant modeling in naive llama modeling

* refine predictor

* fix bug

* Add weightonly support

* remove redundant code

* fix format

* revert stop_generation_multi_ends.cu

* Set InferenceModel use safetensors as False

* fix lint

* fix input dtype

---------

Co-authored-by: 骑马小猫 <1435130236@qq.com>
2023-09-10 15:18:26 +08:00
qingzhong1
bed6fe1428 update chat_table (#6973) 2023-09-08 19:48:22 +08:00
w5688414
ea18e6983a Update llm scripts (#6974) 2023-09-08 19:48:05 +08:00
w5688414
c1e4028103 Add chatglm run_mode with recompute (#6972) 2023-09-08 05:44:08 -05:00
qingzhong1
5c7ba6fb59 [Paddle-pipelines] update chatpaper.py (#6968)
* add translation

* add translation

* add translation

* add translation
2023-09-08 18:32:15 +08:00
骑马小猫
d06252bb62 [Function optimization] refactor predictor & add unittest (#6955)
* refactor predictor & add unittest

* fix force-eos test

* update predictor unittest

* update parameters

* remove hard-code pad-token-id
2023-09-08 03:19:23 -05:00
Zhong Hui
af64a72b0c [Trainer] Fix save model for sharding stage3. (#6966) 2023-09-08 15:53:12 +08:00
w5688414
7a6c68af1d Upgrade pipelines to 0.6.1 (#6969) 2023-09-08 02:52:42 -05:00
Yuang Liu
e77ae17c52 [Trainer] Support master grad for sharding stage1 (#6916) 2023-09-08 14:49:42 +08:00
骑马小猫
490c5d46a9 fix force-eos unittest (#6958) 2023-09-08 13:49:23 +08:00
骑马小猫
4401d2893c [Function optimization] update predictor & inference model (#6951)
* update predictor & inference model

* add force-decoding-eos token logit processor

* update generation __init__
2023-09-07 08:15:42 -05:00
qingzhong1
a6e3ec7c0e [Paddle-pipelines] modify chatpaper.py (#6949)
* update ui

* update ui_1
2023-09-07 17:57:17 +08:00
lugimzzz
694c0bc9b4 add quant save (#6937) 2023-09-07 03:11:08 -05:00
Ting Liu
a7754b01f2 opt support multi gpu (#6943)
* opt support multi gpu

* remove low mem flag

* bug fix, lm_head initialization
2023-09-07 03:10:23 -05:00
liuzhenhai93
cdba8526a0 [Trainer] Support segment parallel group. (#6946) 2023-09-07 15:32:37 +08:00
w5688414
adee5a5251 Add intokens support for chatglm2 (#6941) 2023-09-07 01:24:20 -05:00
Zhong Hui
deeeb13bf0 change .numpy to cpu().numpy() (#6940) 2023-09-07 11:38:32 +08:00
w5688414
22d69688fc Add llama bloomz benchmark (#6911)
* Add llama bloomz benchmark

* restore prepare.sh

* rename bloom

* rename bloomz

* Add requirements

* rename bloomz chatglm scripts

* Update mode to recompute

---------

Co-authored-by: qingzhong1 <zhongq1234@126.com>
2023-09-06 22:22:27 -05:00
周周周
294df07ea6 [Paddle Inference]support miniGPT4's second part dy2st (#6905)
* support miniGPT4

* remove some useless code

* move some function to modeling.py
commit

* 1->self.config.bos_token_id

* remove useless comment

* huifu

* move prepare_input_ids_for_generation to modeling

* LlamaForMiniGPT4InferenceModel

* use model_type
2023-09-07 10:05:33 +08:00
qingzhong1
579d1f947a modify chatpaper (#6935)
* modify chatpaper_1

* modify history
2023-09-06 20:13:49 +08:00
骑马小猫
c59f161920 [New features] Add no bad words logit processor (#6932)
* use model_type to control model-intialization

* add no-bad-words
2023-09-06 04:46:17 -05:00
Ruibin Cheung
ba2a788cff [Feature] profiler utils add record_shapes option (#6871) 2023-09-06 17:11:22 +08:00
qingzhong1
5fec2f4d4a [Paddle-pipelines] update chat_paper.py (#6925)
* update ui

* modify chat_paper.py

* modify chat_paper.py

* modify chat_paper_1.py
2023-09-06 03:05:26 -05:00
lugimzzz
3aca6d500a [llm]rename tipc (#6931)
* rename tipc

* update run_mode
2023-09-06 01:49:56 -05:00
Sijun He
e234892a42 Add _pad to qwen tokenizer (#6930)
* qwen _pad

* styles

---------

Co-authored-by: qingzhong1 <zhongq1234@126.com>
2023-09-06 14:23:56 +08:00
Ting Liu
b34420e4b3 fix empty list indices (#6927)
* fix empty list indices

* code refinement
2023-09-05 23:09:07 -05:00
Ting Liu
e183825ca7 pretrainedModel add gconfig (#6915)
* pretrainedModel add gconfig

* max/min_new_token, bug fix

* deprecate generation_utils

* code refinement

* code refinement
2023-09-05 08:05:12 -05:00
Ruibin Cheung
5fe97bd248 [Typo] fix script and docs typo (#6879) 2023-09-05 08:02:01 -05:00
Yuang Liu
63f654bebc for pp_recompute_interval (#6922) 2023-09-05 07:51:32 -05:00
lugimzzz
b97138aca0 [llm]fix generation evaluation (#6924)
* fix generation

* update

* fix
2023-09-05 07:51:03 -05:00
骑马小猫
8a844d2a21 use model_type to control model-intialization (#6923) 2023-09-05 19:40:39 +08:00
w5688414
116c71ca9c Add llama alibi intokens support (#6921)
* Fix llama alibi attention mask

* Add Baichuan
2023-09-05 04:52:08 -05:00
DrownFish19
0283a6b7c1 [FG] Update FG for latest paddle and cuda (#6812)
* fix FG for new paddle and cuda env
2023-09-05 17:41:26 +08:00
骑马小猫
3a9d41b0db fix next-tokens after update_model_kwargs_for_generation (#6919) 2023-09-05 17:11:07 +08:00
ZZK
19a9207b64 Add LLM benchmark scripts (#6906)
* add benchmark

* fix decode length bug and update stop generate custom ops

* refine comment

* remove annotation
2023-09-05 15:00:35 +08:00
lugimzzz
77443ffc1c [llm]support get last checkpoint (#6914)
* add find last checkpoint

* add intro

* fix quant

* delete overwrite
2023-09-04 22:19:15 +08:00
Yuang Liu
30716e892e add flag (#6910) 2023-09-04 03:00:18 -05:00
Sijun He
59b2bd0e1e remove triage issue workflow (#6907) 2023-09-04 01:34:14 -05:00
DrownFish19
88e90ef8da [GPT3 & LLaMA] Fix collate_data (#6869)
* fix collate_data
2023-09-04 14:22:02 +08:00
西瓜
c765bb2ef7 GenerationConfig, logits_process unittests, streamer(unittests) (#6855)
* GenerationConfig, logits_process unittests

* lisence, comment

* use stopping_criteria in generate

* docstring, hint, code adjustment

* group bs bug fix

* d2s unittest close, bug fix

* cpu dtype matching fix

* disable warning temporary
2023-09-03 23:28:05 -05:00
5379 changed files with 939001 additions and 303360 deletions

View File

@@ -71,7 +71,7 @@ RE_SHEBANG = re.compile(r"^[ \t\v]*#[ \t]?\!")
def _check_copyright(path):
head=[]
try:
with open(path) as f:
with open(path, encoding="utf-8") as f:
head = [next(f) for x in range(4)]
except StopIteration:
pass

View File

@@ -1,4 +1,18 @@
<!-- Demo: https://github.com/PaddlePaddle/PaddleNLP/pull/26 -->
#### Before submitting
- [ ] Lint code. If there are lint issues, please format the code first.
```shell
# Install and register `pre-commit` in the project folder
pip install pre-commit && pre-commit install
# Process previous code files separately
pre-commit run --file XXXX.py
```
- [ ] Add test cases into `tests` folder. If there are codecov issues, please add tests cases first.
### PR types
<!-- One of [ New features | Bug fixes | Function optimization | Performance optimization | Breaking changes | Others ] -->

13
.github/codecov.yml vendored
View File

@@ -1,8 +1,13 @@
codecov:
notify:
wait_for_ci: false
coverage:
status:
project:
default:
informational: true
default:
target: 58% # overall project Coverage
threshold: 1% # Allow the coverage to drop by 1%, and posting a success status.
patch:
default:
informational: true
default:
target: 80% # lines adjusted Coverage < 80% CI will fail

View File

@@ -1,48 +0,0 @@
name: FastTokenizer
on:
push:
paths:
- 'fast_tokenizer/*'
pull_request:
paths:
- 'fast_tokenizer/*'
jobs:
fast_tokenizer_cpp:
name: fast_tokenizer_cpp
runs-on: ubuntu-22.04
permissions:
pull-requests: write
contents: read
id-token: write
steps:
- uses: actions/checkout@v3
- name: compile
working-directory: ./fast_tokenizer
run: make fast_tokenizer_cpp_compile
- name: test
working-directory: ./fast_tokenizer
run: make fast_tokenizer_cpp_test
fast_tokenizer_python38:
name: fast_tokenizer_python38
runs-on: ubuntu-22.04
permissions:
pull-requests: write
contents: read
id-token: write
steps:
- uses: actions/checkout@v3
- uses: actions/setup-python@v1
with:
python-version: 3.8
- name: install
working-directory: ./fast_tokenizer
run: make fast_tokenizer_python_install
- name: compile
working-directory: ./fast_tokenizer
run: make fast_tokenizer_python_compile
- name: test
working-directory: ./fast_tokenizer
run: make fast_tokenizer_python_test

View File

@@ -21,7 +21,7 @@ jobs:
fi
- uses: actions/setup-python@v4
with:
python-version: 3.8
python-version: '3.10'
cache: 'pip' # caching pip dependencies
- name: Install dependencies
run: |

View File

@@ -1,21 +0,0 @@
name: Label New issues
on:
issues:
types:
- reopened
- opened
jobs:
label_issues:
runs-on: ubuntu-20.04
permissions:
issues: write
steps:
- uses: actions/github-script@v6
with:
script: |
github.rest.issues.addLabels({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
labels: ["triage"]
})

View File

@@ -3,10 +3,10 @@ name: Pipelines-Test
on:
push:
paths:
- 'pipelines/*'
- 'slm/pipelines/*'
pull_request:
paths:
- 'pipelines/*'
- 'slm/pipelines/*'
jobs:
@@ -17,14 +17,14 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: 3.8
python-version: '3.10'
cache: 'pip' # caching pip dependencies
- name: Install dependencies
working-directory: ./pipelines
working-directory: ./slm/pipelines
run: |
python -m pip install --upgrade pip
make install
pip install -r tests/requirements.txt
- name: run the command
working-directory: ./pipelines
working-directory: ./slm/pipelines
run: make test

View File

@@ -21,7 +21,7 @@ jobs:
- uses: actions/checkout@v2
- uses: actions/setup-python@v1
with:
python-version: 3.8
python-version: '3.10'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
@@ -35,14 +35,14 @@ jobs:
- name: Check Branch
id: check-branch
run: |
if [[ ${{ github.ref }} =~ ^refs/heads/(develop)$ ]]; then
if [[ ${{ github.ref }} =~ ^refs/tags/v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
echo "match=true" >> $GITHUB_OUTPUT
fi # See: https://stackoverflow.com/a/58869470/1123955
- name: Is A Publish Branch
if: steps.check-branch.outputs.match == 'true' && steps.should-deploy.outputs.should_deploy == 'true'
env:
TWINE_USERNAME: paddle-dev
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{ secrets.paddlenlp }}
PACKAGE: ${{ inputs.package }}
PADDLENLP_STABLE_VERSION: "true"

View File

@@ -14,7 +14,7 @@ jobs:
- uses: actions/checkout@v3
- uses: actions/setup-python@v4
with:
python-version: 3.8
python-version: '3.10'
cache: 'pip' # caching pip dependencies
- name: Install dependencies
run: |
@@ -24,4 +24,6 @@ jobs:
- name: run the command
run: make test
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
uses: codecov/codecov-action@v4
env:
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}

19
.gitignore vendored
View File

@@ -123,4 +123,21 @@ FETCH_HEAD
# vscode
.vscode
./ppdiffusers/ppdiffusers/version.py
./ppdiffusers/ppdiffusers/version.py
# third party
csrc/third_party/
dataset/
output/
# gen codes
autogen/
# cutlass kernel
!csrc/gpu/cutlass_kernels/gemm/collective/builders
#fp8
ops/csrc/fp8/deep_gemm/include/cutlass
ops/csrc/fp8/deep_gemm/include/cute

6
.gitmodules vendored Normal file
View File

@@ -0,0 +1,6 @@
[submodule "csrc/third_party/cutlass"]
path = csrc/third_party/cutlass
url = https://github.com/NVIDIA/cutlass.git
[submodule "csrc/third_party/nlohmann_json"]
path = csrc/third_party/nlohmann_json
url = https://github.com/nlohmann/json.git

View File

@@ -1,4 +1,4 @@
exclude: 'model_zoo/gpt-3'
exclude: 'slm/model_zoo/gpt-3;csrc/third_party'
repos:
# For Python files
- repo: https://github.com/psf/black.git
@@ -44,3 +44,30 @@ repos:
entry: python .copyright.hook
language: system
files: \.(c|cc|cxx|cpp|cu|h|hpp|hxx|proto|xpu|kps|py|sh)$
# For Markdown files
- repo: local
hooks:
- id: add-spaces-between-chinese-and-english
name: Add spaces between Chinese and English characters
entry: python scripts/codestyle/check_spaces.py
language: python
files: \.(md|markdown)$
pass_filenames: true
# For dead links
- repo: local
hooks:
- id: check-dead-links
name: Check dead links
entry: python scripts/codestyle/check_dead_links.py
language: python
files: \.(md|markdown|rst)$
pass_filenames: true
- repo: local
hooks:
- id: clang-format
name: clang-format
description: Format files with ClangFormat.
entry: bash ./tools/codestyle/clang_format.sh -i
language: system
files: \.(c|cc|cxx|cpp|cu|h|hpp|hxx|xpu|kps)$

View File

@@ -7,7 +7,7 @@ version: 2
build:
os: "ubuntu-20.04"
tools:
python: "3.8"
python: "3.10"
submodules:
include: all

View File

@@ -9,30 +9,30 @@
我们欢迎不同的向`PaddleNLP`做出贡献的方式,例如:
- 修复已知的Issue
- 提交新的Issue,例如提出功能需求或者bug报告
- 修复已知的 Issue
- 提交新的 Issue,例如提出功能需求或者 bug 报告
- 实现新的模型结构
如果您不知道从哪里开始,请查看Issues板块中的`Good First Issue`标签。它为您提供一个对初学者友好的已知Issue列表,可以降低贡献的门槛,帮助您开始为开源做出贡献。您只需在您想处理的Issue中告知我们您想负责此Issue即可。
如果您不知道从哪里开始,请查看 Issues 板块中的`Good First Issue`标签。它为您提供一个对初学者友好的已知 Issue 列表,可以降低贡献的门槛,帮助您开始为开源做出贡献。您只需在您想处理的 Issue 中告知我们您想负责此 Issue 即可。
## 开发流程
PaddleNLP 使用 [Git 分支模型](http://nvie.com/posts/a-successful-git-branching-model/)。对于常见的开源贡献,我们有以下的贡献流程:
#### 1. Fork
### 1. Fork
因为PaddleNLP的开发社区一直在发展,如果每位贡献者都直接向官方Repo提交commit将会难以管理。因此,请从您的分支中提交 Pull Requests。建议您通过GitHub的[“Fork”按钮](https://help.github.com/articles/fork-a-repo/)来创建您的Fork分支。
因为 PaddleNLP 的开发社区一直在发展,如果每位贡献者都直接向官方 Repo 提交 commit 将会难以管理。因此,请从您的分支中提交 Pull Requests。建议您通过 GitHub 的[“Fork”按钮](https://help.github.com/articles/fork-a-repo/)来创建您的 Fork 分支。
#### 2. Clone
### 2. Clone
请运行一下命令将您的分支clone到本地
请运行一下命令将您的分支 clone 到本地
```bash
git clone https://github.com/<your-github-account>/PaddleNLP
cd PaddleNLP
```
#### 3. 创建本地开发分支
### 3. 创建本地开发分支
对于添加新功能或修复错误等日常工作,请在开发前创建您的本地开发分支:
@@ -40,7 +40,8 @@ PaddleNLP 使用 [Git 分支模型](http://nvie.com/posts/a-successful-git-branc
git checkout -b my-cool-feature
```
#### 4. 配置开发环境
### 4. 配置开发环境
在开始编码之前,您需要设置开发环境。我们强烈建议您在虚拟环境中进行所有开发,例如[venv](https://docs.python.org/3/library/venv.html)或[conda](https://docs.conda.io/en/latest/)。
请您设置并激活虚拟环境后,运行以下命令:
@@ -54,8 +55,7 @@ PaddleNLP 使用 [Git 分支模型](http://nvie.com/posts/a-successful-git-branc
如果在虚拟环境中已经安装 `PaddleNLP` ,请使用 `pip uninstall paddlenlp` 将其删除,然后以可编辑模式重新安装它
`pip install -e .`
#### 5. 开发
### 5. 开发
当您开发时,请确保您新增的代码会被单元测试所覆盖。我们所有的单元测试都可以在 `tests` 目录下找到。
您可以修改现有单元测试以覆盖新功能,也可以从头开始创建新测试。
@@ -65,13 +65,13 @@ PaddleNLP 使用 [Git 分支模型](http://nvie.com/posts/a-successful-git-branc
pytest tests/<test_to_run>.py
```
#### 6. Commit
### 6. Commit
我们使用 [`pre-commit`](http://pre-commit.com/)工具(包括[black](https://black.readthedocs.io/en/stable/)、[isort](https:/ /pycqa.github.io/isort/) 和
[flake8](https://flake8.pycqa.org/en/latest/))来检查每次提交中的代码和文档的风格。当你运行 `git commit` 时,你会看到
类似于以下内容:
```
```text
➜ (my-virtual-env) git commit -m "commiting my cool feature"
black....................................................................Passed
isort....................................................................Passed
@@ -89,7 +89,8 @@ PaddleNLP 使用 [Git 分支模型](http://nvie.com/posts/a-successful-git-branc
```
但大多数时候事情并没有那么顺利。当您的代码或文档不符合标准时,`pre-commit` 检查将失败。
```
```text
➜ (my-virtual-env) git commit -m "commiting my cool feature"
black....................................................................Passed
isort....................................................................Failed
@@ -112,34 +113,34 @@ PaddleNLP 使用 [Git 分支模型](http://nvie.com/posts/a-successful-git-branc
```
我们的工具将自动修复大部分样式错误,但是有些错误需要手动解决。幸运的是,错误信息一般通俗易懂,很容易修复。
解决错误后,您可以再次运行 git add <files> 和 git commit ,这将再次触发 pre-commit 。
解决错误后,您可以再次运行 `git add <files>` 和 `git commit`,这将再次触发 pre-commit 。
一旦 pre-commit 检查通过,您就可以推送代码了。
[Google][http://google.com/] 或 [StackOverflow](https://stackoverflow.com/) 是帮助您了解代码风格错误的好工具。
[Google](https://google.com/) 或 [StackOverflow](https://stackoverflow.com/) 是帮助您了解代码风格错误的好工具。
如果您仍然无法弄清楚,请不要担心。您可以使用 `git commit -m "style error" --no-verify` 提交,我们很乐意在您创建 Pull Request 后帮助您。
#### 7. git pull与代码冲突
### 7. git pull 与代码冲突
有经验的 Git 用户经常从官方Repo中git pull。因为这样子他们会及早注意到与其他人的代码冲突,并且让代码冲突更容易解决
有经验的 Git 用户经常从官方 Repo 中 git pull。因为这样子他们会及早注意到与其他人的代码冲突,并且让代码冲突更容易解决
```bash
git remote add upstream https://github.com/PaddlePaddle/PaddleNLP
git pull upstream develop
```
#### 8. git push与提交Pull Request
### 8. git push 与提交 Pull Request
您可以将您的本地开发分支中的工作 push 到您的fork的分支中:
您可以将您的本地开发分支中的工作 push 到您的 fork 的分支中:
```bash
git push origin my-cool-stuff
```
git push之后,您可以提交Pull Request,请求[官方repo](https://github.com/PaddlePaddle/PaddleNLP) 采纳您的开发工作。请您依照[这些步骤](https://help.github.com/articles/creating-a-pull-request/)创建Pull Request。
git push 之后,您可以提交 Pull Request,请求[官方 repo](https://github.com/PaddlePaddle/PaddleNLP) 采纳您的开发工作。请您依照[这些步骤](https://help.github.com/articles/creating-a-pull-request/)创建 Pull Request。
#### 9. 删除已经合入的本地和远程分支
### 9. 删除已经合入的本地和远程分支
为了保持您本地的工作区和fork分支的干净整洁,建议您在Pull Request合入之后删除本地的残余分支:
为了保持您本地的工作区和 fork 分支的干净整洁,建议您在 Pull Request 合入之后删除本地的残余分支:
```bash
git push origin my-cool-stuff
@@ -148,10 +149,10 @@ PaddleNLP 使用 [Git 分支模型](http://nvie.com/posts/a-successful-git-branc
git branch -d my-cool-stuff
```
## 代码Review
## 代码 Review
- 在您的Pull Request能够顺利通过本地测试以及CI的情况下,您可以在Pull Request中 @ 相关的Reviewer,提醒他们尽快对您的Pull Request进行Review。
- 在您的 Pull Request 能够顺利通过本地测试以及 CI 的情况下,您可以在 Pull Request 中 @ 相关的 Reviewer,提醒他们尽快对您的 Pull Request 进行 Review。
- 请处理Reviewer的每一条评论。如果您已按照评论修改,请回复“完成”;否则,可以在评论下展开讨论。
- 请处理 Reviewer 的每一条评论。如果您已按照评论修改,请回复“完成”;否则,可以在评论下展开讨论。
- 如果您不希望您的Reviewer被电子邮件通知淹没,您可以[批量回复](https://help.github.com/articles/reviewing-proposed-changes-in-a-pull-request/)。
- 如果您不希望您的 Reviewer 被电子邮件通知淹没,您可以[批量回复](https://help.github.com/articles/reviewing-proposed-changes-in-a-pull-request/)。

View File

@@ -37,6 +37,7 @@ test: unit-test
unit-test:
PYTHONPATH=$(shell pwd) pytest -v \
-n auto \
--retries 1 --retry-delay 1 \
--durations 20 \
--cov paddlenlp \
--cov-report xml:coverage.xml
@@ -45,6 +46,7 @@ unit-test:
.PHONY: install
install:
pip install --pre paddlepaddle -i https://www.paddlepaddle.org.cn/packages/nightly/cpu/
pip install -r requirements-dev.txt
pip install -r requirements.txt
pip install -r paddlenlp/experimental/autonlp/requirements.txt

463
README.md
View File

@@ -7,7 +7,7 @@
------------------------------------------------------------------------------------------
<p align="center">
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache%202-dfd.svg"></a>
<a href="https://paddlenlp.readthedocs.io/en/latest/?badge=latest"><img src="https://readthedocs.org/projects/paddlenlp/badge/?version=latest">
<a href="https://github.com/PaddlePaddle/PaddleNLP/releases"><img src="https://img.shields.io/github/v/release/PaddlePaddle/PaddleNLP?color=ffa"></a>
<a href=""><img src="https://img.shields.io/badge/python-3.7+-aff.svg"></a>
<a href=""><img src="https://img.shields.io/badge/os-linux%2C%20win%2C%20mac-pink.svg"></a>
@@ -16,35 +16,174 @@
<a href="https://pypi.org/project/paddlenlp/"><img src="https://img.shields.io/pypi/dm/paddlenlp?color=9cf"></a>
<a href="https://github.com/PaddlePaddle/PaddleNLP/issues"><img src="https://img.shields.io/github/issues/PaddlePaddle/PaddleNLP?color=9cc"></a>
<a href="https://github.com/PaddlePaddle/PaddleNLP/stargazers"><img src="https://img.shields.io/github/stars/PaddlePaddle/PaddleNLP?color=ccf"></a>
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache%202-dfd.svg"></a>
</p>
<h4 align="center">
<a href=#特性> 特性 </a> |
<a href=#模型支持> 模型支持 </a> |
<a href=#安装> 安装 </a> |
<a href=#快速开始> 快速开始 </a> |
<a href=#特性> 特性 </a> |
<a href=#社区交流> 社区交流 </a>
</h4>
**PaddleNLP**是一款**简单易用**且**功能强大**的自然语言处理和大语言模型(LLM)开发库。聚合业界**优质预训练模型**并提供**开箱即用**的开发体验,覆盖NLP多场景的模型库搭配**产业实践范例**可满足开发者**灵活定制**的需求。
**PaddleNLP**是一款基于飞桨深度学习框架的大语言模型(LLM)开发套件,支持在多种硬件上进行高效的大模型训练、无损压缩以及高性能推理。PaddleNLP 具备**简单易用**和**性能极致**的特点,致力于助力开发者实现高效的大模型产业级应用。
<a href="https://trendshift.io/repositories/2246" target="_blank"><img src="https://trendshift.io/api/badge/repositories/2246" alt="PaddlePaddle%2FPaddleNLP | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
## News 📢
* **2023.8.15 [PaddleNLP v2.6](https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v2.6.0)**: 发布[全流程大模型工具链](./llm),涵盖预训练,精调,压缩,推理以及部署等各个环节,为用户提供端到端的大模型方案和一站式的开发体验;内置[4D并行分布式Trainer](./docs/trainer.md),[高效微调算法LoRA/Prefix Tuning](./llm#33-lora), [自研INT8/INT4量化算法](./llm#6-量化)等等;全面支持[LLaMA 1/2](./llm/llama), [BLOOM](.llm/bloom), [ChatGLM 1/2](./llm/chatglm), [GLM](./llm/glm), [OPT](./llm/opt)等主流大模型
* **2025.03.12 [PaddleNLP v3.0 Beta4](https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v3.0.0-beta4)**:全面支持 DeepSeek V3/R1/R1-Distill, 及QwQ-32B等热门思考模型。**DeepSeek V3/R1完整版支持FP8、INT8、4-bit量化推理,MTP投机解码**。单机FP8推理输出超**1000 tokens/s**; 4-bit推理输出超**2100 tokens/s**! 发布新版推理部署镜像,热门模型[一键部署](https://paddlenlp.readthedocs.io/zh/latest/llm/server/docs/general_model_inference.html)。推理部署[使用文档](https://paddlenlp.readthedocs.io/zh/latest/llm/docs/predict/index.html)全面更新,体验全面提升!自研下一代通用信息抽取模型 PP-UIE [全新发布](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/application/information_extraction),支持8K长度信息抽取。新增大模型 Embedding 训练,支持INF-CL超大batch size训练。新增[MergeKit](https://paddlenlp.readthedocs.io/zh/latest/llm/docs/mergekit.html)模型融合工具,缓解对齐代价。低资源训练全面优化,16G小显存可以流畅训练。
* **2025.03.06 PaddleNLP 现已支持 Qwen/QwQ-32B 模型**: 其模型参数仅有 32B,但其数学推理、编程能力和通用能力可与具备 671B 参数(其中 37B 被激活)的 DeepSeek-R1 媲美。借助 PaddleNLP 3.0套件,现可实现多种并行策略[微调训练](./llm/README.md)、[高性能推理、低比特量化](./llm/docs/predict/qwen.md)和[服务化部署](./llm/server/README.md)。
* **2025.02.10 PaddleNLP 现已支持 DeepSeek-R1系列模型,[在线使用](https://aistudio.baidu.com/projectdetail/8775758)**:依托全新的 PaddleNLP 3.0套件,DeepSeek-R1系列模型现已全面支持。凭借数据并行、数据分组切分并行、模型并行、流水线并行以及专家并行等一系列先进的分布式训练能力,结合 Paddle 框架独有的列稀疏注意力掩码表示技术——FlashMask 方法,DeepSeek-R1系列模型在训练过程中显著降低了显存消耗,同时取得了卓越的训练性能提升。
<details><summary> <b>点击展开</b> </summary><div>
* **2025.02.20 🔥🔥《PP-UIE 信息抽取智能引擎全新升级》** 强化零样本学习能力,支持极少甚至零标注数据实现高效冷启动与迁移学习,显著降低数据标注成本;具备处理长文本能力,支持 8192 个 Token 长度文档信息抽取,实现跨段落识别关键信息,形成完整理解;提供完整可定制化的训练和推理全流程,训练效率相较于 LLama-Factory 实现了1.8倍的提升。
2月26日(周三)19:00为您深度解析全新 PP-UIE 技术方案及在部署方面的功能、优势与技巧。报名链接:https://www.wjx.top/vm/mBKC6pb.aspx?udsid=606418
* **2024.12.16 [PaddleNLP v3.0 Beta3](https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v3.0.0-beta3)**:大模型功能全新升级,新增了 Llama-3.2、DeepSeekV2模型,升级了 TokenizerFast,快速分词,重构了 SFTTrainer,一键开启 SFT 训练。此外,PaddleNLP 还支持了优化器状态的卸载和重载功能,实现了精细化的重新计算,训练性能提升7%。在 Unified Checkpoint 方面,进一步优化了异步保存逻辑,新增 Checkpoint 压缩功能,可节省78.5%存储空间。
最后,在大模型推理方面,升级 Append Attention,支持了 FP8量化,支持投机解码。
* **2024.12.13 📚《飞桨大模型套件 Unified Checkpoint 技术》**,加速模型存储95%,节省空间78%。支持全分布式策略调整自适应转换,提升模型训练的灵活性与可扩展性。训练-压缩-推理统一存储协议,无需手动转换提升全流程体验。Checkpoint 无损压缩结合异步保存,实现秒级存储并降低模型存储成本。适用于智能制造、指挥交通、医疗健康、金融服务等产业实际场景。12月24日(周二)19:00直播为您详细解读该技术如何优化大模型训练流程。报名链接:https://www.wjx.top/vm/huZkHn9.aspx?udsid=787976
* **2024.11.28 📚《FlashRAG-Paddle | 基于 PaddleNLP 的高效开发与评测 RAG 框架》**,为文本更快更好构建准确嵌入表示、加速推理生成速度。PaddleNLP 支持超大 Batch 嵌入表示学习与多硬件高性能推理,涵盖 INT8/INT4量化技术及多种高效注意力机制优化与 TensorCore 深度优化。内置全环节算子融合技术,使得 FlashRAG 推理性能相比 transformers 动态图提升70%以上,结合检索增强知识输出结果更加准确,带来敏捷高效的使用体验。直播时间:12月3日(周二)19:00。报名链接:https://www.wjx.top/vm/eaBa1vA.aspx?udsid=682361
* **2024.08.08 📚《飞桨产业级大语言模型开发利器 PaddleNLP 3.0 重磅发布》**,训压推全流程贯通,主流模型全覆盖。大模型自动并行,千亿模型训推全流程开箱即用。提供产业级高性能精调与对齐解决方案,压缩推理领先,多硬件适配。覆盖产业级智能助手、内容创作、知识问答、关键信息抽取等应用场景。直播时间:8月22日(周四)19:00。报名链接:https://www.wjx.top/vm/Y2f7FFY.aspx?udsid=143844
* **2024.06.27 [PaddleNLP v3.0 Beta](https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v3.0.0-beta0)**:拥抱大模型,体验全升级。统一大模型套件,实现国产计算芯片全流程接入;全面支持飞桨4D 并行配置、高效精调策略、高效对齐算法、高性能推理等大模型产业级应用流程;自研极致收敛的 RsLoRA+算法、自动扩缩容存储机制 Unified Checkpoint 和通用化支持的 FastFFN、FusedQKV 助力大模型训推;主流模型持续支持更新,提供高效解决方案。
* **2024.04.24 [PaddleNLP v2.8](https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v2.8.0)**:自研极致收敛的 RsLoRA+算法,大幅提升 PEFT 训练收敛速度以及训练效果;引入高性能生成加速到 RLHF PPO 算法,打破 PPO 训练中生成速度瓶颈,PPO 训练性能大幅领先。通用化支持 FastFFN、FusedQKV 等多个大模型训练性能优化方式,大模型训练更快、更稳定。
</div></details>
## 特性
### <a href=#多硬件训推一体> 🔧 多硬件训推一体 </a>
支持英伟达 GPU、昆仑 XPU、昇腾 NPU、燧原 GCU 和海光 DCU 等多个硬件的大模型和自然语言理解模型训练和推理,套件接口支持硬件快速切换,大幅降低硬件切换研发成本。
当前支持的自然语言理解模型:[多硬件自然语言理解模型列表](./docs/model_zoo/model_list_multy_device.md)
### <a href=#高效易用的预训练> 🚀 高效易用的预训练 </a>
支持纯数据并行策略、分组参数切片的数据并行策略、张量模型并行策略和流水线模型并行策略的4D 高性能训练,Trainer 支持分布式策略配置化,降低复杂分布式组合带来的使用成本;
[Unified Checkpoint 大模型存储工具](./llm/docs/unified_checkpoint.md)可以使得训练断点支持机器资源动态扩缩容恢复。此外,异步保存,模型存储可加速95%,Checkpoint 压缩,可节省78.5%存储空间。
### <a href=#高效精调> 🤗 高效精调 </a>
精调算法深度结合零填充数据流和 [FlashMask](./llm/docs/flashmask.md) 高性能算子,降低训练无效数据填充和计算,大幅提升精调训练吞吐。
### <a href=#无损压缩和高性能推理> 🎛️ 无损压缩和高性能推理 </a>
大模型套件高性能推理模块内置动态插入和全环节算子融合策略,极大加快并行推理速度。底层实现细节封装化,实现开箱即用的高性能并行推理能力。
## 文档
更多详细文档, 请访问 [PaddleNLP Documentation](https://paddlenlp.readthedocs.io/).
------------------------------------------------------------------------------------------
## 模型支持
* 模型参数已支持 LLaMA 系列、Baichuan 系列、Bloom 系列、ChatGLM 系列、Gemma 系列、Mistral 系列、OPT 系列和 Qwen 系列,详细列表👉【LLM】模型参数支持列表如下:
| 模型系列 | 模型名称 |
|:-------------------------------------------------------------------------------------------------------:|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [PP-UIE](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/application/information_extraction) | paddlenlp/PP-UIE-0.5B, paddlenlp/PP-UIE-1.5B, paddlenlp/PP-UIE-7B, paddlenlp/PP-UIE-14B |
| [LLaMA](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/llama) | facebook/llama-7b, facebook/llama-13b, facebook/llama-30b, facebook/llama-65b |
| [Llama2](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/llama) | meta-llama/Llama-2-7b, meta-llama/Llama-2-7b-chat, meta-llama/Llama-2-13b, meta-llama/Llama-2-13b-chat, meta-llama/Llama-2-70b, meta-llama/Llama-2-70b-chat |
| [Llama3](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/llama) | meta-llama/Meta-Llama-3-8B, meta-llama/Meta-Llama-3-8B-Instruct, meta-llama/Meta-Llama-3-70B, meta-llama/Meta-Llama-3-70B-Instruct |
| [Llama3.1](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/llama) | meta-llama/Meta-Llama-3.1-8B, meta-llama/Meta-Llama-3.1-8B-Instruct, meta-llama/Meta-Llama-3.1-70B, meta-llama/Meta-Llama-3.1-70B-Instruct, meta-llama/Meta-Llama-3.1-405B, meta-llama/Meta-Llama-3.1-405B-Instruct, meta-llama/Llama-Guard-3-8B |
| [Llama3.2](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/llama) | meta-llama/Llama-3.2-1B, meta-llama/Llama-3.2-1B-Instruct, meta-llama/Llama-3.2-3B, meta-llama/Llama-3.2-3B-Instruct, meta-llama/Llama-Guard-3-1B |
| [Llama3.3](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/llama) | meta-llama/Llama-3.3-70B-Instruct |
| [Baichuan](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/baichuan) | baichuan-inc/Baichuan-7B, baichuan-inc/Baichuan-13B-Base, baichuan-inc/Baichuan-13B-Chat |
| [Baichuan2](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/baichuan) | baichuan-inc/Baichuan2-7B-Base, baichuan-inc/Baichuan2-7B-Chat, baichuan-inc/Baichuan2-13B-Base, baichuan-inc/Baichuan2-13B-Chat |
| [Bloom](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/bloom) | bigscience/bloom-560m, bigscience/bloom-560m-bf16, bigscience/bloom-1b1, bigscience/bloom-3b, bigscience/bloom-7b1, bigscience/bloomz-560m, bigscience/bloomz-1b1, bigscience/bloomz-3b, bigscience/bloomz-7b1-mt, bigscience/bloomz-7b1-p3, bigscience/bloomz-7b1, bellegroup/belle-7b-2m |
| [ChatGLM](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/chatglm/) | THUDM/chatglm-6b, THUDM/chatglm-6b-v1.1 |
| [ChatGLM2](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/chatglm2) | THUDM/chatglm2-6b |
| [ChatGLM3](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/chatglm2) | THUDM/chatglm3-6b |
| [DeepSeekV2](https://github.com/PaddlePaddle/PaddleNLP/blob/develop/llm/config/deepseek-v2) | deepseek-ai/DeepSeek-V2, deepseek-ai/DeepSeek-V2-Chat, deepseek-ai/DeepSeek-V2-Lite, deepseek-ai/DeepSeek-V2-Lite-Chat, deepseek-ai/DeepSeek-Coder-V2-Base, deepseek-ai/DeepSeek-Coder-V2-Instruct, deepseek-ai/DeepSeek-Coder-V2-Lite-Base, deepseek-ai/DeepSeek-Coder-V2-Lite-Instruct |
| [DeepSeekV3](https://github.com/PaddlePaddle/PaddleNLP/blob/develop/llm/config/deepseek-v2) | deepseek-ai/DeepSeek-V3, deepseek-ai/DeepSeek-V3-Base |
| [DeepSeek-R1](https://github.com/PaddlePaddle/PaddleNLP/blob/develop/llm/config/deepseek-v2) | deepseek-ai/DeepSeek-R1, deepseek-ai/DeepSeek-R1-Zero, deepseek-ai/DeepSeek-R1-Distill-Llama-70B, deepseek-ai/DeepSeek-R1-Distill-Llama-8B, deepseek-ai/DeepSeek-R1-Distill-Qwen-14B, deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B, deepseek-ai/DeepSeek-R1-Distill-Qwen-32B, deepseek-ai/DeepSeek-R1-Distill-Qwen-7B |
| [Gemma](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/gemma) | google/gemma-7b, google/gemma-7b-it, google/gemma-2b, google/gemma-2b-it |
| [Mistral](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/mistral) | mistralai/Mistral-7B-Instruct-v0.3, mistralai/Mistral-7B-v0.1 |
| [Mixtral](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/mixtral) | mistralai/Mixtral-8x7B-Instruct-v0.1 |
| [OPT](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/opt) | facebook/opt-125m, facebook/opt-350m, facebook/opt-1.3b, facebook/opt-2.7b, facebook/opt-6.7b, facebook/opt-13b, facebook/opt-30b, facebook/opt-66b, facebook/opt-iml-1.3b, opt-iml-max-1.3b |
| [Qwen](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/qwen/) | qwen/qwen-7b, qwen/qwen-7b-chat, qwen/qwen-14b, qwen/qwen-14b-chat, qwen/qwen-72b, qwen/qwen-72b-chat, |
| [Qwen1.5](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/qwen/) | Qwen/Qwen1.5-0.5B, Qwen/Qwen1.5-0.5B-Chat, Qwen/Qwen1.5-1.8B, Qwen/Qwen1.5-1.8B-Chat, Qwen/Qwen1.5-4B, Qwen/Qwen1.5-4B-Chat, Qwen/Qwen1.5-7B, Qwen/Qwen1.5-7B-Chat, Qwen/Qwen1.5-14B, Qwen/Qwen1.5-14B-Chat, Qwen/Qwen1.5-32B, Qwen/Qwen1.5-32B-Chat, Qwen/Qwen1.5-72B, Qwen/Qwen1.5-72B-Chat, Qwen/Qwen1.5-110B, Qwen/Qwen1.5-110B-Chat, Qwen/Qwen1.5-MoE-A2.7B, Qwen/Qwen1.5-MoE-A2.7B-Chat |
| [Qwen2](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/qwen/) | Qwen/Qwen2-0.5B, Qwen/Qwen2-0.5B-Instruct, Qwen/Qwen2-1.5B, Qwen/Qwen2-1.5B-Instruct, Qwen/Qwen2-7B, Qwen/Qwen2-7B-Instruct, Qwen/Qwen2-72B, Qwen/Qwen2-72B-Instruct, Qwen/Qwen2-57B-A14B, Qwen/Qwen2-57B-A14B-Instruct |
| [Qwen2-Math](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/qwen/) | Qwen/Qwen2-Math-1.5B, Qwen/Qwen2-Math-1.5B-Instruct, Qwen/Qwen2-Math-7B, Qwen/Qwen2-Math-7B-Instruct, Qwen/Qwen2-Math-72B, Qwen/Qwen2-Math-72B-Instruct, Qwen/Qwen2-Math-RM-72B |
| [Qwen2.5](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/qwen/) | Qwen/Qwen2.5-0.5B, Qwen/Qwen2.5-0.5B-Instruct, Qwen/Qwen2.5-1.5B, Qwen/Qwen2.5-1.5B-Instruct, Qwen/Qwen2.5-3B, Qwen/Qwen2.5-3B-Instruct, Qwen/Qwen2.5-7B, Qwen/Qwen2.5-7B-Instruct, Qwen/Qwen2.5-7B-Instruct-1M, Qwen/Qwen2.5-14B, Qwen/Qwen2.5-14B-Instruct, Qwen/Qwen2.5-14B-Instruct-1M, Qwen/Qwen2.5-32B, Qwen/Qwen2.5-32B-Instruct, Qwen/Qwen2.5-72B, Qwen/Qwen2.5-72B-Instruct |
| [Qwen2.5-Math](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/qwen/) | Qwen/Qwen2.5-Math-1.5B, Qwen/Qwen2.5-Math-1.5B-Instruct, Qwen/Qwen2.5-Math-7B, Qwen/Qwen2.5-Math-7B-Instruct, Qwen/Qwen2.5-Math-72B, Qwen/Qwen2.5-Math-72B-Instruct, Qwen/Qwen2.5-Math-RM-72B |
| [Qwen2.5-Coder](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/qwen/) | Qwen/Qwen2.5-Coder-1.5B, Qwen/Qwen2.5-Coder-1.5B-Instruct, Qwen/Qwen2.5-Coder-7B, Qwen/Qwen2.5-Coder-7B-Instruct |
| [QwQ](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/qwen/) | Qwen/QwQ-32B, Qwen/QwQ-32B-Preview |
| [Yuan2](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/llm/config/yuan/) | IEITYuan/Yuan2-2B, IEITYuan/Yuan2-51B, IEITYuan/Yuan2-102B |
* 4D 并行和算子优化已支持 LLaMA 系列、Baichuan 系列、Bloom 系列、ChatGLM 系列、Gemma 系列、Mistral 系列、OPT 系列和 Qwen 系列,【LLM】模型4D 并行和算子支持列表如下:
| 模型名称/并行能力支持 | 数据并行 | 张量模型并行 | | 参数分片并行 | | | 流水线并行 |
|:---------------------:|:--------:|:------------:|:--------:|:------------:|:------:|:------:|:----------:|
| | | 基础能力 | 序列并行 | stage1 | stage2 | stage3 | |
| Llama | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Qwen | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Qwen1.5 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Qwen2 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Mixtral(moe) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 🚧 |
| Mistral | ✅ | ✅ | 🚧 | ✅ | ✅ | ✅ | 🚧 |
| Baichuan | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Baichuan2 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| ChatGLM | ✅ | ✅ | 🚧 | ✅ | ✅ | ✅ | 🚧 |
| ChatGLM2 | ✅ | 🚧 | 🚧 | ✅ | ✅ | ✅ | 🚧 |
| ChatGLM3 | ✅ | 🚧 | 🚧 | ✅ | ✅ | ✅ | 🚧 |
| Bloom | ✅ | ✅ | 🚧 | ✅ | ✅ | ✅ | 🚧 |
| GPT-2/GPT-3 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| OPT | ✅ | ✅ | 🚧 | ✅ | ✅ | ✅ | 🚧 |
| Gemma | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Yuan2 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 🚧 |
* 大模型预训练、精调(包含 SFT、PEFT 技术)、对齐、量化已支持 LLaMA 系列、Baichuan 系列、Bloom 系列、ChatGLM 系列、Mistral 系列、OPT 系列和 Qwen 系列,【LLM】模型预训练、精调、对齐、量化支持列表如下:
| Model | Pretrain | SFT | LoRA | FlashMask | Prefix Tuning | DPO/SimPO/ORPO/KTO | RLHF | Mergekit | Quantization |
|--------------------------------------------|:--------:|:---:|:----:|:---------:|:-------------:|:------------------:|:----:|:--------:|:------------:|
| [Llama](./llm/config/llama) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| [Qwen](./llm/config/qwen) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 🚧 | ✅ | 🚧 |
| [Mixtral](./llm/config/mixtral) | ✅ | ✅ | ✅ | 🚧 | 🚧 | ✅ | 🚧 | ✅ | 🚧 |
| [Mistral](./llm/config/mistral) | ✅ | ✅ | ✅ | 🚧 | ✅ | ✅ | 🚧 | ✅ | 🚧 |
| [Baichuan/Baichuan2](./llm/config/llama) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | 🚧 | ✅ | ✅ |
| [ChatGLM-6B](./llm/config/chatglm) | ✅ | ✅ | ✅ | 🚧 | ✅ | 🚧 | 🚧 | ✅ | ✅ |
| [ChatGLM2/ChatGLM3](./llm/config/chatglm2) | ✅ | ✅ | ✅ | 🚧 | ✅ | ✅ | 🚧 | ✅ | ✅ |
| [Bloom](./llm/config/bloom) | ✅ | ✅ | ✅ | 🚧 | ✅ | 🚧 | 🚧 | ✅ | ✅ |
| [GPT-3](./llm/config/gpt-3) | ✅ | ✅ | 🚧 | 🚧 | 🚧 | 🚧 | 🚧 | ✅ | 🚧 |
| [OPT](./llm/config/opt) | ✅ | ✅ | ✅ | 🚧 | 🚧 | 🚧 | 🚧 | ✅ | 🚧 |
| [Gemma](./llm/config/gemma) | ✅ | ✅ | ✅ | 🚧 | 🚧 | ✅ | 🚧 | ✅ | 🚧 |
| [Yuan](./llm/config/yuan) | ✅ | ✅ | ✅ | 🚧 | 🚧 | ✅ | 🚧 | ✅ | 🚧 |
* [大模型推理](./llm/docs/predict/inference.md)已支持 LLaMA 系列、Qwen 系列、DeepSeek 系列、Mistral 系列、ChatGLM 系列、Bloom 系列和 Baichuan 系列,支持 Weight Only INT8及 INT4推理,支持 WAC(权重、激活、Cache KV)进行 INT8、FP8量化的推理,【LLM】模型推理支持列表如下:
| 模型名称/量化类型支持 | FP16/BF16 | WINT8 | WINT4 | INT8-A8W8 | FP8-A8W8 | INT8-A8W8C8 |
|:------------------------------------------:|:---------:|:-----:|:-----:|:---------:|:--------:|:-----------:|
| [LLaMA](./llm/docs/predict/llama.md) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| [Qwen](./llm/docs/predict/qwen.md) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| [DeepSeek](./llm/docs/predict/deepseek.md) | ✅ | ✅ | ✅ | 🚧 | ✅ | 🚧 |
| [Qwen-Moe](./llm/docs/predict/qwen.md) | ✅ | ✅ | ✅ | 🚧 | 🚧 | 🚧 |
| [Mixtral](./llm/docs/predict/mixtral.md) | ✅ | ✅ | ✅ | 🚧 | 🚧 | 🚧 |
| ChatGLM | ✅ | ✅ | ✅ | 🚧 | 🚧 | 🚧 |
| Bloom | ✅ | ✅ | ✅ | 🚧 | 🚧 | 🚧 |
| BaiChuan | ✅ | ✅ | ✅ | ✅ | ✅ | 🚧 |
## 安装
### 环境依赖
- python >= 3.7
- paddlepaddle >= 2.5.1
- 如需大模型功能,请使用 paddlepaddle-gpu >= 2.5.1
* python >= 3.8
* paddlepaddle >= 3.0.0rc1
### pip安装
如果您尚未安装 PaddlePaddle,请参考 [飞桨官网](https://www.paddlepaddle.org.cn/) 进行安装。
### pip 安装
```shell
pip install --upgrade paddlenlp
pip install --upgrade paddlenlp==3.0.0b4
```
或者可通过以下命令安装最新 develop 分支代码:
@@ -53,281 +192,87 @@ pip install --upgrade paddlenlp
pip install --pre --upgrade paddlenlp -f https://www.paddlepaddle.org.cn/whl/paddlenlp.html
```
更多关于PaddlePaddle和PaddleNLP安装的详细教程请查看[Installation](./docs/get_started/installation.rst)。
更多关于 PaddlePaddle 和 PaddleNLP 安装的详细教程请查看[Installation](./docs/get_started/installation.rst)。
------------------------------------------------------------------------------------------
## 快速开始
### 大模型文本生成
PaddleNLP提供了方便易用的Auto API,能够快速的加载模型和Tokenizer。这里以使用 `linly-ai/chinese-llama-2-7b` 大模型做文本生成为例:
PaddleNLP 提供了方便易用的 Auto API,能够快速的加载模型和 Tokenizer。这里以使用 `Qwen/Qwen2-0.5B` 模型做文本生成为例:
```python
>>> from paddlenlp.transformers import AutoTokenizer, AutoModelForCausalLM
>>> tokenizer = AutoTokenizer.from_pretrained("linly-ai/chinese-llama-2-7b")
>>> model = AutoModelForCausalLM.from_pretrained("linly-ai/chinese-llama-2-7b", dtype="float16")
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B")
>>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B", dtype="float16")
>>> input_features = tokenizer("你好!请自我介绍一下。", return_tensors="pd")
>>> outputs = model.generate(**input_features, max_length=128)
>>> tokenizer.batch_decode(outputs[0])
['\n你好!我是一个AI语言模型,可以回答你的问题和提供帮助。']
>>> print(tokenizer.batch_decode(outputs[0], skip_special_tokens=True))
['我是一个AI语言模型,我可以回答各种问题,包括但不限于:天气、新闻、历史、文化、科学、教育、娱乐等。请问您有什么需要了解的吗?']
```
### 一键UIE预测
### 大模型预训练
PaddleNLP提供[一键预测功能](./docs/model_zoo/taskflow.md),无需训练,直接输入数据即可开放域抽取结果。这里以信息抽取-命名实体识别任务,UIE模型为例:
```shell
git clone https://github.com/PaddlePaddle/PaddleNLP.git && cd PaddleNLP # 如已clone或下载PaddleNLP可跳过
mkdir -p llm/data && cd llm/data
wget https://bj.bcebos.com/paddlenlp/models/transformers/llama/data/llama_openwebtext_100k.bin
wget https://bj.bcebos.com/paddlenlp/models/transformers/llama/data/llama_openwebtext_100k.idx
cd .. # change folder to PaddleNLP/llm
# 如需使用use_fused_rms_norm=true,需要前往slm/model_zoo/gpt-3/external_ops安装fused_ln
python -u run_pretrain.py ./config/qwen/pretrain_argument_0p5b.json
```
### 大模型 SFT 精调
```shell
git clone https://github.com/PaddlePaddle/PaddleNLP.git && cd PaddleNLP # 如已clone或下载PaddleNLP可跳过
mkdir -p llm/data && cd llm/data
wget https://bj.bcebos.com/paddlenlp/datasets/examples/AdvertiseGen.tar.gz && tar -zxvf AdvertiseGen.tar.gz
cd .. # change folder to PaddleNLP/llm
python -u run_finetune.py ./config/qwen/sft_argument_0p5b.json
```
更多大模型全流程步骤,请参考[飞桨大模型套件](./llm)介绍。
另外我们还提供了快速微调方式, 无需 clone 源代码:
```python
>>> from pprint import pprint
>>> from paddlenlp import Taskflow
from paddlenlp.trl import SFTConfig, SFTTrainer
from datasets import load_dataset
>>> schema = ['时间', '选手', '赛事名称'] # Define the schema for entity extraction
>>> ie = Taskflow('information_extraction', schema=schema)
>>> pprint(ie("2月8日上午北京冬奥会自由式滑雪女子大跳台决赛中中国选手谷爱凌以188.25分获得金牌!"))
[{'时间': [{'end': 6,
'probability': 0.9857378532924486,
'start': 0,
'text': '2月8日上午'}],
'赛事名称': [{'end': 23,
'probability': 0.8503089953268272,
'start': 6,
'text': '北京冬奥会自由式滑雪女子大跳台决赛'}],
'选手': [{'end': 31,
'probability': 0.8981548639781138,
'start': 28,
'text': '谷爱凌'}]}]
dataset = load_dataset("ZHUI/alpaca_demo", split="train")
training_args = SFTConfig(output_dir="Qwen/Qwen2.5-0.5B-SFT", device="gpu")
trainer = SFTTrainer(
args=training_args,
model="Qwen/Qwen2.5-0.5B-Instruct",
train_dataset=dataset,
)
trainer.train()
```
更多PaddleNLP内容可参考:
- [大模型全流程工具链](./llm),包含主流中文大模型的全流程方案。
- [精选模型库](./model_zoo),包含优质预训练模型的端到端全流程使用。
- [多场景示例](./examples),了解如何使用PaddleNLP解决NLP多种技术问题,包含基础技术、系统应用与拓展应用。
- [交互式教程](https://aistudio.baidu.com/aistudio/personalcenter/thirdview/574995),在🆓免费算力平台AI Studio上快速学习PaddleNLP。
更多 PaddleNLP 内容可参考:
* [精选模型库](./slm/model_zoo),包含优质预训练模型的端到端全流程使用。
* [多场景示例](./slm/examples),了解如何使用 PaddleNLP 解决 NLP 多种技术问题,包含基础技术、系统应用与拓展应用。
* [交互式教程](https://aistudio.baidu.com/aistudio/personalcenter/thirdview/574995),在🆓免费算力平台 AI Studio 上快速学习 PaddleNLP。
## 特性
#### <a href=#开箱即用的nlp工具集> 📦 开箱即用的NLP工具集 </a>
#### <a href=#丰富完备的中文模型库> 🤗 丰富完备的中文模型库 </a>
#### <a href=#产业级端到端系统范例> 🎛️ 产业级端到端系统范例 </a>
#### <a href=#高性能分布式训练与推理> 🚀 高性能分布式训练与推理 </a>
### 开箱即用的NLP工具集
Taskflow提供丰富的**📦开箱即用**的产业级NLP预置模型,覆盖自然语言理解与生成两大场景,提供**💪产业级的效果**与**⚡️极致的推理性能**。
![taskflow1](https://user-images.githubusercontent.com/11793384/159693816-fda35221-9751-43bb-b05c-7fc77571dd76.gif)
更多使用方法可参考[Taskflow文档](./docs/model_zoo/taskflow.md)。
### 丰富完备的中文模型库
#### 🀄 业界最全的中文预训练模型
精选 45+ 个网络结构和 500+ 个预训练模型参数,涵盖业界最全的中文预训练模型:既包括文心NLP大模型的ERNIE、PLATO等,也覆盖BERT、GPT、RoBERTa、T5等主流结构。通过`AutoModel` API一键⚡**高速下载**⚡。
```python
from paddlenlp.transformers import *
ernie = AutoModel.from_pretrained('ernie-3.0-medium-zh')
bert = AutoModel.from_pretrained('bert-wwm-chinese')
albert = AutoModel.from_pretrained('albert-chinese-tiny')
roberta = AutoModel.from_pretrained('roberta-wwm-ext')
electra = AutoModel.from_pretrained('chinese-electra-small')
gpt = AutoModelForPretraining.from_pretrained('gpt-cpm-large-cn')
```
针对预训练模型计算瓶颈,可以使用API一键使用文心ERNIE-Tiny全系列轻量化模型,降低预训练模型部署难度。
```python
# 6L768H
ernie = AutoModel.from_pretrained('ernie-3.0-medium-zh')
# 6L384H
ernie = AutoModel.from_pretrained('ernie-3.0-mini-zh')
# 4L384H
ernie = AutoModel.from_pretrained('ernie-3.0-micro-zh')
# 4L312H
ernie = AutoModel.from_pretrained('ernie-3.0-nano-zh')
```
对预训练模型应用范式如语义表示、文本分类、句对匹配、序列标注、问答等,提供统一的API体验。
```python
import paddle
from paddlenlp.transformers import *
tokenizer = AutoTokenizer.from_pretrained('ernie-3.0-medium-zh')
text = tokenizer('自然语言处理')
# 语义表示
model = AutoModel.from_pretrained('ernie-3.0-medium-zh')
sequence_output, pooled_output = model(input_ids=paddle.to_tensor([text['input_ids']]))
# 文本分类 & 句对匹配
model = AutoModelForSequenceClassification.from_pretrained('ernie-3.0-medium-zh')
# 序列标注
model = AutoModelForTokenClassification.from_pretrained('ernie-3.0-medium-zh')
# 问答
model = AutoModelForQuestionAnswering.from_pretrained('ernie-3.0-medium-zh')
```
#### 💯 全场景覆盖的应用示例
覆盖从学术到产业的NLP应用示例,涵盖NLP基础技术、NLP系统应用以及拓展应用。全面基于飞桨核心框架2.0全新API体系开发,为开发者提供飞桨文本领域的最佳实践。
精选预训练模型示例可参考[Model Zoo](./model_zoo),更多场景示例文档可参考[examples目录](./examples)。更有免费算力支持的[AI Studio](https://aistudio.baidu.com)平台的[Notbook交互式教程](https://aistudio.baidu.com/aistudio/personalcenter/thirdview/574995)提供实践。
<details><summary> PaddleNLP预训练模型适用任务汇总(<b>点击展开详情</b>)</summary><div>
| Model | Sequence Classification | Token Classification | Question Answering | Text Generation | Multiple Choice |
| :----------------- | ----------------------- | -------------------- | ------------------ | --------------- | --------------- |
| ALBERT | ✅ | ✅ | ✅ | ❌ | ✅ |
| BART | ✅ | ✅ | ✅ | ✅ | ❌ |
| BERT | ✅ | ✅ | ✅ | ❌ | ✅ |
| BigBird | ✅ | ✅ | ✅ | ❌ | ✅ |
| BlenderBot | ❌ | ❌ | ❌ | ✅ | ❌ |
| ChineseBERT | ✅ | ✅ | ✅ | ❌ | ❌ |
| ConvBERT | ✅ | ✅ | ✅ | ❌ | ✅ |
| CTRL | ✅ | ❌ | ❌ | ❌ | ❌ |
| DistilBERT | ✅ | ✅ | ✅ | ❌ | ❌ |
| ELECTRA | ✅ | ✅ | ✅ | ❌ | ✅ |
| ERNIE | ✅ | ✅ | ✅ | ❌ | ✅ |
| ERNIE-CTM | ❌ | ✅ | ❌ | ❌ | ❌ |
| ERNIE-Doc | ✅ | ✅ | ✅ | ❌ | ❌ |
| ERNIE-GEN | ❌ | ❌ | ❌ | ✅ | ❌ |
| ERNIE-Gram | ✅ | ✅ | ✅ | ❌ | ❌ |
| ERNIE-M | ✅ | ✅ | ✅ | ❌ | ❌ |
| FNet | ✅ | ✅ | ✅ | ❌ | ✅ |
| Funnel-Transformer | ✅ | ✅ | ✅ | ❌ | ❌ |
| GPT | ✅ | ✅ | ❌ | ✅ | ❌ |
| LayoutLM | ✅ | ✅ | ❌ | ❌ | ❌ |
| LayoutLMv2 | ❌ | ✅ | ❌ | ❌ | ❌ |
| LayoutXLM | ❌ | ✅ | ❌ | ❌ | ❌ |
| LUKE | ❌ | ✅ | ✅ | ❌ | ❌ |
| mBART | ✅ | ❌ | ✅ | ❌ | ✅ |
| MegatronBERT | ✅ | ✅ | ✅ | ❌ | ✅ |
| MobileBERT | ✅ | ❌ | ✅ | ❌ | ❌ |
| MPNet | ✅ | ✅ | ✅ | ❌ | ✅ |
| NEZHA | ✅ | ✅ | ✅ | ❌ | ✅ |
| PP-MiniLM | ✅ | ❌ | ❌ | ❌ | ❌ |
| ProphetNet | ❌ | ❌ | ❌ | ✅ | ❌ |
| Reformer | ✅ | ❌ | ✅ | ❌ | ❌ |
| RemBERT | ✅ | ✅ | ✅ | ❌ | ✅ |
| RoBERTa | ✅ | ✅ | ✅ | ❌ | ✅ |
| RoFormer | ✅ | ✅ | ✅ | ❌ | ❌ |
| SKEP | ✅ | ✅ | ❌ | ❌ | ❌ |
| SqueezeBERT | ✅ | ✅ | ✅ | ❌ | ❌ |
| T5 | ❌ | ❌ | ❌ | ✅ | ❌ |
| TinyBERT | ✅ | ❌ | ❌ | ❌ | ❌ |
| UnifiedTransformer | ❌ | ❌ | ❌ | ✅ | ❌ |
| XLNet | ✅ | ✅ | ✅ | ❌ | ✅ |
</div></details>
可参考[Transformer 文档](/docs/model_zoo/index.rst) 查看目前支持的预训练模型结构、参数和详细用法。
### 产业级端到端系统范例
PaddleNLP针对信息抽取、语义检索、智能问答、情感分析等高频NLP场景,提供了端到端系统范例,打通*数据标注*-*模型训练*-*模型调优*-*预测部署*全流程,持续降低NLP技术产业落地门槛。更多详细的系统级产业范例使用说明请参考[Applications](./applications)。
#### 🔍 语义检索系统
针对无监督数据、有监督数据等多种数据情况,结合SimCSE、In-batch Negatives、ERNIE-Gram单塔模型等,推出前沿的语义检索方案,包含召回、排序环节,打通训练、调优、高效向量检索引擎建库和查询全流程。
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168514909-8817d79a-72c4-4be1-8080-93d1f682bb46.gif" width="400">
</div>
更多使用说明请参考[语义检索系统](./applications/neural_search)。
#### ❓ 智能问答系统
基于[🚀RocketQA](https://github.com/PaddlePaddle/RocketQA)技术的检索式问答系统,支持FAQ问答、说明书问答等多种业务场景。
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168514868-1babe981-c675-4f89-9168-dd0a3eede315.gif" width="400">
</div>
更多使用说明请参考[智能问答系统](./applications/question_answering)与[文档智能问答](./applications/document_intelligence/doc_vqa)
#### 💌 评论观点抽取与情感分析
基于情感知识增强预训练模型SKEP,针对产品评论进行评价维度和观点抽取,以及细粒度的情感分析。
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168407260-b7f92800-861c-4207-98f3-2291e0102bbe.png" width="400">
</div>
更多使用说明请参考[情感分析](./applications/sentiment_analysis)。
#### 🎙️ 智能语音指令解析
集成了[PaddleSpeech](https://github.com/PaddlePaddle/PaddleSpeech)和[百度开放平台](https://ai.baidu.com/)的语音识别和[UIE](./model_zoo/uie)通用信息抽取等技术,打造智能一体化的语音指令解析系统范例,该方案可应用于智能语音填单、智能语音交互、智能语音检索等场景,提高人机交互效率。
<div align="center">
<img src="https://user-images.githubusercontent.com/16698950/168589100-a6c6f346-97bb-47b2-ac26-8d50e71fddc5.png" width="400">
</div>
更多使用说明请参考[智能语音指令解析](./applications/speech_cmd_analysis)。
### 高性能分布式训练与推理
#### ⚡ FastTokenizer:高性能文本处理库
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168407921-b4395b1d-44bd-41a0-8c58-923ba2b703ef.png" width="400">
</div>
```python
AutoTokenizer.from_pretrained("ernie-3.0-medium-zh", use_fast=True)
```
为了实现更极致的模型部署性能,安装FastTokenizers后只需在`AutoTokenizer` API上打开 `use_fast=True`选项,即可调用C++实现的高性能分词算子,轻松获得超Python百余倍的文本处理加速,更多使用说明可参考[FastTokenizer文档](./fast_tokenizer)。
#### ⚡️ FastGeneration:高性能生成加速库
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168407831-914dced0-3a5a-40b8-8a65-ec82bf13e53c.gif" width="400">
</div>
```python
model = GPTLMHeadModel.from_pretrained('gpt-cpm-large-cn')
...
outputs, _ = model.generate(
input_ids=inputs_ids, max_length=10, decode_strategy='greedy_search',
use_fast=True)
```
简单地在`generate()`API上打开`use_fast=True`选项,轻松在Transformer、GPT、BART、PLATO、UniLM等生成式预训练模型上获得5倍以上GPU加速,更多使用说明可参考[FastGeneration文档](./fast_generation)。
#### 🚀 Fleet:飞桨4D混合并行分布式训练技术
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168515134-513f13e0-9902-40ef-98fa-528271dcccda.png" width="300">
</div>
更多关于千亿级AI模型的分布式训练使用说明可参考[GPT-3](./examples/language_model/gpt-3)。
------------------------------------------------------------------------------------------
## 社区交流
- 微信扫描二维码并填写问卷,回复小助手关键词(NLP)之后,即可加入交流群领取福利
* 微信扫描二维码并填写问卷,即可加入交流群与众多社区开发者以及官方团队深度交流.
- 与众多社区开发者以及官方团队深度交流。
- 10G重磅NLP学习大礼包!
<div align="center">
<img src="https://user-images.githubusercontent.com/11987277/245085922-0aa68d24-00ff-442e-9c53-2f1e898151ce.png" width="150" height="150" />
</div>
<div align="center">
<img src="https://github.com/user-attachments/assets/3a58cc9f-69c7-4ccb-b6f5-73e966b8051a" width="150" height="150" />
</div>
## Citation
如果PaddleNLP对您的研究有帮助,欢迎引用
如果 PaddleNLP 对您的研究有帮助,欢迎引用
```
```bibtex
@misc{=paddlenlp,
title={PaddleNLP: An Easy-to-use and High Performance NLP Library},
author={PaddleNLP Contributors},
@@ -338,8 +283,8 @@ outputs, _ = model.generate(
## Acknowledge
我们借鉴了Hugging Face的[Transformers](https://github.com/huggingface/transformers)🤗关于预训练模型使用的优秀设计,在此对Hugging Face作者及其开源社区表示感谢。
我们借鉴了 Hugging Face 的[Transformers](https://github.com/huggingface/transformers)🤗关于预训练模型使用的优秀设计,在此对 Hugging Face 作者及其开源社区表示感谢。
## License
PaddleNLP遵循[Apache-2.0开源协议](./LICENSE)。
PaddleNLP 遵循[Apache-2.0开源协议](./LICENSE)。

View File

@@ -1,12 +1,13 @@
[简体中文🀄](./README.md) | **English🌎**
<p align="center"> <img src="https://user-images.githubusercontent.com/1371212/175816733-8ec25eb0-9af3-4380-9218-27c154518258.png" align="middle" width="500" /> </p>
<p align="center">
<img src="https://user-images.githubusercontent.com/1371212/175816733-8ec25eb0-9af3-4380-9218-27c154518258.png" align="middle" width="500" />
</p>
------------------------------------------------------------------------------------------
<p align="center">
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache%202-dfd.svg"></a>
<a href="https://paddlenlp.readthedocs.io/en/latest/?badge=latest"><img src="https://readthedocs.org/projects/paddlenlp/badge/?version=latest">
<a href="https://github.com/PaddlePaddle/PaddleNLP/releases"><img src="https://img.shields.io/github/v/release/PaddlePaddle/PaddleNLP?color=ffa"></a>
<a href=""><img src="https://img.shields.io/badge/python-3.7+-aff.svg"></a>
<a href=""><img src="https://img.shields.io/badge/os-linux%2C%20win%2C%20mac-pink.svg"></a>
@@ -15,261 +16,63 @@
<a href="https://pypi.org/project/paddlenlp/"><img src="https://img.shields.io/pypi/dm/paddlenlp?color=9cf"></a>
<a href="https://github.com/PaddlePaddle/PaddleNLP/issues"><img src="https://img.shields.io/github/issues/PaddlePaddle/PaddleNLP?color=9cc"></a>
<a href="https://github.com/PaddlePaddle/PaddleNLP/stargazers"><img src="https://img.shields.io/github/stars/PaddlePaddle/PaddleNLP?color=ccf"></a>
<a href="./LICENSE"><img src="https://img.shields.io/badge/license-Apache%202-dfd.svg"></a>
</p>
<h4 align="center"> <a href=#features> Features </a> | <a href=#installation> Installation </a> | <a href=#quick-start> Quick Start </a> | <a href=#api-reference> API Reference </a> | <a href=#community> Community </a>
<h4 align="center">
<a href=#Features> Features </a> |
<a href=#Support-Models> Supported Models </a> |
<a href=#Installation> Installation </a> |
<a href=#Quick-start> Quick Start </a> |
<a href=#community> Community </a>
</h4>
**PaddleNLP** is a NLP library that is both **easy to use** and **powerful**. It aggregates high-quality pretrained models in the industry and provides a **plug-and-play** development experience, covering a model library for various NLP scenarios. With practical examples from industry practices, PaddleNLP can meet the needs of developers who require **flexible customization**.
**PaddleNLP** is a Large Language Model (LLM) development suite based on the PaddlePaddle deep learning framework, supporting efficient large model training, lossless compression, and high-performance inference on various hardware devices. With its **simplicity** and **ultimate performance**, PaddleNLP is dedicated to helping developers achieve efficient industrial applications of large models.
## News 📢
* **2023.6.12: [Release of PaddleNLP v2.6rc](https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v2.6.0rc)**
* 🔨 LLM Tools:Introduces comprehensive examples of open-source LLM training and inference, including [Bloom](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples/language_model/bloom), [ChatGLM](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples/language_model/chatglm), [GLM](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples/language_model/glm), [Llama](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples/language_model/llama) and [OPT](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/examples/language_model/opt). Added Tensor Parallel capability to [Trainer API](./docs/trainer.md) for distributed LLM trainin. Also released [Parameter-Efficient Finetuning](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/paddlenlp/peft),which enables training LLMs on consumer hardware.
* **2023.1.12: [Release of PaddleNLP v2.5](<https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v2.5.0>)**
* 🔨 NLP Tools: [PPDiffusers](./ppdiffusers), our cross-modal diffusion model toolbox based on PaddlePaddle, has been released! It provides a complete training process for diffusion models, and supports FastDeploy inference acceleration and multi-hardware deployment (supports Ascend chips and Kunlun core deployment).
* 💎 Industrial Applications: Information extraction, text classification, sentiment analysis, and intelligent question answering have all been newly upgraded. New releases include document information extraction [UIE-X](./applications/information_extraction/document), unified text classification [UTC](./applications/zero_shot_text_classification), unified sentiment analysis [UIE-Senta](./applications/sentiment_analysis/unified_sentiment_extraction) , and [unsupervised QA application](./applications/question_answering/unsupervised_qa). At the same time, the [ERNIE 3.0 Tiny v2](./model_zoo/ernie-tiny) series of pretrained small models have been released, which are more effective with low-resource and foreign data. They provide open-source end-to-end deployment solutions such as model pruning, model quantization, FastDeploy inference acceleration, and edge-side deployment to reduce the difficulty of pretrained model deployment.
* 💪 Framework Upgrade: Pretrained model [parameter configuration unification](./paddlenlp/transformers/configuration_utils.py), saving and loading custom parameter configurations no longer requires additional development; [Trainer API](./docs/trainer.md) has added BF16 training, recompute recalculations, sharding, and other distributed capabilities. Large-scale pre-training model training can easily be accomplished through simple configuration. [Model Compression API](./docs/compression.md) supports quantization training, vocabulary compression, and other functions. The compressed model has smaller accuracy loss, and the memory consumption of model deployment is greatly reduced. [Data Augmentation API](./docs/dataaug.md) has been comprehensively upgraded to support three granularities of data augmentation strategy: character, word, and sentence, making it easy to customize data augmentation strategies.
* 🤝 Community: 🤗Huggingface hub officially supports PaddleNLP pretrained models, supporting PaddleNLP Model and Tokenizer downloads and uploads directly from the 🤗Huggingface hub. Everyone is welcome to try out PaddleNLP pretrained models on the 🤗Huggingface hub [here](https://huggingface.co/PaddlePaddle).
* **September 6, 2022: [Release of PaddleNLP v2.4](<https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v2.4.0>)**
* 🔨 NLP Tools: [NLP Pipeline System Pipelines](./pipelines) has been released, supporting the rapid construction of search engines and question-answering systems, and can be extended to support various NLP systems, making it easy, flexible, and efficient to solve NLP tasks like building blocks!
* 💎 Industrial Applications: A new [text classification full-process application solution](./applications/text_classification) has been added, covering various scenarios such as multi-classification, multi-label, and hierarchical classification, supporting small-sample learning and TrustAI trustworthy computing model training and tuning.
* 🍭 AIGC: The SOTA model [CodeGen](https://github.com/PaddlePaddle/PaddleNLP/blob/develop/examples/code_generation/codegen) for code generation in various programming languages has been added.
* 💪 Framework Upgrade: [Automatic Model Compression API](./docs/compression.md) has been released, which automatically cuts and quantizes models, greatly reducing the threshold for using model compression technology. [Few-shot Prompt](./applications/text_classification/multi_class/few-shot) capability has been released, integrating classic algorithms such as PET, P-Tuning, and RGL.
* **2024.06.27 [PaddleNLP v3.0 Beta](https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v3.0.0-beta0)**:Embrace large models and experience a complete upgrade. With a unified large model suite, we achieve full-process access to domestically produced computing chips. We fully support industrial-level application processes for large models, such as PaddlePaddle's 4D parallel configuration, efficient fine-tuning strategies, efficient alignment algorithms, and high-performance reasoning. Our developed RsLoRA+ algorithm, full checkpoint storage mechanism Unified Checkpoint, and generalized support for FastFNN and FusedQKV all contribute to the training and inference of large models. We continuously support updates to mainstream models for providing efficient solutions.
* **2024.04.24 [PaddleNLP v2.8](https://github.com/PaddlePaddle/PaddleNLP/releases/tag/v2.8.0)**:Our self-developed RsLoRA+ algorithm with extreme convergence significantly improves the convergence speed and training effectiveness of PEFT training. By introducing high-performance generation acceleration into the RLHF PPO algorithm, we have broken through the generation speed bottleneck in PPO training, achieving a significant lead in PPO training performance. We generally support multiple large model training performance optimization methods such as FastFFN and FusedQKV, making large model training faster and more stable.
## Features
#### <a href=#out-of-box-nlp-toolset> 📦 Out-of-Box NLP Toolset </a>
### <a href=#Integrated training and inference on multiple hardware platforms> 🔧 Integrated training and inference on multiple hardware platforms </a>
#### <a href=#awesome-chinese-model-zoo> 🤗 Awesome Chinese Model Zoo </a>
Our development suit supports large model training and inference on multiple hardware platforms, including NVIDIA GPUs, Kunlun XPUs, Ascend NPUs, Enflame GCUs, and Hygon DCUs. The toolkit's interface allows for quick hardware switching, significantly reducing research and development costs associated with hardware transitions.
#### <a href=#industrial-end-to-end-system> 🎛️ Industrial End-to-end System </a>
### <a href=Efficient and easy-to-use pre-training> 🚀 Efficient and easy-to-use pre-training </a>
#### <a href=#high-performance-distributed-training-and-inference> 🚀 High Performance Distributed Training and Inference </a>
We support 4D high-performance training with data parallelism, sharding parallelism, tensor parallelism, and pipeline parallelism. The Trainer supports configurable distributed strategies, reducing the cost associated with complex distributed combinations. The Unified Checkpoint large model storage format supports dynamic scaling of model parameter distribution during training, thereby reducing the migration cost caused by hardware switching.
### <a href=#Efficient fine-tuning> 🤗 Efficient fine-tuning </a>
### Out-of-Box NLP Toolset
The fine-tuning algorithms are deeply integrated with zero-padding data streams and high-performance FlashMask operators, reducing invalid data padding and computation during training, and significantly improving the throughput of fine-tuning training.
Taskflow aims to provide off-the-shelf NLP pre-built task covering NLU and NLG technique, in the meanwhile with extremely fast inference satisfying industrial scenario.
### <a href=#Lossless compression and high-performance inference> 🎛️ Lossless compression and high-performance inference </a>
![taskflow1](https://user-images.githubusercontent.com/11793384/159693816-fda35221-9751-43bb-b05c-7fc77571dd76.gif)
The high-performance inference module of the large model toolkit incorporates dynamic insertion and operator fusion strategies throughout the entire process, greatly accelerating parallel inference speed. The underlying implementation details are encapsulated, enabling out-of-the-box high-performance parallel inference capabilities.
For more usage please refer to [Taskflow Docs](./docs/model_zoo/taskflow.md).
## Documentation
For detailed documentation, visit the [PaddleNLP Documentation](https://paddlenlp.readthedocs.io/).
### Awesome Chinese Model Zoo
------------------------------------------------------------------------------------------
#### 🀄 Comprehensive Chinese Transformer Models
We provide **45+** network architectures and over **500+** pretrained models. Not only includes all the SOTA model like ERNIE, PLATO and SKEP released by Baidu, but also integrates most of the high-quality Chinese pretrained model developed by other organizations. Use `AutoModel` API to **⚡SUPER FAST⚡** download pretrained models of different architecture. We welcome all developers to contribute your Transformer models to PaddleNLP!
```python
from paddlenlp.transformers import *
ernie = AutoModel.from_pretrained('ernie-3.0-medium-zh')
bert = AutoModel.from_pretrained('bert-wwm-chinese')
albert = AutoModel.from_pretrained('albert-chinese-tiny')
roberta = AutoModel.from_pretrained('roberta-wwm-ext')
electra = AutoModel.from_pretrained('chinese-electra-small')
gpt = AutoModelForPretraining.from_pretrained('gpt-cpm-large-cn')
```
Due to the computation limitation, you can use the ERNIE-Tiny light models to accelerate the deployment of pretrained models.
```python
# 6L768H
ernie = AutoModel.from_pretrained('ernie-3.0-medium-zh')
# 6L384H
ernie = AutoModel.from_pretrained('ernie-3.0-mini-zh')
# 4L384H
ernie = AutoModel.from_pretrained('ernie-3.0-micro-zh')
# 4L312H
ernie = AutoModel.from_pretrained('ernie-3.0-nano-zh')
```
Unified API experience for NLP task like semantic representation, text classification, sentence matching, sequence labeling, question answering, etc.
```python
import paddle
from paddlenlp.transformers import *
tokenizer = AutoTokenizer.from_pretrained('ernie-3.0-medium-zh')
text = tokenizer('natural language processing')
# Semantic Representation
model = AutoModel.from_pretrained('ernie-3.0-medium-zh')
sequence_output, pooled_output = model(input_ids=paddle.to_tensor([text['input_ids']]))
# Text Classificaiton and Matching
model = AutoModelForSequenceClassification.from_pretrained('ernie-3.0-medium-zh')
# Sequence Labeling
model = AutoModelForTokenClassification.from_pretrained('ernie-3.0-medium-zh')
# Question Answering
model = AutoModelForQuestionAnswering.from_pretrained('ernie-3.0-medium-zh')
```
#### Wide-range NLP Task Support
PaddleNLP provides rich examples covering mainstream NLP task to help developers accelerate problem solving. You can find our powerful transformer [Model Zoo](./model_zoo), and wide-range NLP application [examples](./examples) with detailed instructions.
Also you can run our interactive [Notebook tutorial](https://aistudio.baidu.com/aistudio/personalcenter/thirdview/574995) on AI Studio, a powerful platform with **FREE** computing resource.
<details><summary> PaddleNLP Transformer model summary (<b>click to show details</b>) </summary><div>
| Model | Sequence Classification | Token Classification | Question Answering | Text Generation | Multiple Choice |
| :----------------- | ----------------------- | -------------------- | ------------------ | --------------- | --------------- |
| ALBERT | ✅ | ✅ | ✅ | ❌ | ✅ |
| BART | ✅ | ✅ | ✅ | ✅ | ❌ |
| BERT | ✅ | ✅ | ✅ | ❌ | ✅ |
| BigBird | ✅ | ✅ | ✅ | ❌ | ✅ |
| BlenderBot | ❌ | ❌ | ❌ | ✅ | ❌ |
| ChineseBERT | ✅ | ✅ | ✅ | ❌ | ❌ |
| ConvBERT | ✅ | ✅ | ✅ | ❌ | ✅ |
| CTRL | ✅ | ❌ | ❌ | ❌ | ❌ |
| DistilBERT | ✅ | ✅ | ✅ | ❌ | ❌ |
| ELECTRA | ✅ | ✅ | ✅ | ❌ | ✅ |
| ERNIE | ✅ | ✅ | ✅ | ❌ | ✅ |
| ERNIE-CTM | ❌ | ✅ | ❌ | ❌ | ❌ |
| ERNIE-Doc | ✅ | ✅ | ✅ | ❌ | ❌ |
| ERNIE-GEN | ❌ | ❌ | ❌ | ✅ | ❌ |
| ERNIE-Gram | ✅ | ✅ | ✅ | ❌ | ❌ |
| ERNIE-M | ✅ | ✅ | ✅ | ❌ | ❌ |
| FNet | ✅ | ✅ | ✅ | ❌ | ✅ |
| Funnel-Transformer | ✅ | ✅ | ✅ | ❌ | ❌ |
| GPT | ✅ | ✅ | ❌ | ✅ | ❌ |
| LayoutLM | ✅ | ✅ | ❌ | ❌ | ❌ |
| LayoutLMv2 | ❌ | ✅ | ❌ | ❌ | ❌ |
| LayoutXLM | ❌ | ✅ | ❌ | ❌ | ❌ |
| LUKE | ❌ | ✅ | ✅ | ❌ | ❌ |
| mBART | ✅ | ❌ | ✅ | ❌ | ✅ |
| MegatronBERT | ✅ | ✅ | ✅ | ❌ | ✅ |
| MobileBERT | ✅ | ❌ | ✅ | ❌ | ❌ |
| MPNet | ✅ | ✅ | ✅ | ❌ | ✅ |
| NEZHA | ✅ | ✅ | ✅ | ❌ | ✅ |
| PP-MiniLM | ✅ | ❌ | ❌ | ❌ | ❌ |
| ProphetNet | ❌ | ❌ | ❌ | ✅ | ❌ |
| Reformer | ✅ | ❌ | ✅ | ❌ | ❌ |
| RemBERT | ✅ | ✅ | ✅ | ❌ | ✅ |
| RoBERTa | ✅ | ✅ | ✅ | ❌ | ✅ |
| RoFormer | ✅ | ✅ | ✅ | ❌ | ❌ |
| SKEP | ✅ | ✅ | ❌ | ❌ | ❌ |
| SqueezeBERT | ✅ | ✅ | ✅ | ❌ | ❌ |
| T5 | ❌ | ❌ | ❌ | ✅ | ❌ |
| TinyBERT | ✅ | ❌ | ❌ | ❌ | ❌ |
| UnifiedTransformer | ❌ | ❌ | ❌ | ✅ | ❌ |
| XLNet | ✅ | ✅ | ✅ | ❌ | ✅ |
</div></details>
For more pretrained model usage, please refer to [Transformer API Docs](./docs/model_zoo/index.rst).
### Industrial End-to-end System
We provide high value scenarios including information extraction, semantic retrieval, question answering high-value.
For more details industrial cases please refer to [Applications](./applications).
#### 🔍 Neural Search System
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168514909-8817d79a-72c4-4be1-8080-93d1f682bb46.gif" width="400">
</div>
For more details please refer to [Neural Search](./applications/neural_search).
#### ❓ Question Answering System
We provide question answering pipeline which can support FAQ system, Document-level Visual Question answering system based on [🚀RocketQA](https://github.com/PaddlePaddle/RocketQA).
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168514868-1babe981-c675-4f89-9168-dd0a3eede315.gif" width="400">
</div>
For more details please refer to [Question Answering](./applications/question_answering) and [Document VQA](./applications/document_intelligence/doc_vqa).
#### 💌 Opinion Extraction and Sentiment Analysis
We build an opinion extraction system for product review and fine-grained sentiment analysis based on [SKEP](https://arxiv.org/abs/2005.05635) Model.
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168407260-b7f92800-861c-4207-98f3-2291e0102bbe.png" width="300">
</div>
For more details please refer to [Sentiment Analysis](./applications/sentiment_analysis).
#### 🎙️ Speech Command Analysis
Integrated ASR Model, Information Extraction, we provide a speech command analysis pipeline that show how to use PaddleNLP and [PaddleSpeech](https://github.com/PaddlePaddle/PaddleSpeech) to solve Speech + NLP real scenarios.
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168412618-04897a47-79c9-4fe7-a054-5dc1f6a1f75c.png" width="500">
</div>
For more details please refer to [Speech Command Analysis](./applications/speech_cmd_analysis).
### High Performance Distributed Training and Inference
#### ⚡ FastTokenizer: High Performance Text Preprocessing Library
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168407921-b4395b1d-44bd-41a0-8c58-923ba2b703ef.png" width="400">
</div>
```python
AutoTokenizer.from_pretrained("ernie-3.0-medium-zh", use_fast=True)
```
Set `use_fast=True` to use C++ Tokenizer kernel to achieve 100x faster on text pre-processing. For more usage please refer to [FastTokenizer](./fast_tokenizer).
#### ⚡ FastGeneration: High Performance Generation Library
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168407831-914dced0-3a5a-40b8-8a65-ec82bf13e53c.gif" width="400">
</div>
```python
model = GPTLMHeadModel.from_pretrained('gpt-cpm-large-cn')
...
outputs, _ = model.generate(
input_ids=inputs_ids, max_length=10, decode_strategy='greedy_search',
use_fast=True)
```
Set `use_fast=True` to achieve 5x speedup for Transformer, GPT, BART, PLATO, UniLM text generation. For more usage please refer to [FastGeneration](./fast_generation).
#### 🚀 Fleet: 4D Hybrid Distributed Training
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168515134-513f13e0-9902-40ef-98fa-528271dcccda.png" width="300">
</div>
For more super large-scale model pre-training details please refer to [GPT-3](./examples/language_model/gpt-3).
## Support Models
Detailed list 👉 [Supported Model List](https://github.com/PaddlePaddle/PaddleNLP/issues/8663)
## Installation
### Prerequisites
* python >= 3.7
* paddlepaddle >= 2.3
* python >= 3.8
* paddlepaddle >= 3.0.0b0
More information about PaddlePaddle installation please refer to [PaddlePaddle's Website](https://www.paddlepaddle.org.cn/install/quick?docurl=/documentation/docs/zh/install/conda/linux-conda.html).
### Pip Installation
### Python pip Installation
```
pip install --upgrade paddlenlp
```shell
pip install --upgrade paddlenlp==3.0.0b3
```
or you can install the latest develop branch code with the following command:
@@ -278,46 +81,56 @@ or you can install the latest develop branch code with the following command:
pip install --pre --upgrade paddlenlp -f https://www.paddlepaddle.org.cn/whl/paddlenlp.html
```
More information about PaddlePaddle installation please refer to [PaddlePaddle's Website](https://www.paddlepaddle.org.cn).
------------------------------------------------------------------------------------------
## Quick Start
**Taskflow** aims to provide off-the-shelf NLP pre-built task covering NLU and NLG scenario, in the meanwhile with extremely fast inference satisfying industrial applications.
### Text generation with large language model
PaddleNLP provides a convenient and easy-to-use Auto API, which can quickly load models and Tokenizers. Here, we use the `Qwen/Qwen2-0.5B` large model as an example for text generation:
```python
from paddlenlp import Taskflow
# Chinese Word Segmentation
seg = Taskflow("word_segmentation")
seg("第十四届全运会在西安举办")
>>> ['第十四届', '全运会', '在', '西安', '举办']
# POS Tagging
tag = Taskflow("pos_tagging")
tag("第十四届全运会在西安举办")
>>> [('第十四届', 'm'), ('全运会', 'nz'), ('在', 'p'), ('西安', 'LOC'), ('举办', 'v')]
# Named Entity Recognition
ner = Taskflow("ner")
ner("《孤女》是2010年九州出版社出版的小说,作者是余兼羽")
>>> [('《', 'w'), ('孤女', '作品类_实体'), ('》', 'w'), ('是', '肯定词'), ('2010年', '时间类'), ('九州出版社', '组织机构类'), ('出版', '场景事件'), ('的', '助词'), ('小说', '作品类_概念'), (',', 'w'), ('作者', '人物类_概念'), ('是', '肯定词'), ('余兼羽', '人物类_实体')]
# Dependency Parsing
ddp = Taskflow("dependency_parsing")
ddp("9月9日上午纳达尔在亚瑟·阿什球场击败俄罗斯球员梅德韦杰夫")
>>> [{'word': ['9月9日', '上午', '纳达尔', '在', '亚瑟·阿什球场', '击败', '俄罗斯', '球员', '梅德韦杰夫'], 'head': [2, 6, 6, 5, 6, 0, 8, 9, 6], 'deprel': ['ATT', 'ADV', 'SBV', 'MT', 'ADV', 'HED', 'ATT', 'ATT', 'VOB']}]
# Sentiment Analysis
senta = Taskflow("sentiment_analysis")
senta("这个产品用起来真的很流畅,我非常喜欢")
>>> [{'text': '这个产品用起来真的很流畅,我非常喜欢', 'label': 'positive', 'score': 0.9938690066337585}]
>>> from paddlenlp.transformers import AutoTokenizer, AutoModelForCausalLM
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-0.5B")
>>> model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen2-0.5B", dtype="float16")
>>> input_features = tokenizer("你好!请自我介绍一下。", return_tensors="pd")
>>> outputs = model.generate(**input_features, max_length=128)
>>> print(tokenizer.batch_decode(outputs[0], skip_special_tokens=True))
['我是一个AI语言模型,我可以回答各种问题,包括但不限于:天气、新闻、历史、文化、科学、教育、娱乐等。请问您有什么需要了解的吗?']
```
## API Reference
### Pre-training for large language model
- Support [LUGE](https://www.luge.ai/) dataset loading and compatible with Hugging Face [Datasets](https://huggingface.co/datasets). For more details please refer to [Dataset API](https://paddlenlp.readthedocs.io/zh/latest/data_prepare/dataset_list.html).
- Using Hugging Face style API to load 500+ selected transformer models and download with fast speed. For more information please refer to [Transformers API](https://paddlenlp.readthedocs.io/zh/latest/model_zoo/index.html).
- One-line of code to load pre-trained word embedding. For more usage please refer to [Embedding API](https://paddlenlp.readthedocs.io/zh/latest/model_zoo/embeddings.html).
```shell
git clone https://github.com/PaddlePaddle/PaddleNLP.git && cd PaddleNLP # if cloned or downloaded, can skip this step
mkdir -p llm/data && cd llm/data
wget https://bj.bcebos.com/paddlenlp/models/transformers/llama/data/llama_openwebtext_100k.bin
wget https://bj.bcebos.com/paddlenlp/models/transformers/llama/data/llama_openwebtext_100k.idx
cd .. # change folder to PaddleNLP/llm
python -u -m paddle.distributed.launch --gpus "0,1,2,3,4,5,6,7" run_pretrain.py ./config/llama/pretrain_argument.json
```
Please find all PaddleNLP API Reference from our [readthedocs](https://paddlenlp.readthedocs.io/).
### SFT finetuning forlarge language model
```shell
git clone https://github.com/PaddlePaddle/PaddleNLP.git && cd PaddleNLP # if cloned or downloaded, can skip this step
mkdir -p llm/data && cd llm/data
wget https://bj.bcebos.com/paddlenlp/datasets/examples/AdvertiseGen.tar.gz && tar -zxvf AdvertiseGen.tar.gz
cd .. # change folder to PaddleNLP/llm
python -u -m paddle.distributed.launch --gpus "0,1,2,3,4,5,6,7" run_finetune.py ./config/llama/sft_argument.json
```
For more steps in the entire large model process, please refer to the[Large Model Full-Process Suite](./llm).
For more PaddleNLP content, please refer to:
* [Model Library](./slm/model_zoo),which includes end-to-end usage of high-quality pre-trained models.
* [Multi-scenario Examples](./slm/examples),to understand how to use PaddleNLP to solve various NLP technical problems, including basic techniques, system applications, and extended applications.
* [Interactive Tutorial](https://aistudio.baidu.com/aistudio/personalcenter/thirdview/574995),to quickly learn PaddleNLP on the free computing platform AI Studio.
------------------------------------------------------------------------------------------
## Community
@@ -330,15 +143,14 @@ To connect with other users and contributors, welcome to join our [Slack channel
Scan the QR code below with your Wechat⬇️. You can access to official technical exchange group. Look forward to your participation.
<div align="center">
<img src="https://user-images.githubusercontent.com/11987277/245085922-0aa68d24-00ff-442e-9c53-2f1e898151ce.png" width="150" height="150" />
<img src="https://github.com/user-attachments/assets/3a58cc9f-69c7-4ccb-b6f5-73e966b8051a" width="150" height="150" />
</div>
## Citation
If you find PaddleNLP useful in your research, please consider cite
```
If you find PaddleNLP useful in your research, please consider citing
```bibtext
@misc{=paddlenlp,
title={PaddleNLP: An Easy-to-use and High Performance NLP Library},
author={PaddleNLP Contributors},

View File

@@ -1,130 +0,0 @@
# 产业级端到端系统范例
## 1、简介
PaddleNLP 从预训练模型库出发,提供了经典预训练模型在主流 NLP 任务上丰富的[应用示例](../examples),满足了大量开发者的学习科研与基础应用需求。
针对更广泛的产业落地需求、更复杂的 NLP 场景任务,PaddleNLP 推出**产业级端到端系统范例库**(下文简称产业范例),提供单个模型之上的产业解决方案。
- 最强模型与实践———产业范例针对具体业务场景,提供最佳模型(组合),兼顾模型精度与性能,降低开发者模型选型成本;
- 全流程———打通数据标注-模型训练-模型调优-模型压缩—预测部署全流程,帮助开发者更低成本得完成产业落地。
## 2、基于 Pipelines 构建产业范例,加速落地
在面向不同场景任务建设一系列产业方案的过程中,不难发现,从技术基础设施角度看:
(1)NLP系统都可以抽象为由多个基础组件串接而成的流水线系统;
(2)多个NLP流水线系统可共享使用相同的基础组件。
因此,PaddleNLP 逐渐孵化出了一套 NLP 流水线系统 [Pipelines](../pipelines),将各个 NLP 复杂系统的通用模块抽象封装为标准组件,支持开发者通过配置文件对标准组件进行组合,仅需几分钟即可定制化构建智能系统,让解决NLP任务像搭积木一样便捷、灵活、高效。同时,Pipelines 中预置了前沿的预训练模型和算法,在研发效率、模型效果和性能方面提供多重保障。因此,Pipelines 能够大幅加快开发者使用飞桨落地的效率。
<div>
<img src="https://user-images.githubusercontent.com/11793384/212836991-d9132e46-b5bf-4389-80e1-4f9dee32f1fe.png" width="90%" length="90%">
</div>
<br>
**PaddleNLP 提供了多个版本的产业范例:**
- 如果你希望快速体验、直接应用、从零搭建一套完整系统,推荐使用 **Pipelines 版本**。这里集成了训练好的模型,无需关心模型训练细节;提供 Docker 环境,可快速一键部署端到端系统;打通前端 Demo 界面,便于直观展示、分析、调试效果。
- 如果你希望使用自己的业务数据进行二次开发,推荐使用`./applications`目录下的**可定制版本**,训练好的模型可以直接集成进 Pipelines 中进行使用。
- 也可以使用 [AI Studio](https://aistudio.baidu.com/aistudio/index) 在线 Jupyter Notebook 快速体验,有 GPU 算力哦。
| 场景任务 | Pipelines版本地址 | 可定制版本地址 | Notebook |
| :--------------- | ------- | ------- | ------- |
| **检索**| [字面+语义检索](../pipelines/examples/semantic-search) | [语义检索](./neural_search) | [基于Pipelines搭建检索系统](https://aistudio.baidu.com/aistudio/projectdetail/4442670)<br>[二次开发语义检索](https://aistudio.baidu.com/aistudio/projectdetail/3351784) |
| **问答** | [FAQ问答](../pipelines/examples/FAQ/)<br>[无监督检索式问答](../pipelines/examples/unsupervised-question-answering)<br>[有监督检索式问答](../pipelines/examples/question-answering) | [FAQ问答](./question_answering/supervised_qa)<br>[无监督检索式问答](./question_answering/unsupervised_qa) | [基于Pipelines搭建FAQ问答系统](https://aistudio.baidu.com/aistudio/projectdetail/4465498)<br>[基于Pipelines搭建抽取式问答系统](https://aistudio.baidu.com/aistudio/projectdetail/4442857)<br>[FAQ政务问答](https://aistudio.baidu.com/aistudio/projectdetail/3678873)<br>[FAQ保险问答](https://aistudio.baidu.com/aistudio/projectdetail/3882519) |
| **文本分类**| 暂无 | [文本分类](./text_classification) | [对话意图识别](https://aistudio.baidu.com/aistudio/projectdetail/2017202)<br>[法律文本多标签分类](https://aistudio.baidu.com/aistudio/projectdetail/3996601)<br>[层次分类](https://aistudio.baidu.com/aistudio/projectdetail/4568985) |
| **通用文本分类** | 暂无 | [通用文本分类](./zero_shot_text_classification) | |
| **通用信息抽取** | 暂无 | [通用信息抽取](./information_extraction) | [UIE快速体验](https://aistudio.baidu.com/aistudio/projectdetail/3914778)<br>[UIE微调实体抽取](https://aistudio.baidu.com/aistudio/projectdetail/4038499)<br>[UIE微调关系抽取](https://aistudio.baidu.com/aistudio/projectdetail/4371345)<br>[UIE-X快速体验](https://aistudio.baidu.com/aistudio/projectdetail/5017442)<br>[UIE-X微调](https://aistudio.baidu.com/aistudio/projectdetail/5261592) |
| **情感分析** | [情感分析](../pipelines/examples/sentiment_analysis) | [情感分析](./sentiment_analysis) | [情感分析](https://aistudio.baidu.com/aistudio/projectdetail/5318177)|
| **文档智能** | [文档抽取问答](../pipelines/examples/document-intelligence) | [跨模态文档问答](./document_intelligence/doc_vqa)| [文档抽取问答](https://aistudio.baidu.com/aistudio/projectdetail/4881278)<br>[汽车说明书问答](https://aistudio.baidu.com/aistudio/projectdetail/4049663) |
| **文生图** | [文生图系统](../pipelines/examples/text_to_image) | 可参考[PPDiffusers](../ppdiffusers) | |
| **语音指令解析** | 暂无 | [语音指令解析](./speech_cmd_analysis) | [语音指令解析](https://aistudio.baidu.com/aistudio/projectdetail/4399703) |
| **文本摘要** | 暂无 | [文本摘要](./text_summarization) | [文本摘要](https://aistudio.baidu.com/aistudio/projectdetail/4903667) |
## 3、典型范例介绍
#### 📄 通用信息抽取系统
- 首个产业级通用信息抽取方案 UIE,面向纯文本,实现多任务统一建模,提供强大的零样本抽取和少样本快速迁移能力;
- 首个兼具文本及文档抽取能力、多语言、开放域的信息抽取方案 UIE-X,基于 [ERNIE-Layout](../model_zoo/ernie-layout) 跨模态布局增强预训练模型,集成 [PaddleOCR](https://github.com/PaddlePaddle/PaddleOCR) 的 PP-OCR、PP-Structure 版面分析能力,小样本文档信息抽取效果领先。
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/213365046-69967745-b4a8-4435-98fb-c34f68cd22e9.png" width="60%" length="60%">
</div>
详细使用说明请参考[通用信息抽取系统](./information_extraction),更多:[UIE 解读](https://mp.weixin.qq.com/s/-hHz8knHIKKqKCBTke7i5A)、[UIE-X 解读](https://zhuanlan.zhihu.com/p/592422623)。
#### 🔍 语义检索系统
- 前沿算法———基于 SimCSE、In-batch Negatives、ERNIE Pairwise、RocketQA Pointwise 等提供针对无监督、有监督等多种数据情况的多样化方案;
- 全流程———覆盖召回、排序环节,集成主流 ANN 引擎,同时兼容 ElasticSearch 字面检索模式,提供多路召回方案。打通训练、调优、高效向量检索引擎建库和查询全流程。
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/213134465-30cae5fd-4cd1-4e5b-a1cb-fa55c72980a7.gif" width="60%" length="60%">
</div>
详细使用说明请参考[语义检索系统](./neural_search)。
#### ❓ 智能问答系统
- 端到端问答技术 [🚀RocketQA](https://github.com/PaddlePaddle/RocketQA),首个中文端到端问答模型,基于知识增强的预训练模型ERNIE和百万量级的人工标注数据集DuReader训练得到,效果优异;
- 覆盖有监督(如 FAQ 问答)、无监督(自动生成 QA 对,生成的问答对语料可以通过无监督的方式构建检索式问答系统)等多种情况,适用各类业务场景。
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/168514868-1babe981-c675-4f89-9168-dd0a3eede315.gif" width="60%" length="60%">
</div>
详细使用说明请参考[智能问答系统](./question_answering)与[文档智能问答](./document_intelligence/doc_vqa)。
#### 📚 通用文本分类
- 基于“任务架构统一、通用能力共享”的通用文本分类技术 UTC,实了良好的零/少样本迁移能力,实现大一统诸多任务的开放域分类,可支持情感分析、意图识别、语义匹配、蕴含推理等各种可转换为分类问题的 NLU 任务。
<div align="center">
<img src="https://user-images.githubusercontent.com/11793384/213347595-e9c08bd1-3d32-4519-9a52-31fb69b841e8.png" width="60%" length="60%">
</div>
<br>
详细使用说明请参考[通用文本分类](./zero_shot_text_classification),更多:[文章解读](https://mp.weixin.qq.com/s/VV-nYv4y1r7oipJnURRL5w)。
#### 🗂 文本分类
- 场景方案全覆盖––––开源预训练模型-微调、提示学习、基于语义索引等多种分类技术方案,满足不同场景需求,涵盖多分类(multi-class)、多标签(multi-label)、层次分类(hierarchical)三类任务;
- 模型高效调优––––强强结合数据增强能力与可信增强技术,解决脏数据、标注数据欠缺、数据不平衡等问题,大幅提升模型效果。
<div align="center">
<img src="https://user-images.githubusercontent.com/63761690/186378697-630d3590-4e67-49a0-8d5f-7cabd9daa894.png" width="60%" length="60%">
</div>
<br>
详细使用说明请参考[文本分类](./text_classification),更多:[文章解读](https://mp.weixin.qq.com/s/tas7yM8vapxwtlJt-MRZdg)。
#### 💌 评论观点抽取与情感分析
- 经典方案:基于情感知识增强预训练模型SKEP,两阶段式抽取和分类,首先通过序列标注的方式定位属性词和观点词,然后进行属性集情感分类;
- 前沿方案:基于UIE的情感分析方案采用 Prompt Learning 的方式进行情感信息抽取,精度更高。支持语句级和属性级情感分析,解决同义属性聚合、隐性观点抽取难点,并提供可视化分析能力。
<div align="center">
<img src="https://user-images.githubusercontent.com/35913314/200259473-434888f7-c0ac-4253-ab23-ede1628e6ba2.png" width="60%" length="60%">
</div>
<br>
详细使用说明请参考[情感分析](./sentiment_analysis),更多:[文章解读](https://mp.weixin.qq.com/s/QAHjIRG9zxpYfM6YPRQ-9w)。
#### 🎙️ 智能语音指令解析
- 集成了[PaddleSpeech](https://github.com/PaddlePaddle/PaddleSpeech)和[百度开放平台](https://ai.baidu.com/)的语音识别和[UIE](./model_zoo/uie)通用信息抽取等技术,打造智能一体化的语音指令解析系统范例,该方案可应用于智能语音填单、智能语音交互、智能语音检索等场景,提高人机交互效率。
<div align="center">
<img src="https://user-images.githubusercontent.com/16698950/168589100-a6c6f346-97bb-47b2-ac26-8d50e71fddc5.png" width="400">
</div>
详细使用说明请参考[智能语音指令解析](./applications/speech_cmd_analysis)。

View File

@@ -1,188 +0,0 @@
# 文档智能应用
**目录**
- [1. 文档智能应用简介](#文档智能应用简介)
- [2. 技术特色介绍](#技术特色介绍)
- [2.1 多语言跨模态训练基座](#多语言跨模态训练基座)
- [2.2 多场景覆盖](#多场景覆盖)
- [3. 快速开始](#快速开始)
- [3.1 开箱即用](#开箱即用)
- [3.2 产业级流程方案](#产业级流程方案)
## 1. 文档智能应用简介
文档智能(DI, Document Intelligence)主要指**对于网页、数字文档或扫描文档所包含的文本以及丰富的排版格式等信息,通过人工智能技术进行理解、分类、提取以及信息归纳**的过程。文档智能技术广泛应用于金融、保险、能源、物流、医疗等行业,常见的应用场景包括财务报销单、招聘简历、企业财报、合同文书、动产登记证、法律判决书、物流单据等多模态文档的关键信息抽取、文档解析、文档比对等。
在实际应用中,需要解决文档格式繁杂、布局多样、信息模态多样、需求开放、业务数据少等多重难题。针对文档智能领域的痛点和难点,PaddleNLP将持续开源一系列产业实践范例,解决开发者们实际应用难题。
<div align="center">
<img width="1000" height="270" alt="文档智能技术一般流程" src="https://user-images.githubusercontent.com/40840292/196361583-6b1c66d1-6a9b-4193-949a-71e2d420a82a.png">
</div>
<a name="技术特色介绍"></a>
## 2. 技术特色介绍
<a name="多语言跨模态训练基座"></a>
### 2.1 多语言跨模态训练基座
近期,百度文心文档智能,基于多语言跨模态布局增强的文档智能大模型[ERNIE-Layout](http://arxiv.org/abs/2210.06155),刷新了五类11项文档智能任务效果。依托文心ERNIE大模型,基于布局知识增强技术,融合文本、图像、布局等信息进行联合建模,能够对多模态文档(如文档图片、PDF 文件、扫描件等)进行深度理解与分析,为各类上层应用提供SOTA模型底座。
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/196373896-597f6178-4c78-41a1-bb12-796546644b32.png width="600"/>
</div>
<a name="多场景覆盖"></a>
### 2.2 多场景覆盖
以下是文档智能技术的一些应用场景展示:
- 发票抽取问答
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/196118171-fd3e49a0-b9f1-4536-a904-c48f709a2dec.png height=350 width=1000 hspace='10'/>
</div>
- 海报抽取问答
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/195610368-04230855-62de-439e-b708-2c195b70461f.png height=600 width=1000 hspace='15'/>
</div>
- 网页抽取问答
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/195611613-bdbe692e-d7f2-4a2b-b548-1a933463b0b9.png height=350 width=1000 hspace='10'/>
</div>
- 表格抽取问答
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/195610692-8367f1c8-32c2-4b5d-9514-a149795cf609.png height=350 width=1000 hspace='10'/>
</div>
- 试卷抽取问答
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/195823294-d891d95a-2ef8-4519-be59-0fedb96c00de.png height=700 width=1000 hspace='10'/>
</div>
- 英文票据多语种(中、英、日、泰、西班牙、俄语)抽取问答
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/195610820-7fb88608-b317-45fc-a6ab-97bf3b20a4ac.png height=400 width=1000 hspace='15'/>
</div>
- 中文票据多语种(中简、中繁、英、日、法语)抽取问答
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/195611075-9323ce9f-134b-4657-ab1c-f4892075d909.png height=350 width=1000 hspace='15'/>
</div>
- Demo图片可在此[下载](https://bj.bcebos.com/paddlenlp/taskflow/document_intelligence/demo.zip)
<a name="快速开始"></a>
## 3. 快速开始
<a name="开箱即用"></a>
### 3.1 开箱即用
开源DocPrompt开放文档抽取问答模型,以ERNIE-Layout为底座,可精准理解图文信息,推理学习附加知识,准备捕捉图片、PDF等多模态文档中的每个细节。
🧾 通过[Huggingface网页](https://huggingface.co/spaces/PaddlePaddle/ERNIE-Layout)体验DocPrompt功能:
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/195749427-864d7744-1fd1-455e-99c6-53a260776483.jpg height=700 width=1100 hspace='10'/>
</div>
#### Taskflow
通过``paddlenlp.Taskflow``三行代码调用DocPrompt功能,具备多语言文档抽取问答能力,部分应用场景展示如下:
- 输入格式
```
[
{"doc": "./invoice.jpg", "prompt": ["发票号码是多少?", "校验码是多少?"]},
{"doc": "./resume.png", "prompt": ["五百丁本次想要担任的是什么职位?", "五百丁是在哪里上的大学?", "大学学的是什么专业?"]}
]
```
默认使用PaddleOCR进行OCR识别,同时支持用户通过``word_boxes``传入自己的OCR结果,格式为``List[str, List[float, float, float, float]]``。
```
[
{"doc": doc_path, "prompt": prompt, "word_boxes": word_boxes}
]
```
- 支持单条、批量预测
- 支持本地图片路径输入
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/194748579-f9e8aa86-7f65-4827-bfae-824c037228b3.png height=800 hspace='20'/>
</div>
```python
>>> from pprint import pprint
>>> from paddlenlp import Taskflow
>>> docprompt = Taskflow("document_intelligence")
>>> pprint(docprompt([{"doc": "./resume.png", "prompt": ["五百丁本次想要担任的是什么职位?", "五百丁是在哪里上的大学?", "大学学的是什么专业?"]}]))
[{'prompt': '五百丁本次想要担任的是什么职位?',
'result': [{'end': 7, 'prob': 1.0, 'start': 4, 'value': '客户经理'}]},
{'prompt': '五百丁是在哪里上的大学?',
'result': [{'end': 37, 'prob': 1.0, 'start': 31, 'value': '广州五百丁学院'}]},
{'prompt': '大学学的是什么专业?',
'result': [{'end': 44, 'prob': 0.82, 'start': 38, 'value': '金融学(本科)'}]}]
```
- http图片链接输入
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/194748592-e20b2a5f-d36b-46fb-8057-86755d188af0.jpg height=400 hspace='10'/>
</div>
```python
>>> from pprint import pprint
>>> from paddlenlp import Taskflow
>>> docprompt = Taskflow("document_intelligence")
>>> pprint(docprompt([{"doc": "https://bj.bcebos.com/paddlenlp/taskflow/document_intelligence/images/invoice.jpg", "prompt": ["发票号码是多少?", "校验码是多少?"]}]))
[{'prompt': '发票号码是多少?',
'result': [{'end': 2, 'prob': 0.74, 'start': 2, 'value': 'No44527206'}]},
{'prompt': '校验码是多少?',
'result': [{'end': 233,
'prob': 1.0,
'start': 231,
'value': '01107 555427109891646'}]}]
```
- 可配置参数说明
* `batch_size`:批处理大小,请结合机器情况进行调整,默认为1。
* `lang`:选择PaddleOCR的语言,`ch`可在中英混合的图片中使用,`en`在英文图片上的效果更好,默认为`ch`。
* `topn`: 如果模型识别出多个结果,将返回前n个概率值最高的结果,默认为1。
<a name="产业级流程方案"></a>
### 3.2 产业级流程方案
针对文档智能领域的痛点和难点,PaddleNLP将持续开源一系列文档智能产业实践范例,解决开发者们实际应用难题。
- 👉 [汽车说明书跨模态智能问答](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/applications/document_intelligence/doc_vqa#readme)
更多:百度TextMind智能文档分析平台可提供包括文档信息抽取、文本内容审查、企业文档管理、文档格式解析、文档内容比对等全方位一站式的文档智能服务,已形成一套完整的企业文档场景化解决方案,满足银行、券商、法律、能源、传媒、通信、物流等不同行业和场景的文档处理需求,以AI助力企业的办公智能化升级和数字化转型。欢迎深度交流与商业合作,了解详情:https://ai.baidu.com/tech/nlp/Textanalysis
## References
- [文档智能:数据集、模型和应用](http://jcip.cipsc.org.cn/CN/abstract/abstract3331.shtml)
- [ERNIE-Layout: Layout-Knowledge Enhanced Multi-modal Pre-training for Document Understanding](http://arxiv.org/abs/2210.06155)

View File

@@ -1,17 +0,0 @@
OCR_process/*.json
*.png
*.json
answers/*
checkpoints/*
__pycache__/*
OCR_process/demo_pics/*
Rerank/log/*
Rerank/checkpoints/*
Rerank/data/*
Rerank/output/*
Rerank/__pycache__/*
Extraction/log/*
Extraction/checkpoints/*
Extraction/data/*
Extraction/output/*
Extraction/__pycache__/*

View File

@@ -1,51 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import json
import numpy as np
def get_top1_from_ranker(path):
with open(path, "r", encoding="utf-8") as f:
scores = [float(line.strip()) for line in f.readlines()]
top_id = np.argmax(scores)
return top_id
def get_ocr_result_by_id(path, top_id):
with open(path, "r", encoding="utf-8") as f:
reses = f.readlines()
res = reses[top_id]
return json.loads(res)
def write_to_file(doc, path):
with open(path, "w", encoding="utf-8") as f:
json.dump(doc, f, ensure_ascii=False)
f.write("\n")
if __name__ == "__main__":
question = sys.argv[1]
ranker_result_path = "../Rerank/data/demo.score"
ocr_result_path = "../OCR_process/demo_ocr_res.json"
save_path = "data/demo_test.json"
top_id = get_top1_from_ranker(ranker_result_path)
doc = get_ocr_result_by_id(ocr_result_path, top_id)
doc["question"] = question
doc["img_id"] = str(top_id + 1)
write_to_file(doc, save_path)

View File

@@ -1,359 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import collections
import json
import sys
import numpy as np
import paddle
from paddle.io import Dataset
from tqdm import tqdm
sys.path.insert(0, "../")
class DocVQAExample(object):
def __init__(self, question, doc_tokens, doc_boxes=[], answer=None, labels=None, image=None):
self.question = question
self.doc_tokens = doc_tokens
self.doc_boxes = doc_boxes
self.image = image
self.answer = answer
self.labels = labels
class DocVQAFeatures(object):
"""A single set of features of data."""
def __init__(self, example_index, input_ids, input_mask, segment_ids, boxes=None, label=None):
self.example_index = example_index
self.input_ids = input_ids
self.input_mask = input_mask
self.segment_ids = segment_ids
self.boxes = boxes
self.label = label
class DocVQA(Dataset):
def __init__(
self, args, tokenizer, label2id_map, max_seq_len=512, max_query_length=20, max_doc_length=512, max_span_num=1
):
super(DocVQA, self).__init__()
self.tokenizer = tokenizer
self.label2id_map = label2id_map
self.max_seq_len = max_seq_len
self.max_query_length = max_query_length
self.max_doc_length = max_doc_length
self.max_span_num = max_span_num
self.sample_list = None
self.args = args
self.docvqa_inputs = self.docvqa_input()
def check_is_max_context(self, doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a single
# token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a gallon of milk
# Span A: the man went to the
# Span B: to the store and bought
# Span C: and bought a gallon of
# ...
#
# Now the word 'bought' will have two scores from spans B and C. We only
# want to consider the score with "maximum context", which we define as
# the *minimum* of its left and right context (the *sum* of left and
# right context will always be the same, of course).
#
# In the example the maximum context for 'bought' would be span C since
# it has 1 left context and 3 right context, while span B has 4 left context
# and 0 right context.
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
def convert_examples_to_features(
self, examples, tokenizer, label_map, max_seq_length, max_span_num, max_doc_length, max_query_length
):
if "[CLS]" in self.tokenizer.get_vocab():
start_token = "[CLS]"
end_token = "[SEP]"
else:
start_token = "<s>"
end_token = "</s>"
features = []
for (example_index, example) in enumerate(examples):
query_tokens = tokenizer.tokenize(example.question)
if len(query_tokens) > max_query_length:
query_tokens = query_tokens[0:max_query_length]
all_doc_tokens = example.doc_tokens
all_doc_boxes_tokens = example.doc_boxes
cls_token_box = [0, 0, 0, 0]
sep_token_box = [1000, 1000, 1000, 1000]
pad_token_box = [0, 0, 0, 0]
ques_token_box = [0, 0, 0, 0]
# The -3 accounts for [CLS], [SEP] and [SEP]
max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
# We can have documents that are longer than the maximum sequence length.
# To deal with this we do a sliding window approach, where we take chunks
# of the up to our max length with a stride of `doc_stride`.
_DocSpan = collections.namedtuple("DocSpan", ["start", "length"])
doc_spans = []
start_offset = 0
while start_offset < len(all_doc_tokens):
length = len(all_doc_tokens) - start_offset
if length > max_tokens_for_doc:
length = max_tokens_for_doc
doc_spans.append(_DocSpan(start=start_offset, length=length))
if start_offset + length == len(all_doc_tokens):
break
start_offset += length
spans_input_ids = []
spans_input_mask = []
spans_segment_ids = []
spans_boxes_tokens = []
for (doc_span_index, doc_span) in enumerate(doc_spans):
if doc_span_index == max_span_num:
break
tokens = []
boxes_tokens = []
token_is_max_context = {}
segment_ids = []
tokens.append(start_token)
boxes_tokens.append(cls_token_box)
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
boxes_tokens.append(ques_token_box)
segment_ids.append(0)
tokens.append(end_token)
boxes_tokens.append(sep_token_box)
segment_ids.append(0)
for i in range(doc_span.length):
split_token_index = doc_span.start + i
is_max_context = self.check_is_max_context(doc_spans, doc_span_index, split_token_index)
token_is_max_context[len(tokens)] = is_max_context
tokens.append(all_doc_tokens[split_token_index])
boxes_tokens.append(all_doc_boxes_tokens[split_token_index])
segment_ids.append(0)
tokens.append(end_token)
boxes_tokens.append(sep_token_box)
segment_ids.append(0)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
# The mask has 1 for real tokens and 0 for padding tokens. Only real
# tokens are attended to.
input_mask = [1] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
boxes_tokens.append(pad_token_box)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
assert len(boxes_tokens) == max_seq_length
spans_input_ids.append(input_ids)
spans_input_mask.append(input_mask)
spans_segment_ids.append(segment_ids)
spans_boxes_tokens.append(boxes_tokens)
# Padding
# padding spans
# max_span_num: max_seg_num
# spans_input_ids: the tokens in each segment
if len(spans_input_ids) > max_span_num:
spans_input_ids = spans_input_ids[0:max_span_num]
spans_input_mask = spans_input_mask[0:max_span_num]
spans_segment_ids = spans_segment_ids[0:max_span_num]
spans_boxes_tokens = spans_boxes_tokens[0:max_span_num]
while len(spans_input_ids) < max_span_num:
tokens = []
boxes_tokens = []
segment_ids = []
tokens.append(start_token)
boxes_tokens.append(cls_token_box)
segment_ids.append(0)
for token in query_tokens:
tokens.append(token)
boxes_tokens.append(ques_token_box)
segment_ids.append(0)
tokens.append(end_token)
boxes_tokens.append(sep_token_box)
segment_ids.append(0)
tokens.append(end_token)
boxes_tokens.append(sep_token_box)
segment_ids.append(0)
input_ids = tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1] * len(input_ids)
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(0)
segment_ids.append(0)
boxes_tokens.append(pad_token_box)
spans_input_ids.append(input_ids)
spans_input_mask.append(input_mask)
spans_segment_ids.append(segment_ids)
spans_boxes_tokens.append(boxes_tokens)
# padding labels
labels = example.labels
sep_id = tokenizer.convert_tokens_to_ids(end_token)
labels = ["O"] * (spans_input_ids[0].index(sep_id) + 1) + labels
if len(labels) > 512:
labels = labels[:512]
if len(labels) < 512:
labels += ["O"] * (512 - len(labels))
assert len(spans_input_ids[0]) == len(labels)
label_ids = []
for lid, l in enumerate(labels):
if l not in label_map:
label_ids.append(0)
else:
label_ids.append(label_map[l])
feature = DocVQAFeatures(
example_index=example_index,
input_ids=spans_input_ids,
input_mask=spans_input_mask,
segment_ids=spans_segment_ids,
boxes=spans_boxes_tokens,
label=label_ids,
)
features.append(feature)
return features
def create_examples(self, data, is_test=False):
"""Creates examples for the training and dev sets."""
examples = []
for sample in tqdm(data, total=len(data)):
question = sample["question"]
doc_tokens = sample["document"]
doc_boxes = sample["document_bbox"]
labels = sample["labels"] if not is_test else []
x_min, y_min = min(doc_boxes, key=lambda x: x[0])[0], min(doc_boxes, key=lambda x: x[2])[2]
x_max, y_max = max(doc_boxes, key=lambda x: x[1])[1], max(doc_boxes, key=lambda x: x[3])[3]
width = x_max - x_min
height = y_max - y_min
if max(width, height) < 1000:
scale_x = 1
scale_y = 1
else:
scale_x = 1000 / max(width, height)
scale_y = 1000 / max(width, height)
scaled_doc_boxes = [
[
round((b[0] - x_min) * scale_x),
round((b[2] - y_min) * scale_y),
round((b[1] - x_min) * scale_x),
round((b[3] - y_min) * scale_y),
]
for b in doc_boxes
]
for box, oribox in zip(scaled_doc_boxes, doc_boxes):
if box[0] < 0:
print(box, oribox)
if box[2] - box[0] < 0:
print(box, oribox)
if box[3] - box[1] < 0:
print(box, oribox)
for pos in box:
if pos > 1000:
print(width, height, box, oribox)
example = DocVQAExample(
question=question, doc_tokens=doc_tokens, doc_boxes=scaled_doc_boxes, labels=labels
)
examples.append(example)
return examples
def docvqa_input(self):
data = []
if self.args.do_train:
dataset = self.args.train_file
elif self.args.do_test:
dataset = self.args.test_file
with open(dataset, "r", encoding="utf8") as f:
for index, line in enumerate(f):
data.append(json.loads(line.strip()))
# read the examples from train/test xlm files
examples = self.create_examples(data, is_test=self.args.do_test)
features = self.convert_examples_to_features(
examples,
self.tokenizer,
self.label2id_map,
max_seq_length=self.max_seq_len,
max_doc_length=self.max_doc_length,
max_span_num=self.max_span_num,
max_query_length=self.max_query_length,
)
all_input_ids = paddle.to_tensor([f.input_ids for f in features], dtype="int64")
all_input_mask = paddle.to_tensor([f.input_mask for f in features], dtype="int64")
all_segment_ids = paddle.to_tensor([f.segment_ids for f in features], dtype="int64")
all_bboxes = paddle.to_tensor([f.boxes for f in features], dtype="int64")
all_labels = paddle.to_tensor([f.label for f in features], dtype="int64")
self.sample_list = [
np.array(all_input_ids),
np.array(all_input_mask),
np.array(all_segment_ids),
np.array(all_bboxes),
np.array(all_labels),
]
def __getitem__(self, idx):
return (
self.sample_list[0][idx],
self.sample_list[1][idx],
self.sample_list[2][idx],
self.sample_list[3][idx],
self.sample_list[4][idx],
)
def __len__(
self,
):
return self.sample_list[0].shape[0]

View File

@@ -1,206 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import paddle
import paddle.fluid as fluid
import paddle.nn as nn
from paddlenlp.transformers import LayoutXLMPretrainedModel
class Crf_decoding(paddle.fluid.dygraph.Layer):
def __init__(self, param_attr, size=None, is_test=True, dtype="float32"):
super(Crf_decoding, self).__init__()
self._dtype = dtype
self._size = size
self._is_test = is_test
self._param_attr = param_attr
self._transition = self.create_parameter(
attr=self._param_attr, shape=[self._size + 2, self._size], dtype=self._dtype
)
@property
def weight(self):
return self._transition
@weight.setter
def weight(self, value):
self._transition = value
def forward(self, input, label=None, length=None):
viterbi_path = self._helper.create_variable_for_type_inference(dtype=self._dtype)
this_inputs = {"Emission": [input], "Transition": self._transition, "Label": label}
if length is not None:
this_inputs["Length"] = [length]
self._helper.append_op(
type="crf_decoding",
inputs=this_inputs,
outputs={"ViterbiPath": [viterbi_path]},
attrs={
"is_test": self._is_test,
},
)
return viterbi_path
class Chunk_eval(paddle.fluid.dygraph.Layer):
def __init__(self, num_chunk_types, chunk_scheme, excluded_chunk_types=None):
super(Chunk_eval, self).__init__()
self.num_chunk_types = num_chunk_types
self.chunk_scheme = chunk_scheme
self.excluded_chunk_types = excluded_chunk_types
def forward(self, input, label, seq_length=None):
precision = self._helper.create_variable_for_type_inference(dtype="float32")
recall = self._helper.create_variable_for_type_inference(dtype="float32")
f1_score = self._helper.create_variable_for_type_inference(dtype="float32")
num_infer_chunks = self._helper.create_variable_for_type_inference(dtype="int64")
num_label_chunks = self._helper.create_variable_for_type_inference(dtype="int64")
num_correct_chunks = self._helper.create_variable_for_type_inference(dtype="int64")
this_input = {"Inference": [input], "Label": [label]}
if seq_length is not None:
this_input["SeqLength"] = [seq_length]
self._helper.append_op(
type="chunk_eval",
inputs=this_input,
outputs={
"Precision": [precision],
"Recall": [recall],
"F1-Score": [f1_score],
"NumInferChunks": [num_infer_chunks],
"NumLabelChunks": [num_label_chunks],
"NumCorrectChunks": [num_correct_chunks],
},
attrs={
"num_chunk_types": self.num_chunk_types,
"chunk_scheme": self.chunk_scheme,
"excluded_chunk_types": self.excluded_chunk_types or [],
},
)
return (precision, recall, f1_score, num_infer_chunks, num_label_chunks, num_correct_chunks)
class Linear_chain_crf(paddle.fluid.dygraph.Layer):
def __init__(self, param_attr, size=None, is_test=False, dtype="float32"):
super(Linear_chain_crf, self).__init__()
self._param_attr = param_attr
self._dtype = dtype
self._size = size
self._is_test = is_test
self._transition = self.create_parameter(
attr=self._param_attr, shape=[self._size + 2, self._size], dtype=self._dtype
)
@property
def weight(self):
return self._transition
@weight.setter
def weight(self, value):
self._transition = value
def forward(self, input, label, length=None):
alpha = self._helper.create_variable_for_type_inference(dtype=self._dtype)
emission_exps = self._helper.create_variable_for_type_inference(dtype=self._dtype)
transition_exps = self._helper.create_variable_for_type_inference(dtype=self._dtype)
log_likelihood = self._helper.create_variable_for_type_inference(dtype=self._dtype)
this_inputs = {"Emission": [input], "Transition": self._transition, "Label": [label]}
if length is not None:
this_inputs["Length"] = [length]
self._helper.append_op(
type="linear_chain_crf",
inputs=this_inputs,
outputs={
"Alpha": [alpha],
"EmissionExps": [emission_exps],
"TransitionExps": transition_exps,
"LogLikelihood": log_likelihood,
},
attrs={
"is_test": self._is_test,
},
)
return log_likelihood
class LayoutXLMForTokenClassification_with_CRF(LayoutXLMPretrainedModel):
def __init__(self, layoutxlm, num_classes, dropout=None):
super(LayoutXLMForTokenClassification_with_CRF, self).__init__()
self.num_classes = num_classes
self.layoutxlm = layoutxlm
self.dropout = nn.Dropout(dropout if dropout is not None else self.layoutxlm.config["hidden_dropout_prob"])
self.emission_classifier = nn.Linear(self.layoutxlm.config["hidden_size"], self.num_classes)
self.emission_classifier.apply(self.init_weights)
self.linear_chain_crf = Linear_chain_crf(
size=self.num_classes, param_attr=paddle.fluid.ParamAttr(name="liner_chain_crfw")
)
self.crf_decoding = Crf_decoding(param_attr=paddle.fluid.ParamAttr(name="crfw_decode"), size=self.num_classes)
self.crf_decoding.weight = self.linear_chain_crf.weight
self.crfw = fluid.layers.create_parameter(
shape=[self.num_classes + 2, self.num_classes], dtype="float32", name="crfw"
)
self.mask_crfw = fluid.layers.create_parameter(
shape=[self.num_classes + 2, self.num_classes], dtype="float32", name="mask_matrix"
)
def get_input_embeddings(self):
return self.layoutxlm.embeddings.word_embeddings
def forward(
self,
input_ids=None,
bbox=None,
attention_mask=None,
token_type_ids=None,
labels=None,
image=None,
position_ids=None,
head_mask=None,
is_train=False,
):
input_ids = input_ids.squeeze(axis=1)
bbox = bbox.squeeze(axis=1)
attention_mask = attention_mask.squeeze(axis=1)
token_type_ids = token_type_ids.squeeze(axis=1)
outputs = self.layoutxlm(
input_ids=input_ids,
bbox=bbox,
image=image,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
)
seq_length = input_ids.shape[1]
# sequence out and image out
sequence_logits, _ = outputs[0][:, :seq_length], outputs[0][:, seq_length:]
emission = self.emission_classifier(sequence_logits)
length = paddle.sum(attention_mask, axis=1)
labels = labels.reshape([-1, seq_length, 1])
# standard crf loss
crf_cost = self.linear_chain_crf(input=emission, label=labels, length=length)
crf_decode = self.crf_decoding(input=emission, length=length)
if is_train:
return [crf_cost]
else:
return [crf_cost, crf_decode]

View File

@@ -1,457 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import json
import logging
import os
import random
import warnings
from collections import Counter
import numpy as np
import paddle
from docvqa import DocVQA
from model import LayoutXLMForTokenClassification_with_CRF
from paddlenlp.transformers import LayoutXLMModel, LayoutXLMTokenizer
warnings.filterwarnings("ignore")
logger = logging.getLogger(__name__)
def parse_args():
parser = argparse.ArgumentParser()
# yapf: disable
parser.add_argument("--model_name_or_path", default=None, type=str, required=True)
parser.add_argument("--do_train", default=False, type=bool, required=False)
parser.add_argument("--do_test", default=False, type=bool, required=False)
parser.add_argument("--test_file", default=None, type=str, required=False)
parser.add_argument("--train_file", default=None, type=str, required=False)
parser.add_argument("--output_dir", default=None, type=str, required=True)
parser.add_argument("--max_seq_len", default=512, type=int)
parser.add_argument("--max_query_length", default=20, type=int)
parser.add_argument("--max_doc_length", default=512, type=int)
parser.add_argument("--max_span_num", default=1, type=int)
parser.add_argument("--per_gpu_train_batch_size", default=8, type=int, help="Batch size per GPU/CPU for training.")
parser.add_argument("--per_gpu_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for eval.")
parser.add_argument("--learning_rate", default=5e-5, type=float, help="The initial learning rate for Adam.")
parser.add_argument("--weight_decay", default=0.0, type=float, help="Weight decay if we apply some.")
parser.add_argument("--adam_epsilon", default=1e-8, type=float, help="Epsilon for Adam optimizer.")
parser.add_argument("--num_train_epochs", default=3, type=int, help="Total number of training epochs to perform.")
parser.add_argument("--warmup_steps", default=0, type=int, help="Linear warmup over warmup_steps.")
parser.add_argument("--eval_steps", type=int, default=10, help="eval every X updates steps.")
parser.add_argument("--save_steps", type=int, default=50, help="Save checkpoint every X updates steps.")
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
parser.add_argument("--init_checkpoint", type=str, default=None, help="the initialized checkpoint")
parser.add_argument("--save_path", type=str, default=None, help="the initialized checkpoint")
# yapf: enable
args = parser.parse_args()
return args
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
paddle.seed(args.seed)
def get_label_maps():
labels = ["O", "I-ans", "B-ans", "E-ans"]
label2id_map = {label: idx for idx, label in enumerate(labels)}
id2label_map = {idx: label for idx, label in enumerate(labels)}
return label2id_map, id2label_map
def main(args):
os.makedirs(args.output_dir, exist_ok=True)
logging.basicConfig(
filename=os.path.join(args.output_dir, "train.log") if paddle.distributed.get_rank() == 0 else None,
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO if paddle.distributed.get_rank() == 0 else logging.WARN,
)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)
label2id_map, id2label_map = get_label_maps()
pad_token_label_id = paddle.nn.CrossEntropyLoss().ignore_index
# dist mode
if paddle.distributed.get_world_size() > 1:
paddle.distributed.init_parallel_env()
tokenizer = LayoutXLMTokenizer.from_pretrained(args.model_name_or_path)
if args.do_test:
model = LayoutXLMForTokenClassification_with_CRF.from_pretrained(args.init_checkpoint)
evaluate(args, model, tokenizer, label2id_map, id2label_map, pad_token_label_id, global_step=0)
exit(0)
if args.init_checkpoint:
logger.info("Init checkpoint from {}".format(args.init_checkpoint))
model = LayoutXLMForTokenClassification_with_CRF.from_pretrained(args.init_checkpoint)
else:
base_model = LayoutXLMModel.from_pretrained(args.model_name_or_path)
model = LayoutXLMForTokenClassification_with_CRF(base_model, num_classes=len(label2id_map), dropout=None)
# dist mode
if paddle.distributed.get_world_size() > 1:
model = paddle.DataParallel(model)
train_dataset = DocVQA(
args,
tokenizer,
label2id_map,
max_seq_len=args.max_seq_len,
max_query_length=args.max_query_length,
max_doc_length=args.max_doc_length,
max_span_num=args.max_span_num,
)
train_sampler = paddle.io.DistributedBatchSampler(
train_dataset, batch_size=args.per_gpu_train_batch_size, shuffle=False
)
args.train_batch_size = args.per_gpu_train_batch_size * max(1, paddle.distributed.get_world_size())
train_dataloader = paddle.io.DataLoader(
train_dataset, batch_sampler=train_sampler, num_workers=0, use_shared_memory=True, collate_fn=None
)
t_total = len(train_dataloader) * args.num_train_epochs
# build linear decay with warmup lr sch
lr_scheduler = paddle.optimizer.lr.PolynomialDecay(
learning_rate=args.learning_rate, decay_steps=t_total, end_lr=0.0, power=1.0
)
if args.warmup_steps > 0:
lr_scheduler = paddle.optimizer.lr.LinearWarmup(
lr_scheduler, args.warmup_steps, start_lr=0, end_lr=args.learning_rate
)
optimizer = paddle.optimizer.AdamW(
learning_rate=lr_scheduler,
parameters=model.parameters(),
epsilon=args.adam_epsilon,
weight_decay=args.weight_decay,
)
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(train_dataset))
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
logger.info(
" Total train batch size (w. parallel, distributed) = %d",
args.train_batch_size * paddle.distributed.get_world_size(),
)
logger.info(" Total optimization steps = %d", t_total)
global_step = 0
tr_loss = 0.0
set_seed(args)
for epoch_id in range(args.num_train_epochs):
print("epoch id:{}".format(epoch_id))
for step, batch in enumerate(train_dataloader):
model.train()
input_ids, input_mask, segment_ids, bboxes, labels = batch
if input_ids.shape[0] != args.per_gpu_train_batch_size:
continue
outputs = model(
input_ids=input_ids,
bbox=bboxes,
attention_mask=input_mask,
token_type_ids=segment_ids,
labels=labels,
is_train=True,
)
# model outputs are always tuple in paddlenlp (see doc)
loss = outputs[0]
loss = loss.mean()
if global_step % 50 == 0:
logger.info(
"[epoch {}/{}][iter: {}/{}] lr: {:.5f}, train loss: {:.5f}, ".format(
epoch_id,
args.num_train_epochs,
step,
len(train_dataloader),
lr_scheduler.get_lr(),
float(loss),
)
)
loss.backward()
tr_loss += loss.item()
optimizer.step()
lr_scheduler.step() # Update learning rate schedule
optimizer.clear_grad()
global_step += 1
if paddle.distributed.get_rank() == 0 and args.save_steps > 0 and global_step % args.save_steps == 0:
# Save model checkpoint
output_dir = os.path.join(args.output_dir, "checkpoint-{}".format(global_step))
os.makedirs(output_dir, exist_ok=True)
if paddle.distributed.get_rank() == 0:
model.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)
paddle.save(args, os.path.join(output_dir, "training_args.bin"))
logger.info("Saving model checkpoint to %s", output_dir)
def _tokenize_chinese_chars(text):
"""
:param text: input text, unicode string
:return:
tokenized text, list
"""
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
if (
(cp >= 0x4E00 and cp <= 0x9FFF)
or (cp >= 0x3400 and cp <= 0x4DBF) #
or (cp >= 0x20000 and cp <= 0x2A6DF) #
or (cp >= 0x2A700 and cp <= 0x2B73F) #
or (cp >= 0x2B740 and cp <= 0x2B81F) #
or (cp >= 0x2B820 and cp <= 0x2CEAF) #
or (cp >= 0xF900 and cp <= 0xFAFF)
or (cp >= 0x2F800 and cp <= 0x2FA1F) #
): #
return True
return False
output = []
buff = ""
for char in text:
cp = ord(char)
if _is_chinese_char(cp) or char == "=":
if buff != "":
output.append(buff)
buff = ""
output.append(char)
else:
buff += char
if buff != "":
output.append(buff)
return output
def fast_f1(text1, text2):
common_char = Counter(text1) & Counter(text2)
len_seq1 = len(text1)
len_seq2 = len(text2)
len_common = sum(common_char.values())
if len_common == 0:
return 0.0
precision = 1.0 * len_common / len_seq2
recall = 1.0 * len_common / len_seq1
return (2.0 * precision * recall) / (precision + recall)
def _normalize(in_str):
"""
normalize the input unicode string
"""
in_str = in_str.lower()
sp_char = [
":",
"_",
"`",
",",
"。",
":",
"?",
"!",
"(",
")",
"“",
"”",
";",
"’",
"《",
"》",
"……",
"·",
"、",
",",
"「",
"」",
"(",
")",
"-",
"~",
"『",
"』",
"|",
]
out_segs = []
for char in in_str:
if char in sp_char:
continue
else:
out_segs.append(char)
return "".join(out_segs)
def calc_f1_score(answer, prediction):
ans_segs = _tokenize_chinese_chars(_normalize(answer))
prediction_segs = _tokenize_chinese_chars(_normalize(prediction))
f1 = fast_f1(prediction_segs, ans_segs)
return f1
def decode(tokenizer, res):
sep_id = tokenizer._convert_token_to_id("</s>")
text_res = []
all_f1 = []
save_f1 = []
for i in range(len(res)):
input_ids, label_ids, predict_ids, bbox = res[i]
remove_pos = (
len(" ".join([str(x) for x in input_ids]).split("2 6 ")[0].strip(" ").split(" ")) + 2
) # remove the question bbox and sep bbox
start_pos = input_ids.index(sep_id)
query_text = []
for idx in range(1, start_pos):
input_id = input_ids[idx]
query_text.append(tokenizer._convert_id_to_token(int(input_id)))
# label texts and predict texts
text_label, text_predict = [], []
label_bbox_index, predict_bbox_index = [], []
for idx in range(start_pos + 1, len(input_ids)):
input_id, label_id, predict_id = input_ids[idx], label_ids[idx], predict_ids[idx]
if label_id in [1, 2, 3]:
text_label.append(tokenizer._convert_id_to_token(int(input_id)))
label_bbox_index.append(idx - remove_pos + 1)
if predict_id in [1, 2, 3]:
text_predict.append(tokenizer._convert_id_to_token(int(input_id)))
predict_bbox_index.append(idx - remove_pos + 1)
text_res.append(
["".join(query_text), "".join(text_label), "".join(text_predict), label_bbox_index, predict_bbox_index]
)
f1 = calc_f1_score("".join(text_label), "".join(text_predict))
save_f1.append(f1)
if len("".join(text_label)) > 10:
all_f1.append(f1)
if len(all_f1) > 0:
print("F1: ", sum(all_f1) / len(all_f1))
assert len(text_res) == len(save_f1)
return text_res
def evaluate(args, model, tokenizer, label2id_map, id2label_map, pad_token_label_id, prefix="", global_step=0):
eval_dataset = DocVQA(
args, tokenizer, label2id_map, max_seq_len=512, max_query_length=20, max_doc_length=512, max_span_num=1
)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, paddle.distributed.get_world_size())
eval_dataloader = paddle.io.DataLoader(
eval_dataset, batch_size=args.eval_batch_size, num_workers=0, use_shared_memory=True, collate_fn=None
)
# Eval!
logger.info("***** Running evaluation %s *****", prefix)
logger.info(" Num examples = %d", len(eval_dataset))
logger.info(" Batch size = %d", args.eval_batch_size)
model.eval()
res = []
for idx, batch in enumerate(eval_dataloader):
with paddle.no_grad():
input_ids, input_mask, segment_ids, bboxes, labels = batch
if input_ids.shape[0] != args.eval_batch_size:
continue
outputs = model(
input_ids=input_ids,
bbox=bboxes,
attention_mask=input_mask,
token_type_ids=segment_ids,
labels=labels,
is_train=False,
)
labels = labels.numpy()
crf_decode = outputs[1].numpy()
bboxes = bboxes.squeeze().numpy()
input_ids = input_ids.squeeze(axis=1).numpy()
for index in range(input_ids.shape[0]):
res.append([list(input_ids[index]), list(labels[index]), list(crf_decode[index]), bboxes[index]])
origin_inputs = []
with open(args.test_file, "r", encoding="utf8") as f:
for line in f:
line = json.loads(line.strip())
origin_inputs.append(
{
"img_name": line["img_name"],
"question": line["question"],
"bboxes": line["document_bbox"],
"img_id": line["img_id"],
}
)
text_res = decode(tokenizer, res)
with open(args.save_path, "w", encoding="utf8") as f:
for line_res, line_text, line_label in zip(res, text_res, origin_inputs):
line_json = {}
line_json["img_name"] = line_label["img_name"]
line_json["img_id"] = line_label["img_id"]
line_json["question"] = line_label["question"]
line_json["label_answer"] = line_text[1]
line_json["predict_answer"] = line_text[2]
label_bbox_index, predict_bbox_index = line_text[3], line_text[4]
label_bboxes, predict_bboxes = [], []
for i in range(len(line_label["bboxes"])):
if i in label_bbox_index:
label_bboxes.append(line_label["bboxes"][i])
if i in predict_bbox_index:
predict_bboxes.append(line_label["bboxes"][i])
line_json["label_bboxes"] = label_bboxes
line_json["predict_bboxes"] = predict_bboxes
json.dump(line_json, f, ensure_ascii=False)
f.write("\n")
def print_arguments(args):
"""print arguments"""
print("----------- Configuration Arguments -----------")
for arg, value in sorted(vars(args).items()):
print("%s: %s" % (arg, value))
print("------------------------------------------------")
if __name__ == "__main__":
args = parse_args()
print_arguments(args)
main(args)

View File

@@ -1,38 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
export CUDA_VISIBLE_DEVICES=0
QUESTION=$1
python3 change_to_mrc.py ${QUESTION}
python3 ./run_docvqa.py \
--model_name_or_path "layoutxlm-base-uncased" \
--max_seq_len 512 \
--do_test true \
--test_file "data/demo_test.json" \
--num_train_epochs 100 \
--eval_steps 6000 \
--save_steps 6000 \
--output_dir "output/" \
--save_path "data/decode_res.json" \
--init_checkpoint "./checkpoints/layoutxlm/" \
--learning_rate 3e-5 \
--warmup_steps 12000 \
--per_gpu_train_batch_size 4 \
--per_gpu_eval_batch_size 1 \
--seed 2048
python3 view.py

View File

@@ -1,32 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
export CUDA_VISIBLE_DEVICES=0
python3 ./run_docvqa.py \
--model_name_or_path "layoutxlm-base-uncased" \
--max_seq_len 512 \
--train_file "data/train.json" \
--init_checkpoint "checkpoints/base_model" \
--do_train true \
--num_train_epochs 50 \
--eval_steps 24000 \
--save_steps 40 \
--output_dir "output" \
--save_path "data/decode_res.json" \
--learning_rate 3e-5 \
--warmup_steps 40 \
--per_gpu_train_batch_size 4 \
--per_gpu_eval_batch_size 4 \
--seed 2048

View File

@@ -1,67 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import cv2
import json
import numpy as np
def view_ocr_result(img_path, bboxes, opath):
image = cv2.imread(img_path)
for char_bbox in bboxes:
x_min, x_max, y_min, y_max = char_bbox
cv2.rectangle(image, (x_min, y_min), (x_max, y_max), (0, 0, 255), 1)
cv2.imwrite(opath, image)
def _highlight_bbox(img, bbox):
x = bbox[0]
w = bbox[1] - x
y = bbox[2]
h = bbox[3] - y
sub_img = img[y : y + h, x : x + w]
colored_rect = np.zeros(sub_img.shape, dtype=np.uint8)
colored_rect[:, :, 2] = 255
colored_rect[:, :, 1] = 255
res = cv2.addWeighted(sub_img, 0.5, colored_rect, 0.5, 1.0)
img[y : y + h, x : x + w] = res
def highlight_ans(source_img_path, output_img_path, ans_bbox):
image = cv2.imread(source_img_path)
for bbox in ans_bbox:
_highlight_bbox(image, bbox)
cv2.imwrite(output_img_path, image)
def highlight_img(source_img_path, output_img_path):
image = cv2.imread(source_img_path)
height = image.shape[0]
width = image.shape[1]
bbox = [0, width - 1, 0, height - 1]
_highlight_bbox(image, bbox)
cv2.imwrite(output_img_path, image)
if __name__ == "__main__":
res_path = "./data/decode_res.json"
result = {}
with open(res_path, "r", encoding="utf-8") as f:
line = f.readline()
result = json.loads(line.strip())
img_path = "../OCR_process/demo_pics/demo_{}.png".format(result["img_id"])
img_save_path = "../answer.png"
highlight_ans(img_path, img_save_path, result["predict_bboxes"])
print("extraction result has been saved to answer.png")

View File

@@ -1,272 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import os
import re
from paddleocr import PaddleOCR
from paddlenlp.transformers import LayoutXLMTokenizer
tokenizer = LayoutXLMTokenizer.from_pretrained("layoutxlm-base-uncased")
def get_all_chars(tokenizer):
all_chr = []
for i in range(30000):
tok_chr = tokenizer.tokenize(chr(i))
tok_chr = [tc.replace("▁", "") for tc in tok_chr]
while "" in tok_chr:
tok_chr.remove("")
tok_chr = "".join(tok_chr)
if len(tok_chr) != 1:
all_chr.append(i)
return all_chr
def merge_bbox(tok_bboxes):
min_gx = min([box[0] for box in tok_bboxes])
max_gx = max([box[1] for box in tok_bboxes])
min_gy = min([box[2] for box in tok_bboxes])
max_gy = max([box[3] for box in tok_bboxes])
height_g = max_gy - min_gy
width_g = max_gx - min_gx
height_m = 0
width_m = 0
for box in tok_bboxes:
x_min, x_max, y_min, y_max = box
height_m += y_max - y_min
width_m += x_max - x_min
height_m = height_m / len(tok_bboxes)
if (height_g - height_m) < 0.5 * height_m and width_g - width_m < 0.1 * width_m:
return False, [min_gx, max_gx, min_gy, max_gy]
else:
return True, tok_bboxes[0]
def xlm_parse(ocr_res, tokenizer):
doc_bboxes = []
all_chr = get_all_chars(tokenizer)
try:
new_tokens, new_token_boxes = [], []
for item in ocr_res:
new_tokens.extend(item["tokens"])
new_token_boxes.extend(item["token_box"])
# get layoutxlm tokenizer results and get the final results
temp_span_text = "".join(new_tokens)
temp_span_bbox = new_token_boxes
span_text = ""
span_bbox = []
# drop blank space
for text, bbox in zip(temp_span_text, temp_span_bbox):
if text == " ":
continue
else:
span_text += text
span_bbox += [bbox]
# span_tokens starts with "_"
span_tokens = tokenizer.tokenize(span_text)
span_tokens[0] = span_tokens[0].replace("▁", "")
while "" in span_tokens:
span_tokens.remove("")
doc_bboxes = []
i = 0
for tid, tok in enumerate(span_tokens):
tok = tok.replace("▁", "")
if tok == "":
doc_bboxes.append(span_bbox[i])
continue
if tok == "<unk>":
if tid + 1 == len(span_tokens):
tok_len = 1
else:
if span_tokens[tid + 1] == "<unk>":
tok_len = 1
else:
for j in range(i, len(span_text)):
if span_text[j].lower() == span_tokens[tid + 1][0]:
break
tok_len = j - i
elif ord(span_text[i]) in all_chr:
if tid + 1 == len(span_tokens):
tok_len = 1
elif "°" in tok and "C" in span_tokens[tid + 1]:
tok_len = len(tok) - 1
if tok_len == 0:
doc_bboxes.append(span_bbox[i])
continue
elif span_text[i] == "ⅱ":
if tok == "ii":
if span_text[i + 1] != "i":
tok_len = len(tok) - 1
else:
tok_len = len(tok)
elif tok == "i":
tok_len = len(tok) - 1
if tok_len == 0:
doc_bboxes.append(span_bbox[i])
continue
elif "m" in tok and "2" == span_tokens[tid + 1][0]:
tok_len = len(tok) - 1
if tok_len == 0:
doc_bboxes.append(span_bbox[i])
continue
elif ord(span_text[i + 1]) in all_chr:
tok_len = 1
else:
for j in range(i, len(span_text)):
if span_text[j].lower() == span_tokens[tid + 1][0]:
break
if span_text[j].lower() == "," and span_tokens[tid + 1][0] == ",":
break
if span_text[j].lower() == ";" and span_tokens[tid + 1][0] == ";":
break
if span_text[j].lower() == ")" and span_tokens[tid + 1][0] == ")":
break
if span_text[j].lower() == "(" and span_tokens[tid + 1][0] == "(":
break
if span_text[j].lower() == "¥" and span_tokens[tid + 1][0] == "¥":
break
tok_len = j - i
else:
if "<EFBFBD>" == span_text[i]:
tok_len = len(tok) + 1
elif tok == "......" and "…" in span_text[i : i + 6]:
tok_len = len(tok) - 2
elif "ⅱ" in span_text[i + len(tok) - 1]:
if tok == "i":
tok_len = 1
else:
tok_len = len(tok) - 1
elif "°" in tok and "C" in span_tokens[tid + 1]:
tok_len = len(tok) - 1
else:
tok_len = len(tok)
assert i + tok_len <= len(span_bbox)
tok_bboxes = span_bbox[i : i + tok_len]
_, merged_bbox = merge_bbox(tok_bboxes)
doc_bboxes.append(merged_bbox)
i = i + tok_len
except Exception:
print("Error")
span_tokens = ["▁"] * 512
doc_bboxes = [[0, 0, 0, 0]] * 512
return span_tokens, doc_bboxes
def tokenize_ocr_res(ocr_reses):
"""
input:
ocr_res: the ocr result of the image
return:
new_reses: {
pid: {
"text": all text in each ocr_res,
"bounding_box": the bounding box of the ocr_res,
"tokens": all chars in ocr_res,
"token_box: bounding box of each chars in ocr_res
}
}
"""
new_reses = []
for img_name, ocr_res in ocr_reses:
new_res = []
for para in ocr_res:
text = para["text"]
text_box = para["bbox"]
x_min, y_min = [int(min(idx)) for idx in zip(*text_box)]
x_max, y_max = [int(max(idx)) for idx in zip(*text_box)]
text_chars = list(text.lower())
char_num = 0
for char in text_chars:
if re.match("[^\x00-\xff]", char):
char_num += 2
else:
char_num += 1
width = x_max - x_min
shift = x_min
new_token_boxes, new_tokens = [], []
for char in text_chars:
if re.match("[^\x00-\xff]", char):
tok_x_max = shift + width / char_num * 2
else:
tok_x_max = shift + width / char_num * 1
tok_x_min = shift
tok_y_min = y_min
tok_y_max = y_max
shift = tok_x_max
new_token_boxes.append([round(tok_x_min), round(tok_x_max), tok_y_min, tok_y_max])
new_tokens.append(char)
new_res.append(
{
"text": para["text"],
"bounding_box": para["bbox"],
"tokens": new_tokens,
"token_box": new_token_boxes,
}
)
new_reses.append((img_name, new_res))
return new_reses
def process_input(ocr_reses, tokenizer, save_ocr_path):
ocr_reses = tokenize_ocr_res(ocr_reses)
examples = []
for img_name, ocr_res in ocr_reses:
doc_tokens, doc_bboxes = xlm_parse(ocr_res, tokenizer)
doc_tokens.insert(0, "▁")
doc_bboxes.insert(0, doc_bboxes[0])
example = {"img_name": img_name, "document": doc_tokens, "document_bbox": doc_bboxes}
examples.append(example)
with open(save_ocr_path, "w", encoding="utf8") as f:
for example in examples:
json.dump(example, f, ensure_ascii=False)
f.write("\n")
print(f"ocr parsing results has been save to: {save_ocr_path}")
def ocr_preprocess(img_dir):
ocr = PaddleOCR(use_angle_cls=True, lang="ch", use_gpu=True)
ocr_reses = []
img_names = sorted(os.listdir(img_dir), key=lambda x: int(x.split("_")[1].split(".")[0]))
for img_name in img_names:
img_path = os.path.join(img_dir, img_name)
parsing_res = ocr.ocr(img_path, cls=True)[0]
ocr_res = []
for para in parsing_res:
ocr_res.append({"text": para[1][0], "bbox": para[0]})
ocr_reses.append((img_name, ocr_res))
return ocr_reses
if __name__ == "__main__":
img_dir = "./demo_pics"
save_path = "./demo_ocr_res.json"
ocr_results = ocr_preprocess(img_dir)
process_input(ocr_results, tokenizer, save_path)

View File

@@ -1,131 +0,0 @@
# 汽车说明书跨模态智能问答
## 1. 项目说明
**跨模态文档问答** 是跨模态的文档抽取任务,要求文档智能模型在文档中抽取能够回答文档相关问题的答案,需要模型在抽取和理解文档中文本信息的同时,还能充分利用文档的布局、字体、颜色等视觉信息,这比单一模态的信息抽取任务更具挑战性。
这种基于跨模态文档阅读理解技术的智能问答能力,可以深度解析非结构化文档中排版复杂的图文/图表内容,直接定位问题答案。
本项目将基于跨模态文档问答技术实现**汽车说明书问答系统**,该系统能够对用户提出的问题,自动从汽车说明书中寻找答案并进行回答。
如下图所示, 用户提出问题:"如何更换前风窗玻璃的刮水片",跨模态文档问答引擎将从库中寻找相关的文档,然后通过跨模态阅读理解模型抽取出相应的答案,并进行了高亮展示。
<center><img width="883" alt="image" src="https://user-images.githubusercontent.com/35913314/169781111-0734729d-3c7b-400d-8e92-e56548bb7dc5.png"></center>
通过使用汽车说明书问答系统,能够极大地解决传统汽车售后的压力:
- 用户:用户没有耐心查阅说明书,打客服电话需要等待
- 售后客服:需要配置大量客服人员,且客服专业知识培训周期长
- 构建问题库:需要投入大量人力整理常见问题库,并且固定的问题库难以覆盖灵活多变的提问
对于用户来说,汽车说明书问答系统能够支持通过车机助手/APP/小程序为用户提供即问即答的功能。对于常见问题,用户不再需要查阅说明书,也无需打客服电话,从而缓解了人工客服的压力。
对于客服来讲,汽车说明书问答系统帮助客服人员快速定位答案,高效查阅文档,提高客服的专业水平,同时也能够缩短客服的培训周期。
## 2. 安装说明
#### 环境要求
- paddlepaddle == 2.3.2
- paddlenlp == 2.5.2
- paddleocr == 2.6.1.3
安装相关问题可参考[PaddlePaddle](https://www.paddlepaddle.org.cn/install/quick?docurl=/documentation/docs/zh/install/pip/linux-pip.html)和[PaddleNLP](https://paddlenlp.readthedocs.io/zh/latest/get_started/installation.html)文档。
## 3. 整体流程
汽车说明书问答系统针对用户提出的汽车使用相关问题,智能化地在汽车说明书中找出对应答案,并返回给用户。本项目提供的汽车说明书问答系统的使用流程如下图所示。本项目提供的汽车说明书问答系统主要包括 3 个模块:OCR处理模块、排序模块和跨模态阅读理解模块。
在使用汽车说明书问答模型回答问题之前,需要先使用PaddleOCR对离线提供的汽车说明书文档进解析,并将解析结果保存下来,以备后续排序模块使用。
对于用户提问的问题,首先会被传入排序模块,排序模块会针对该问题对解析的文档进行排序打分,其结果将会被传入跨模态阅读理解模块。阅读理解模块将从分数最高的说明书文档中,抽取用户问题的答案,并返回给用户。
<center><img width="864" alt="image" src="https://user-images.githubusercontent.com/35913314/170222662-c438ff2a-a1df-44e5-8a83-f14dc0814b9d.png"></center>
下面将具体介绍各个模块的功能。
## 4. OCR处理模块
本项目提供了包含10张图片的汽车说明书,为方便后续处理,首先需要通过 PaddleOCR 对汽车说明书进行识别,记录汽车说明书上的文字和文字布局信息, 以方便后续使用计算机视觉和自然语言处理方面的技术进行问答任务。
本项目提供的汽车说明书图片可点击[这里](https://paddlenlp.bj.bcebos.com/images/applications/automobile.tar.gz)进行下载,下载后解压放至 `./OCR_process/demo_pics` 目录下,然后通过如下命令,使用 PaddleOCR 对图片进行解析。
```shell
cd OCR_process/
python3 ocr_process.py
cd ..
```
解析后的结果存放至 `./OCR_process/demo_ocr_res.json` 中。
## 5. 排序模块
对于用户提出的问题,如果从所有的汽车说明书图片中去寻找答案会比较耗时且耗费资源。因此这里使用了一个基于[RocketQA](https://arxiv.org/pdf/2010.08191.pdf)的排序模块,该模块将根据用户提出的问题对汽车说明书的不同图片进行打分排序,这样便可以获取和问题最相关的图片,并使用跨模态阅读理解模块在该问题上进行抽取答案。
本项目提供了140条汽车说明书相关的训练样本,用于排序模型的训练, 同时也提供了一个基于RocketQA的预先训练好的基线模型 base_model。 本模块可以使用 base_model 在汽车说明书训练样本上进一步微调。
其中,汽车说明书的训练集可点击[这里](https://paddlenlp.bj.bcebos.com/data/automobile_rerank_train.tsv) 进行下载,下载后将其重命名为 `train.tsv` ,存放至 `./Rerank/data/` 目录下。
同时,base_model 是 [Dureader retrieval](https://arxiv.org/abs/2203.10232) 数据集训练的排序模型, 可点击[这里](https://paddlenlp.bj.bcebos.com/models/base_ranker.tar.gz) 进行下载,解压后可获得包含模型的目录 `base_model`,将其放至 `./Rerank/checkpoints` 目录下。
可使用如下代码进行训练:
```shell
cd Rerank
bash run_train.sh ./data/train.tsv ./checkpoints/base_model 50 1
cd ..
```
其中,参数依次为训练数据地址,base_model 地址,训练轮次,节点数。
在模型训练完成后,可将模型重命名为 `ranker` 存放至 `./checkpoints/` 目录下,接下来便可以使用如下命令,根据给定的汽车说明书相关问题,对汽车说明书的图片进行打分。代码如下:
```shell
cd Rerank
bash run_test.sh 后备箱怎么开
cd ..
```
其中,后一项为用户问题,命令执行完成后,分数文件将会保存至 `./Rerank/data/demo.score` 中。
## 6. 跨模态阅读理解模块
本项目首先获取排序模块输出的结果中评分最高的图片,然后将会使用跨模态的语言模型 LayoutXLM 从该图片中去抽取用户提问的答案。在获取答案后,将会对答案在该图片中进行高亮显示并返回用户。
本项目提供了28条汽车说明书相关的训练样本,用于跨模态阅读理解模型的训练, 同时也提供了一个预先训练好的基线模型 base_model。 本模块可以使用 base_model 在汽车说明书训练样本上进一步微调,增强模型对汽车说明书领域的理解。
其中,汽车说明书的阅读理解训练集可点击[这里](https://paddlenlp.bj.bcebos.com/data/automobile_mrc_train.json) 进行下载,下载后将其重命名为 `train.json`,存放至 `./Extraction/data/` 目录下。
同时,base_model 是 [Dureader VIS](https://aclanthology.org/2022.findings-acl.105.pdf) 数据集训练的跨模态阅读理解模型, 可点击[这里](https://paddlenlp.bj.bcebos.com/models/base_mrc.tar.gz) 进行下载,解压后可获得包含模型的目录 `base_model`,将其放至 `./Extraction/checkpoints` 目录下。
可使用如下代码进行训练:
```shell
cd Extraction
bash run_train.sh
cd ..
```
在模型训练完成后,可将模型重命名为 `layoutxlm` 存放至 `./checkpoints/` 目录下,接下来便可以使用如下命令,根据给定的汽车说明书相关问题,从得分最高的汽车说明书图片中抽取答案。代码如下:
```shell
cd Extraction
bash run_test.sh 后备箱怎么开
cd ..
```
其中,后一项为用户问题,命令执行完成后,最终结果将会保存至 `./answer.png` 中。
## 7. 全流程预测
本项目提供了全流程预测的功能,可通过如下命令进行一键式预测:
```shell
bash run_test.sh 后备箱怎么开
```
其中,后一项参数为用户问题,最终结果将会保存至 `./answer.png` 中。
**备注**:在运行命令前,请确保已使用第4节介绍的命令对原始汽车说明书图片完成了文档解析。
下图展示了用户提问的三个问题:"后备箱怎么开","钥匙怎么充电" 和 "NFC解锁注意事项", 可以看到,本项目的汽车说明书问答系统能够精准地找到答案并进行高亮显示。
<center><img src="https://user-images.githubusercontent.com/35913314/169012902-1a42bd14-976f-4da8-b5b5-d8e7352b68df.png"/></center>

View File

@@ -1,33 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import json
question = sys.argv[1]
with open("../OCR_process/demo_ocr_res.json", "r", encoding="utf8") as f:
paras = []
for line in f:
line = json.loads(line.strip())
document = line["document"]
para = []
for token in document:
token = token.replace("▁", "")
para.append(token)
paras.append("".join(para))
with open("./data/demo.tsv", "w", encoding="utf8") as f:
for para in paras:
f.write("{}\t\t{}\t0\n".format(question, para))

View File

@@ -1,12 +0,0 @@
{
"attention_probs_dropout_prob": 0.1,
"hidden_act": "relu",
"hidden_dropout_prob": 0.1,
"hidden_size": 768,
"initializer_range": 0.02,
"max_position_embeddings": 513,
"num_attention_heads": 12,
"num_hidden_layers": 12,
"type_vocab_size": 2,
"vocab_size": 18000
}

View File

@@ -1,45 +0,0 @@
#!/bin/bash
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
export CUDA_VISIBLE_DEVICES=0
QUESTION=$1
if [ ! -d output ]; then
mkdir output
fi
if [ ! -d log ]; then
mkdir log
fi
python3 change_to_rerank.py ${QUESTION}
python3 -u ./src/train_ce.py \
--use_cuda true \
--verbose true \
--do_train false \
--do_val false \
--do_test true \
--batch_size 128 \
--init_checkpoint "./checkpoints/ranker" \
--test_set "./data/demo.tsv" \
--test_save "data/demo.score" \
--max_seq_len 384 \
--for_cn true \
--vocab_path "config/ernie_base_1.0_CN/vocab.txt" \
--ernie_config_path "config/ernie_base_1.0_CN/ernie_config.json"
1>>log/train.log 2>&1

View File

@@ -1,72 +0,0 @@
#!/bin/bash
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
export CUDA_VISIBLE_DEVICES=0
if [ $# != 4 ];then
echo "USAGE: sh run_train.sh \$TRAIN_SET \$MODEL_PATH \$epoch \$nodes_count"
exit 1
fi
TRAIN_SET=$1
MODEL_PATH=$2
epoch=$3
node=$4
CHECKPOINT_PATH=output
if [ ! -d output ]; then
mkdir output
fi
if [ ! -d log ]; then
mkdir log
fi
lr=1e-5
batch_size=32
train_exampls=`cat $TRAIN_SET | wc -l`
save_steps=$[$train_exampls/$batch_size/$node]
data_size=$[$save_steps*$batch_size*$node]
new_save_steps=$[$save_steps*$epoch/2]
python3 -m paddle.distributed.launch \
--log_dir log \
./src/train_ce.py \
--use_cuda true \
--verbose true \
--do_train true \
--do_val false \
--do_test false \
--use_mix_precision false \
--train_data_size ${data_size} \
--batch_size ${batch_size} \
--init_pretraining_params ${MODEL_PATH} \
--train_set ${TRAIN_SET} \
--save_steps ${new_save_steps} \
--validation_steps ${new_save_steps} \
--checkpoints ${CHECKPOINT_PATH} \
--weight_decay 0.01 \
--warmup_proportion 0.0 \
--epoch $epoch \
--max_seq_len 384 \
--for_cn true \
--vocab_path config/ernie_base_1.0_CN/vocab.txt \
--ernie_config_path config/ernie_base_1.0_CN/ernie_config.json \
--learning_rate ${lr} \
--skip_steps 10 \
--num_iteration_per_drop_scope 1 \
--num_labels 2 \
--random_seed 1

View File

@@ -1,69 +0,0 @@
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Mask, padding and batching."""
import numpy as np
def pad_batch_data(
insts,
pad_idx=0,
return_pos=False,
return_input_mask=False,
return_max_len=False,
return_num_token=False,
return_seq_lens=False,
):
"""
Pad the instances to the max sequence length in batch, and generate the
corresponding position data and attention bias.
"""
return_list = []
max_len = max(len(inst) for inst in insts)
# Any token included in dict can be used to pad, since the paddings' loss
# will be masked out by weights and make no effect on parameter gradients.
inst_data = np.array([inst + list([pad_idx] * (max_len - len(inst))) for inst in insts])
return_list += [inst_data.astype("int64").reshape([-1, max_len, 1])]
# position data
if return_pos:
inst_pos = np.array([list(range(0, len(inst))) + [pad_idx] * (max_len - len(inst)) for inst in insts])
return_list += [inst_pos.astype("int64").reshape([-1, max_len, 1])]
if return_input_mask:
# This is used to avoid attention on paddings.
input_mask_data = np.array([[1] * len(inst) + [0] * (max_len - len(inst)) for inst in insts])
input_mask_data = np.expand_dims(input_mask_data, axis=-1)
return_list += [input_mask_data.astype("float32")]
if return_max_len:
return_list += [max_len]
if return_num_token:
num_token = 0
for inst in insts:
num_token += len(inst)
return_list += [num_token]
if return_seq_lens:
seq_lens = np.array([len(inst) for inst in insts])
return_list += [seq_lens.astype("int64").reshape([-1, 1])]
return return_list if len(return_list) > 1 else return_list[0]
if __name__ == "__main__":
pass

View File

@@ -1,333 +0,0 @@
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Model for classifier."""
import logging
import time
import numpy as np
import paddle.fluid as fluid
from model.ernie import ErnieModel
from scipy.stats import pearsonr, spearmanr
log = logging.getLogger(__name__)
def create_model(args, pyreader_name, ernie_config, is_prediction=False, task_name=""):
pyreader = fluid.layers.py_reader(
capacity=50,
shapes=[
[-1, args.max_seq_len, 1],
[-1, args.max_seq_len, 1],
[-1, args.max_seq_len, 1],
[-1, args.max_seq_len, 1],
[-1, args.max_seq_len, 1],
[-1, 1],
[-1, 1],
],
dtypes=["int64", "int64", "int64", "int64", "float32", "int64", "int64"],
lod_levels=[0, 0, 0, 0, 0, 0, 0],
name=task_name + "_" + pyreader_name,
use_double_buffer=True,
)
(src_ids, sent_ids, pos_ids, task_ids, input_mask, labels, qids) = fluid.layers.read_file(pyreader)
def _model(is_noise=False):
ernie = ErnieModel(
src_ids=src_ids,
position_ids=pos_ids,
sentence_ids=sent_ids,
task_ids=task_ids,
input_mask=input_mask,
config=ernie_config,
is_noise=is_noise,
)
cls_feats = ernie.get_pooled_output()
if not is_noise:
cls_feats = fluid.layers.dropout(x=cls_feats, dropout_prob=0.1, dropout_implementation="upscale_in_train")
logits = fluid.layers.fc(
input=cls_feats,
size=args.num_labels,
param_attr=fluid.ParamAttr(
name=task_name + "_cls_out_w", initializer=fluid.initializer.TruncatedNormal(scale=0.02)
),
bias_attr=fluid.ParamAttr(name=task_name + "_cls_out_b", initializer=fluid.initializer.Constant(0.0)),
)
"""
if is_prediction:
probs = fluid.layers.softmax(logits)
feed_targets_name = [
src_ids.name, sent_ids.name, pos_ids.name, input_mask.name
]
if ernie_version == "2.0":
feed_targets_name += [task_ids.name]
return pyreader, probs, feed_targets_name
"""
num_seqs = fluid.layers.create_tensor(dtype="int64")
# add focal loss
ce_loss, probs = fluid.layers.softmax_with_cross_entropy(logits=logits, label=labels, return_softmax=True)
loss = fluid.layers.mean(x=ce_loss)
accuracy = fluid.layers.accuracy(input=probs, label=labels, total=num_seqs)
graph_vars = {
"loss": loss,
"probs": probs,
"accuracy": accuracy,
"labels": labels,
"num_seqs": num_seqs,
"qids": qids,
}
return graph_vars
if not is_prediction:
graph_vars = _model(is_noise=True)
old_loss = graph_vars["loss"]
token_emb = fluid.default_main_program().global_block().var("word_embedding")
token_emb.stop_gradient = False
token_gradient = fluid.gradients(old_loss, token_emb)[0]
token_gradient.stop_gradient = False
epsilon = 1e-8
norm = fluid.layers.sqrt(fluid.layers.reduce_sum(fluid.layers.square(token_gradient)) + epsilon)
gp = (0.01 * token_gradient) / norm
gp.stop_gradient = True
fluid.layers.assign(token_emb + gp, token_emb)
graph_vars = _model()
fluid.layers.assign(token_emb - gp, token_emb)
else:
graph_vars = _model()
return pyreader, graph_vars
def evaluate_mrr(preds):
last_qid = None
total_mrr = 0.0
qnum = 0.0
rank = 0.0
correct = False
for qid, score, label in preds:
if qid != last_qid:
rank = 0.0
qnum += 1
correct = False
last_qid = qid
rank += 1
if not correct and label != 0:
total_mrr += 1.0 / rank
correct = True
return total_mrr / qnum
def evaluate(
exe, test_program, test_pyreader, graph_vars, eval_phase, use_multi_gpu_test=False, metric="simple_accuracy"
):
train_fetch_list = [graph_vars["loss"].name, graph_vars["accuracy"].name, graph_vars["num_seqs"].name]
if eval_phase == "train":
if "learning_rate" in graph_vars:
train_fetch_list.append(graph_vars["learning_rate"].name)
outputs = exe.run(fetch_list=train_fetch_list, program=test_program)
ret = {"loss": np.mean(outputs[0]), "accuracy": np.mean(outputs[1])}
if "learning_rate" in graph_vars:
ret["learning_rate"] = float(outputs[3][0])
return ret
test_pyreader.start()
total_cost = 0.0
total_acc = 0.0
total_num_seqs = 0.0
total_label_pos_num = 0.0
total_pred_pos_num = 0.0
total_correct_num = 0.0
qids, labels, scores, preds = [], [], [], []
time_begin = time.time()
fetch_list = [
graph_vars["loss"].name,
graph_vars["accuracy"].name,
graph_vars["probs"].name,
graph_vars["labels"].name,
graph_vars["num_seqs"].name,
graph_vars["qids"].name,
]
while True:
try:
if use_multi_gpu_test:
np_loss, np_acc, np_probs, np_labels, np_num_seqs, np_qids = exe.run(fetch_list=fetch_list)
else:
np_loss, np_acc, np_probs, np_labels, np_num_seqs, np_qids = exe.run(
program=test_program, fetch_list=fetch_list
)
total_cost += np.sum(np_loss * np_num_seqs)
total_acc += np.sum(np_acc * np_num_seqs)
total_num_seqs += np.sum(np_num_seqs)
labels.extend(np_labels.reshape((-1)).tolist())
if np_qids is None:
np_qids = np.array([])
qids.extend(np_qids.reshape(-1).tolist())
scores.extend(np_probs[:, 1].reshape(-1).tolist())
np_preds = np.argmax(np_probs, axis=1).astype(np.float32)
preds.extend(np_preds)
total_label_pos_num += np.sum(np_labels)
total_pred_pos_num += np.sum(np_preds)
total_correct_num += np.sum(np.dot(np_preds, np_labels))
except fluid.core.EOFException:
test_pyreader.reset()
break
time_end = time.time()
cost = total_cost / total_num_seqs
elapsed_time = time_end - time_begin
evaluate_info = ""
if metric == "acc_and_f1":
ret = acc_and_f1(preds, labels)
evaluate_info = "[%s evaluation] ave loss: %f, ave_acc: %f, f1: %f, data_num: %d, elapsed time: %f s" % (
eval_phase,
cost,
ret["acc"],
ret["f1"],
total_num_seqs,
elapsed_time,
)
elif metric == "matthews_corrcoef":
ret = matthews_corrcoef(preds, labels)
evaluate_info = "[%s evaluation] ave loss: %f, matthews_corrcoef: %f, data_num: %d, elapsed time: %f s" % (
eval_phase,
cost,
ret,
total_num_seqs,
elapsed_time,
)
elif metric == "pearson_and_spearman":
ret = pearson_and_spearman(scores, labels)
evaluate_info = (
"[%s evaluation] ave loss: %f, pearson:%f, spearman:%f, corr:%f, data_num: %d, elapsed time: %f s"
% (eval_phase, cost, ret["pearson"], ret["spearman"], ret["corr"], total_num_seqs, elapsed_time)
)
elif metric == "simple_accuracy":
ret = simple_accuracy(preds, labels)
evaluate_info = "[%s evaluation] ave loss: %f, acc:%f, data_num: %d, elapsed time: %f s" % (
eval_phase,
cost,
ret,
total_num_seqs,
elapsed_time,
)
elif metric == "acc_and_f1_and_mrr":
ret_a = acc_and_f1(preds, labels)
preds = sorted(zip(qids, scores, labels), key=lambda elem: (elem[0], -elem[1]))
ret_b = evaluate_mrr(preds)
evaluate_info = "[%s evaluation] ave loss: %f, acc: %f, f1: %f, mrr: %f, data_num: %d, elapsed time: %f s" % (
eval_phase,
cost,
ret_a["acc"],
ret_a["f1"],
ret_b,
total_num_seqs,
elapsed_time,
)
else:
raise ValueError("unsupported metric {}".format(metric))
return evaluate_info
def matthews_corrcoef(preds, labels):
preds = np.array(preds)
labels = np.array(labels)
tp = np.sum((labels == 1) & (preds == 1))
tn = np.sum((labels == 0) & (preds == 0))
fp = np.sum((labels == 0) & (preds == 1))
fn = np.sum((labels == 1) & (preds == 0))
mcc = ((tp * tn) - (fp * fn)) / np.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn))
return mcc
def f1_score(preds, labels):
preds = np.array(preds)
labels = np.array(labels)
tp = np.sum((labels == 1) & (preds == 1))
fp = np.sum((labels == 0) & (preds == 1))
fn = np.sum((labels == 1) & (preds == 0))
p = tp / (tp + fp)
r = tp / (tp + fn)
f1 = (2 * p * r) / (p + r + 1e-8)
return f1
def pearson_and_spearman(preds, labels):
preds = np.array(preds)
labels = np.array(labels)
pearson_corr = pearsonr(preds, labels)[0]
spearman_corr = spearmanr(preds, labels)[0]
return {
"pearson": pearson_corr,
"spearmanr": spearman_corr,
"corr": (pearson_corr + spearman_corr) / 2,
}
def acc_and_f1(preds, labels):
preds = np.array(preds)
labels = np.array(labels)
acc = simple_accuracy(preds, labels)
f1 = f1_score(preds, labels)
return {
"acc": acc,
"f1": f1,
"acc_and_f1": (acc + f1) / 2,
}
def simple_accuracy(preds, labels):
preds = np.array(preds)
labels = np.array(labels)
return (preds == labels).mean()
def predict(exe, test_program, test_pyreader, graph_vars, dev_count=1):
test_pyreader.start()
qids, probs = [], []
preds = []
fetch_list = [graph_vars["probs"].name, graph_vars["qids"].name]
while True:
try:
if dev_count == 1:
np_probs, np_qids = exe.run(program=test_program, fetch_list=fetch_list)
else:
np_probs, np_qids = exe.run(fetch_list=fetch_list)
if np_qids is None:
np_qids = np.array([])
qids.extend(np_qids.reshape(-1).tolist())
np_preds = np.argmax(np_probs, axis=1).astype(np.float32)
preds.extend(np_preds)
probs.append(np_probs)
except fluid.core.EOFException:
test_pyreader.reset()
break
probs = np.concatenate(probs, axis=0).reshape([len(preds), -1])
return qids, preds, probs

View File

@@ -1,95 +0,0 @@
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
from src.utils.args import ArgumentGroup
# yapf: disable
parser = argparse.ArgumentParser(__doc__)
model_g = ArgumentGroup(parser, "model", "model configuration and paths.")
model_g.add_arg("ernie_config_path", str, None, "Path to the json file for ernie model config.")
model_g.add_arg("init_checkpoint", str, None, "Init checkpoint to resume training from.")
model_g.add_arg("init_pretraining_params", str, None, "Init pre-training params which preforms fine-tuning from. If the arg 'init_checkpoint' has been set, this argument wouldn't be valid.")
model_g.add_arg("checkpoints", str, "checkpoints", "Path to save checkpoints.")
model_g.add_arg("is_classify", bool, True, "is_classify")
model_g.add_arg("is_regression", bool, False, "is_regression")
model_g.add_arg("task_id", int, 0, "task id")
train_g = ArgumentGroup(parser, "training", "training options.")
train_g.add_arg("epoch", int, 3, "Number of epoches for fine-tuning.")
train_g.add_arg("learning_rate", float, 5e-5, "Learning rate used to train with warmup.")
train_g.add_arg("lr_scheduler", str, "linear_warmup_decay", "scheduler of learning rate.", choices=['linear_warmup_decay', 'noam_decay'])
train_g.add_arg("weight_decay", float, 0.01, "Weight decay rate for L2 regularizer.")
train_g.add_arg("warmup_proportion", float, 0.1, "Proportion of training steps to perform linear learning rate warmup for.")
train_g.add_arg("save_steps", int, 10000, "The steps interval to save checkpoints.")
train_g.add_arg("validation_steps", int, 1000, "The steps interval to evaluate model performance.")
train_g.add_arg("use_recompute", bool, False, "Whether to use recompute optimizer for training.")
train_g.add_arg("use_mix_precision", bool, False, "Whether to use mix-precision optimizer for training.")
train_g.add_arg("use_cross_batch", bool, False, "Whether to use cross-batch for training.")
train_g.add_arg("use_lamb", bool, False, "Whether to use LambOptimizer for training.")
train_g.add_arg("use_dynamic_loss_scaling", bool, True, "Whether to use dynamic loss scaling.")
train_g.add_arg("test_save", str, "./checkpoints/test_result", "test_save")
train_g.add_arg("metric", str, "simple_accuracy", "metric")
train_g.add_arg("incr_every_n_steps", int, 100, "Increases loss scaling every n consecutive.")
train_g.add_arg("decr_every_n_nan_or_inf", int, 2, "Decreases loss scaling every n accumulated steps with nan or inf gradients.")
train_g.add_arg("incr_ratio", float, 2.0, "The multiplier to use when increasing the loss scaling.")
train_g.add_arg("decr_ratio", float, 0.8, "The less-than-one-multiplier to use when decreasing.")
log_g = ArgumentGroup(parser, "logging", "logging related.")
log_g.add_arg("skip_steps", int, 10, "The steps interval to print loss.")
log_g.add_arg("verbose", bool, False, "Whether to output verbose log.")
data_g = ArgumentGroup(parser, "data", "Data paths, vocab paths and data processing options")
data_g.add_arg("tokenizer", str, "FullTokenizer", "ATTENTION: the INPUT must be splited by Word with blank while using SentencepieceTokenizer or WordsegTokenizer")
data_g.add_arg("train_set", str, None, "Path to training data.")
data_g.add_arg("test_set", str, None, "Path to test data.")
data_g.add_arg("dev_set", str, None, "Path to validation data.")
data_g.add_arg("vocab_path", str, None, "Vocabulary path.")
data_g.add_arg("max_seq_len", int, 512, "Number of words of the longest seqence.")
data_g.add_arg("q_max_seq_len", int, 32, "Number of words of the longest seqence.")
data_g.add_arg("p_max_seq_len", int, 256, "Number of words of the longest seqence.")
data_g.add_arg("train_data_size", int, 0, "Number of training data's total examples. Set for distribute.")
data_g.add_arg("batch_size", int, 32, "Total examples' number in batch for training. see also --in_tokens.")
data_g.add_arg("predict_batch_size", int, None, "Total examples' number in batch for predict. see also --in_tokens.")
data_g.add_arg("in_tokens", bool, False, "If set, the batch size will be the maximum number of tokens in one batch. Otherwise, it will be the maximum number of examples in one batch.")
data_g.add_arg("do_lower_case", bool, True, "Whether to lower case the input text. Should be True for uncased models and False for cased models.")
data_g.add_arg("random_seed", int, None, "Random seed.")
data_g.add_arg("label_map_config", str, None, "label_map_path.")
data_g.add_arg("num_labels", int, 2, "label number")
data_g.add_arg("diagnostic", str, None, "GLUE Diagnostic Dataset")
data_g.add_arg("diagnostic_save", str, None, "GLUE Diagnostic save f")
data_g.add_arg("max_query_length", int, 64, "Max query length.")
data_g.add_arg("max_answer_length", int, 100, "Max answer length.")
data_g.add_arg("doc_stride", int, 128, "When splitting up a long document into chunks, how much stride to take between chunks.")
data_g.add_arg("n_best_size", int, 20, "The total number of n-best predictions to generate in the nbest_predictions.json output file.")
data_g.add_arg("chunk_scheme", type=str, default="IOB", choices=["IO", "IOB", "IOE", "IOBES"], help="chunk scheme")
run_type_g = ArgumentGroup(parser, "run_type", "running type options.")
run_type_g.add_arg("use_cuda", bool, True, "If set, use GPU for training.")
run_type_g.add_arg("is_distributed", bool, False, "If set, then start distributed training.")
run_type_g.add_arg("use_fast_executor", bool, False, "If set, use fast parallel executor (in experiment).")
run_type_g.add_arg("num_iteration_per_drop_scope", int, 10, "Iteration intervals to drop scope.")
run_type_g.add_arg("do_train", bool, True, "Whether to perform training.")
run_type_g.add_arg("do_val", bool, True, "Whether to perform evaluation on dev data set.")
run_type_g.add_arg("do_test", bool, True, "Whether to perform evaluation on test data set.")
run_type_g.add_arg("output_item", int, 3, "Test output format.")
run_type_g.add_arg("output_file_name", str, None, "Test output file name")
run_type_g.add_arg("test_data_cnt", int, 1110000 , "total cnt of testset")
run_type_g.add_arg("use_multi_gpu_test", bool, False, "Whether to perform evaluation using multiple gpu cards")
run_type_g.add_arg("metrics", bool, True, "Whether to perform evaluation on test data set.")
run_type_g.add_arg("shuffle", bool, True, "")
run_type_g.add_arg("for_cn", bool, False, "model train for cn or for other langs.")

View File

@@ -1,83 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import faiss
import numpy as np
def read_embed(file_name, dim=768, bs=3000):
if file_name.endswith("npy"):
i = 0
emb_np = np.load(file_name)
while i < len(emb_np):
vec_list = emb_np[i : i + bs]
i += bs
yield vec_list
else:
vec_list = []
with open(file_name) as inp:
for line in inp:
data = line.strip()
vector = [float(item) for item in data.split(" ")]
assert len(vector) == dim
vec_list.append(vector)
if len(vec_list) == bs:
yield vec_list
vec_list = []
if vec_list:
yield vec_list
def load_qid(file_name):
qid_list = []
with open(file_name) as inp:
for line in inp:
line = line.strip()
qid = line.split("\t")[0]
qid_list.append(qid)
return qid_list
def search(index, emb_file, qid_list, outfile, top_k):
q_idx = 0
with open(outfile, "w") as out:
for batch_vec in read_embed(emb_file):
q_emb_matrix = np.array(batch_vec)
res_dist, res_p_id = index.search(q_emb_matrix.astype("float32"), top_k)
for i in range(len(q_emb_matrix)):
qid = qid_list[q_idx]
for j in range(top_k):
pid = res_p_id[i][j]
score = res_dist[i][j]
out.write("%s\t%s\t%s\t%s\n" % (qid, pid, j + 1, score))
q_idx += 1
def main():
part = sys.argv[1]
topk = int(sys.argv[2])
q_text_file = sys.argv[3]
outfile = "output/res.top%s-part%s" % (topk, part)
qid_list = load_qid(q_text_file)
engine = faiss.read_index("output/para.index.part%s" % part)
emb_file = "output/query.emb.npy"
search(engine, emb_file, qid_list, outfile, topk)
if __name__ == "__main__":
main()

View File

@@ -1,61 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
shift = int(sys.argv[1])
top = int(sys.argv[2])
total_part = int(sys.argv[3])
f_list = []
for part in range(total_part):
f0 = open("output/res.top%s-part%s" % (top, part))
f_list.append(f0)
line_list = []
for part in range(total_part):
line = f_list[part].readline()
line_list.append(line)
out = open("output/dev.res.top%s" % top, "w")
last_q = ""
ans_list = {}
while line_list[-1]:
cur_list = []
for line in line_list:
sub = line.strip().split("\t")
cur_list.append(sub)
if last_q == "":
last_q = cur_list[0][0]
if cur_list[0][0] != last_q:
rank = sorted(ans_list.items(), key=lambda a: a[1], reverse=True)
for i in range(top):
out.write("%s\t%s\t%s\t%s\n" % (last_q, rank[i][0], i + 1, rank[i][1]))
ans_list = {}
for i, sub in enumerate(cur_list):
ans_list[int(sub[1]) + shift * i] = float(sub[-1])
last_q = cur_list[0][0]
line_list = []
for f0 in f_list:
line = f0.readline()
line_list.append(line)
rank = sorted(ans_list.items(), key=lambda a: a[1], reverse=True)
for i in range(top):
out.write("%s\t%s\t%s\t%s\n" % (last_q, rank[i][0], i + 1, rank[i][1]))
out.close()
print("output/dev.res.top%s" % top)

View File

@@ -1,259 +0,0 @@
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Ernie model."""
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import logging
from io import open
import paddle
import paddle.fluid as fluid
import six
from model.transformer_encoder import encoder, pre_process_layer
log = logging.getLogger(__name__)
class ErnieConfig(object):
def __init__(self, config_path):
self._config_dict = self._parse(config_path)
def _parse(self, config_path):
try:
with open(config_path, "r", encoding="utf8") as json_file:
config_dict = json.load(json_file)
except Exception:
raise IOError("Error in parsing Ernie model config file '%s'" % config_path)
else:
return config_dict
def __getitem__(self, key):
return self._config_dict.get(key, None)
def print_config(self):
for arg, value in sorted(six.iteritems(self._config_dict)):
log.info("%s: %s" % (arg, value))
log.info("------------------------------------------------")
class ErnieModel(object):
def __init__(
self,
src_ids,
position_ids,
sentence_ids,
task_ids,
input_mask,
config,
weight_sharing=True,
model_name="",
is_noise=False,
):
self._emb_size = config["hidden_size"]
self._n_layer = config["num_hidden_layers"]
self._n_head = config["num_attention_heads"]
self._voc_size = config["vocab_size"]
self._max_position_seq_len = config["max_position_embeddings"]
if config["sent_type_vocab_size"]:
self._sent_types = config["sent_type_vocab_size"]
else:
self._sent_types = config["type_vocab_size"]
self._use_task_id = config["use_task_id"]
if self._use_task_id:
self._task_types = config["task_type_vocab_size"]
self._hidden_act = config["hidden_act"]
self._prepostprocess_dropout = config["hidden_dropout_prob"]
self._attention_dropout = config["attention_probs_dropout_prob"]
if is_noise:
self._prepostprocess_dropout = 0
self._attention_dropout = 0
self._weight_sharing = weight_sharing
self.checkpoints = []
self._word_emb_name = "word_embedding"
self._pos_emb_name = "pos_embedding"
self._sent_emb_name = "sent_embedding"
self._task_emb_name = "task_embedding"
self._emb_dtype = "float32"
# Initialize all weights by truncated normal initializer, and all biases
# will be initialized by constant zero by default.
self._param_initializer = fluid.initializer.TruncatedNormal(scale=config["initializer_range"])
self._build_model(model_name, src_ids, position_ids, sentence_ids, task_ids, input_mask)
def _build_model(self, model_name, src_ids, position_ids, sentence_ids, task_ids, input_mask):
# padding id in vocabulary must be set to 0
emb_out = fluid.layers.embedding(
input=src_ids,
size=[self._voc_size, self._emb_size],
dtype=self._emb_dtype,
param_attr=fluid.ParamAttr(name=model_name + self._word_emb_name, initializer=self._param_initializer),
is_sparse=False,
)
position_emb_out = fluid.layers.embedding(
input=position_ids,
size=[self._max_position_seq_len, self._emb_size],
dtype=self._emb_dtype,
param_attr=fluid.ParamAttr(name=model_name + self._pos_emb_name, initializer=self._param_initializer),
)
sent_emb_out = fluid.layers.embedding(
sentence_ids,
size=[self._sent_types, self._emb_size],
dtype=self._emb_dtype,
param_attr=fluid.ParamAttr(name=model_name + self._sent_emb_name, initializer=self._param_initializer),
)
emb_out = emb_out + position_emb_out
emb_out = emb_out + sent_emb_out
if self._use_task_id:
task_emb_out = fluid.layers.embedding(
task_ids,
size=[self._task_types, self._emb_size],
dtype=self._emb_dtype,
param_attr=fluid.ParamAttr(name=model_name + self._task_emb_name, initializer=self._param_initializer),
)
emb_out = emb_out + task_emb_out
emb_out = pre_process_layer(emb_out, "nd", self._prepostprocess_dropout, name=model_name + "pre_encoder")
self_attn_mask = paddle.matmul(x=input_mask, y=input_mask, transpose_y=True)
self_attn_mask = fluid.layers.scale(x=self_attn_mask, scale=10000.0, bias=-1.0, bias_after_scale=False)
n_head_self_attn_mask = fluid.layers.stack(x=[self_attn_mask] * self._n_head, axis=1)
n_head_self_attn_mask.stop_gradient = True
self._enc_out, self.checkpoints = encoder(
enc_input=emb_out,
attn_bias=n_head_self_attn_mask,
n_layer=self._n_layer,
n_head=self._n_head,
d_key=self._emb_size // self._n_head,
d_value=self._emb_size // self._n_head,
d_model=self._emb_size,
d_inner_hid=self._emb_size * 4,
prepostprocess_dropout=self._prepostprocess_dropout,
attention_dropout=self._attention_dropout,
relu_dropout=0,
hidden_act=self._hidden_act,
preprocess_cmd="",
postprocess_cmd="dan",
param_initializer=self._param_initializer,
model_name=model_name,
name=model_name + "encoder",
)
def get_sequence_output(self):
return self._enc_out
def get_cls_output(self):
"""Get the first feature of each sequence for classification"""
cls_output = fluid.layers.slice(input=self._enc_out, axes=[1], starts=[0], ends=[1])
cls_output = fluid.layers.squeeze(cls_output, axes=[1])
return cls_output
def get_pooled_output(self):
"""Get the first feature of each sequence for classification"""
next_sent_feat = fluid.layers.slice(input=self._enc_out, axes=[1], starts=[0], ends=[1])
next_sent_feat = fluid.layers.fc(
input=next_sent_feat,
size=self._emb_size,
act="tanh",
param_attr=fluid.ParamAttr(name="pooled_fc.w_0", initializer=self._param_initializer),
bias_attr="pooled_fc.b_0",
)
return next_sent_feat
def get_lm_output(self, mask_label, mask_pos):
"""Get the loss & accuracy for pretraining"""
mask_pos = fluid.layers.cast(x=mask_pos, dtype="int32")
# extract the first token feature in each sentence
self.next_sent_feat = self.get_pooled_output()
reshaped_emb_out = fluid.layers.reshape(x=self._enc_out, shape=[-1, self._emb_size])
# extract masked tokens' feature
mask_feat = fluid.layers.gather(input=reshaped_emb_out, index=mask_pos)
# transform: fc
mask_trans_feat = fluid.layers.fc(
input=mask_feat,
size=self._emb_size,
act=self._hidden_act,
param_attr=fluid.ParamAttr(name="mask_lm_trans_fc.w_0", initializer=self._param_initializer),
bias_attr=fluid.ParamAttr(name="mask_lm_trans_fc.b_0"),
)
# transform: layer norm
mask_trans_feat = fluid.layers.layer_norm(
mask_trans_feat,
begin_norm_axis=len(mask_trans_feat.shape) - 1,
param_attr=fluid.ParamAttr(
name="mask_lm_trans_layer_norm_scale", initializer=fluid.initializer.Constant(1.0)
),
bias_attr=fluid.ParamAttr(
name="mask_lm_trans_layer_norm_bias", initializer=fluid.initializer.Constant(1.0)
),
)
# transform: layer norm
# mask_trans_feat = pre_process_layer(
# mask_trans_feat, 'n', name='mask_lm_trans')
mask_lm_out_bias_attr = fluid.ParamAttr(
name="mask_lm_out_fc.b_0", initializer=fluid.initializer.Constant(value=0.0)
)
if self._weight_sharing:
fc_out = paddle.matmul(
x=mask_trans_feat,
y=fluid.default_main_program().global_block().var(self._word_emb_name),
transpose_y=True,
)
fc_out += fluid.layers.create_parameter(
shape=[self._voc_size], dtype=self._emb_dtype, attr=mask_lm_out_bias_attr, is_bias=True
)
else:
fc_out = fluid.layers.fc(
input=mask_trans_feat,
size=self._voc_size,
param_attr=fluid.ParamAttr(name="mask_lm_out_fc.w_0", initializer=self._param_initializer),
bias_attr=mask_lm_out_bias_attr,
)
mask_lm_loss = fluid.layers.softmax_with_cross_entropy(logits=fc_out, label=mask_label)
mean_mask_lm_loss = fluid.layers.mean(mask_lm_loss)
return mean_mask_lm_loss
def get_task_output(self, task, task_labels):
task_fc_out = fluid.layers.fc(
input=self.next_sent_feat,
size=task["num_labels"],
param_attr=fluid.ParamAttr(name=task["task_name"] + "_fc.w_0", initializer=self._param_initializer),
bias_attr=task["task_name"] + "_fc.b_0",
)
task_loss, task_softmax = fluid.layers.softmax_with_cross_entropy(
logits=task_fc_out, label=task_labels, return_softmax=True
)
task_acc = fluid.layers.accuracy(input=task_softmax, label=task_labels)
mean_task_loss = fluid.layers.mean(task_loss)
return mean_task_loss, task_acc

View File

@@ -1,318 +0,0 @@
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Transformer encoder."""
from __future__ import absolute_import, division, print_function
from functools import partial
import paddle
import paddle.fluid as fluid
import paddle.fluid.layers as layers
def multi_head_attention(
queries,
keys,
values,
attn_bias,
d_key,
d_value,
d_model,
n_head=1,
dropout_rate=0.0,
cache=None,
param_initializer=None,
name="multi_head_att",
):
"""
Multi-Head Attention. Note that attn_bias is added to the logit before
computing softmax activation to mask certain selected positions so that
they will not considered in attention weights.
"""
keys = queries if keys is None else keys
values = keys if values is None else values
if not (len(queries.shape) == len(keys.shape) == len(values.shape) == 3):
raise ValueError("Inputs: queries, keys and values should all be 3-D tensors.")
def __compute_qkv(queries, keys, values, n_head, d_key, d_value):
"""
Add linear projection to queries, keys, and values.
"""
q = layers.fc(
input=queries,
size=d_key * n_head,
num_flatten_dims=2,
param_attr=fluid.ParamAttr(name=name + "_query_fc.w_0", initializer=param_initializer),
bias_attr=name + "_query_fc.b_0",
)
k = layers.fc(
input=keys,
size=d_key * n_head,
num_flatten_dims=2,
param_attr=fluid.ParamAttr(name=name + "_key_fc.w_0", initializer=param_initializer),
bias_attr=name + "_key_fc.b_0",
)
v = layers.fc(
input=values,
size=d_value * n_head,
num_flatten_dims=2,
param_attr=fluid.ParamAttr(name=name + "_value_fc.w_0", initializer=param_initializer),
bias_attr=name + "_value_fc.b_0",
)
return q, k, v
def __split_heads(x, n_head):
"""
Reshape the last dimension of input tensor x so that it becomes two
dimensions and then transpose. Specifically, input a tensor with shape
[bs, max_sequence_length, n_head * hidden_dim] then output a tensor
with shape [bs, n_head, max_sequence_length, hidden_dim].
"""
hidden_size = x.shape[-1]
# The value 0 in shape attr means copying the corresponding dimension
# size of the input as the output dimension size.
reshaped = layers.reshape(x=x, shape=[0, 0, n_head, hidden_size // n_head], inplace=True)
# permuate the dimensions into:
# [batch_size, n_head, max_sequence_len, hidden_size_per_head]
return layers.transpose(x=reshaped, perm=[0, 2, 1, 3])
def __combine_heads(x):
"""
Transpose and then reshape the last two dimensions of input tensor x
so that it becomes one dimension, which is reverse to __split_heads.
"""
if len(x.shape) == 3:
return x
if len(x.shape) != 4:
raise ValueError("Input(x) should be a 4-D Tensor.")
trans_x = layers.transpose(x, perm=[0, 2, 1, 3])
# The value 0 in shape attr means copying the corresponding dimension
# size of the input as the output dimension size.
return layers.reshape(x=trans_x, shape=[0, 0, trans_x.shape[2] * trans_x.shape[3]], inplace=True)
def scaled_dot_product_attention(q, k, v, attn_bias, d_key, dropout_rate):
"""
Scaled Dot-Product Attention
"""
scaled_q = layers.scale(x=q, scale=d_key**-0.5)
product = paddle.matmul(x=scaled_q, y=k, transpose_y=True)
if attn_bias:
product += attn_bias
weights = layers.softmax(product)
if dropout_rate:
weights = layers.dropout(
weights, dropout_prob=dropout_rate, dropout_implementation="upscale_in_train", is_test=False
)
out = paddle.matmul(weights, v)
return out
q, k, v = __compute_qkv(queries, keys, values, n_head, d_key, d_value)
if cache is not None: # use cache and concat time steps
# Since the inplace reshape in __split_heads changes the shape of k and
# v, which is the cache input for next time step, reshape the cache
# input from the previous time step first.
k = cache["k"] = layers.concat([layers.reshape(cache["k"], shape=[0, 0, d_model]), k], axis=1)
v = cache["v"] = layers.concat([layers.reshape(cache["v"], shape=[0, 0, d_model]), v], axis=1)
q = __split_heads(q, n_head)
k = __split_heads(k, n_head)
v = __split_heads(v, n_head)
ctx_multiheads = scaled_dot_product_attention(q, k, v, attn_bias, d_key, dropout_rate)
out = __combine_heads(ctx_multiheads)
# Project back to the model size.
proj_out = layers.fc(
input=out,
size=d_model,
num_flatten_dims=2,
param_attr=fluid.ParamAttr(name=name + "_output_fc.w_0", initializer=param_initializer),
bias_attr=name + "_output_fc.b_0",
)
return proj_out
def positionwise_feed_forward(x, d_inner_hid, d_hid, dropout_rate, hidden_act, param_initializer=None, name="ffn"):
"""
Position-wise Feed-Forward Networks.
This module consists of two linear transformations with a ReLU activation
in between, which is applied to each position separately and identically.
"""
hidden = layers.fc(
input=x,
size=d_inner_hid,
num_flatten_dims=2,
act=hidden_act,
param_attr=fluid.ParamAttr(name=name + "_fc_0.w_0", initializer=param_initializer),
bias_attr=name + "_fc_0.b_0",
)
if dropout_rate:
hidden = layers.dropout(
hidden, dropout_prob=dropout_rate, dropout_implementation="upscale_in_train", is_test=False
)
out = layers.fc(
input=hidden,
size=d_hid,
num_flatten_dims=2,
param_attr=fluid.ParamAttr(name=name + "_fc_1.w_0", initializer=param_initializer),
bias_attr=name + "_fc_1.b_0",
)
return out
def pre_post_process_layer(prev_out, out, process_cmd, dropout_rate=0.0, name=""):
"""
Add residual connection, layer normalization and dropout to the out tensor
optionally according to the value of process_cmd.
This will be used before or after multi-head attention and position-wise
feed-forward networks.
"""
for cmd in process_cmd:
if cmd == "a": # add residual connection
out = out + prev_out if prev_out else out
elif cmd == "n": # add layer normalization
out_dtype = out.dtype
if out_dtype == fluid.core.VarDesc.VarType.FP16:
out = layers.cast(x=out, dtype="float32")
out = layers.layer_norm(
out,
begin_norm_axis=len(out.shape) - 1,
param_attr=fluid.ParamAttr(
name=name + "_layer_norm_scale", initializer=fluid.initializer.Constant(1.0)
),
bias_attr=fluid.ParamAttr(name=name + "_layer_norm_bias", initializer=fluid.initializer.Constant(0.0)),
)
if out_dtype == fluid.core.VarDesc.VarType.FP16:
out = layers.cast(x=out, dtype="float16")
elif cmd == "d": # add dropout
if dropout_rate:
out = layers.dropout(
out, dropout_prob=dropout_rate, dropout_implementation="upscale_in_train", is_test=False
)
return out
pre_process_layer = partial(pre_post_process_layer, None)
post_process_layer = pre_post_process_layer
def encoder_layer(
enc_input,
attn_bias,
n_head,
d_key,
d_value,
d_model,
d_inner_hid,
prepostprocess_dropout,
attention_dropout,
relu_dropout,
hidden_act,
preprocess_cmd="n",
postprocess_cmd="da",
param_initializer=None,
name="",
):
"""The encoder layers that can be stacked to form a deep encoder.
This module consists of a multi-head (self) attention followed by
position-wise feed-forward networks and both the two components companied
with the post_process_layer to add residual connection, layer normalization
and dropout.
"""
attn_output = multi_head_attention(
pre_process_layer(enc_input, preprocess_cmd, prepostprocess_dropout, name=name + "_pre_att"),
None,
None,
attn_bias,
d_key,
d_value,
d_model,
n_head,
attention_dropout,
param_initializer=param_initializer,
name=name + "_multi_head_att",
)
attn_output = post_process_layer(
enc_input, attn_output, postprocess_cmd, prepostprocess_dropout, name=name + "_post_att"
)
ffd_output = positionwise_feed_forward(
pre_process_layer(attn_output, preprocess_cmd, prepostprocess_dropout, name=name + "_pre_ffn"),
d_inner_hid,
d_model,
relu_dropout,
hidden_act,
param_initializer=param_initializer,
name=name + "_ffn",
)
return (
post_process_layer(attn_output, ffd_output, postprocess_cmd, prepostprocess_dropout, name=name + "_post_ffn"),
ffd_output,
)
def encoder(
enc_input,
attn_bias,
n_layer,
n_head,
d_key,
d_value,
d_model,
d_inner_hid,
prepostprocess_dropout,
attention_dropout,
relu_dropout,
hidden_act,
preprocess_cmd="n",
postprocess_cmd="da",
param_initializer=None,
model_name="",
name="",
):
"""
The encoder is composed of a stack of identical layers returned by calling
encoder_layer.
"""
checkpoints = []
for i in range(n_layer):
enc_output, cp = encoder_layer(
enc_input,
attn_bias,
n_head,
d_key,
d_value,
d_model,
d_inner_hid,
prepostprocess_dropout,
attention_dropout,
relu_dropout,
hidden_act,
preprocess_cmd,
postprocess_cmd,
param_initializer=param_initializer,
name=name + "_layer_" + str(i),
)
checkpoints.append(cp)
enc_input = enc_output
enc_output = pre_process_layer(
enc_output, preprocess_cmd, prepostprocess_dropout, name=model_name + "post_encoder"
)
return enc_output, checkpoints

View File

@@ -1,121 +0,0 @@
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Optimization and learning rate scheduling."""
import paddle.fluid as fluid
from paddle.fluid.incubate.fleet.collective import fleet
def linear_warmup_decay(learning_rate, warmup_steps, num_train_steps):
"""Applies linear warmup of learning rate from 0 and decay to 0."""
with fluid.default_main_program()._lr_schedule_guard():
lr = fluid.layers.tensor.create_global_var(
shape=[1], value=0.0, dtype="float32", persistable=True, name="scheduled_learning_rate"
)
global_step = fluid.layers.learning_rate_scheduler._decay_step_counter()
with fluid.layers.control_flow.Switch() as switch:
with switch.case(global_step < warmup_steps):
warmup_lr = learning_rate * (global_step / warmup_steps)
fluid.layers.tensor.assign(warmup_lr, lr)
with switch.default():
decayed_lr = fluid.layers.learning_rate_scheduler.polynomial_decay(
learning_rate=learning_rate,
decay_steps=num_train_steps,
end_learning_rate=0.0,
power=1.0,
cycle=False,
)
fluid.layers.tensor.assign(decayed_lr, lr)
return lr
def optimization(
loss,
warmup_steps,
num_train_steps,
learning_rate,
train_program,
startup_prog,
weight_decay,
scheduler="linear_warmup_decay",
use_dynamic_loss_scaling=False,
incr_every_n_steps=1000,
decr_every_n_nan_or_inf=2,
incr_ratio=2.0,
decr_ratio=0.8,
dist_strategy=None,
use_lamb=False,
):
if warmup_steps > 0:
if scheduler == "noam_decay":
scheduled_lr = fluid.layers.learning_rate_scheduler.noam_decay(
1 / (warmup_steps * (learning_rate**2)), warmup_steps
)
elif scheduler == "linear_warmup_decay":
scheduled_lr = linear_warmup_decay(learning_rate, warmup_steps, num_train_steps)
else:
raise ValueError("Unknown learning rate scheduler, should be " "'noam_decay' or 'linear_warmup_decay'")
if use_lamb:
optimizer = fluid.optimizer.LambOptimizer(learning_rate=scheduled_lr)
else:
optimizer = fluid.optimizer.Adam(learning_rate=scheduled_lr)
else:
scheduled_lr = fluid.layers.create_global_var(
name=fluid.unique_name.generate("learning_rate"),
shape=[1],
value=learning_rate,
dtype="float32",
persistable=True,
)
if use_lamb:
optimizer = fluid.optimizer.LambOptimizer(learning_rate=scheduled_lr)
else:
optimizer = fluid.optimizer.Adam(learning_rate=scheduled_lr)
optimizer._learning_rate_map[fluid.default_main_program()] = scheduled_lr
fluid.clip.set_gradient_clip(clip=fluid.clip.GradientClipByGlobalNorm(clip_norm=1.0))
def exclude_from_weight_decay(name):
if name.find("layer_norm") > -1:
return True
bias_suffix = ["_bias", "_b", ".b_0"]
for suffix in bias_suffix:
if name.endswith(suffix):
return True
return False
param_list = dict()
for param in train_program.global_block().all_parameters():
param_list[param.name] = param * 1.0
param_list[param.name].stop_gradient = True
if dist_strategy is not None:
# use fleet api
optimizer = fleet.distributed_optimizer(optimizer, strategy=dist_strategy)
_, param_grads = optimizer.minimize(loss)
if weight_decay > 0:
for param, grad in param_grads:
if exclude_from_weight_decay(param.name):
continue
with param.block.program._optimized_guard([param, grad]), fluid.framework.name_scope("weight_decay"):
updated_param = param - param_list[param.name] * weight_decay * scheduled_lr
fluid.layers.assign(output=param, input=updated_param)
return scheduled_lr

View File

@@ -1,314 +0,0 @@
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import logging
import sys
from collections import namedtuple
from io import open
import numpy as np
import six
import tokenization
from batching import pad_batch_data
log = logging.getLogger(__name__)
if six.PY3:
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
def csv_reader(fd, delimiter="\t", trainer_id=0, trainer_num=1):
def gen():
for i, line in enumerate(fd):
if i % trainer_num == trainer_id:
slots = line.rstrip("\n").split(delimiter)
if len(slots) == 1:
yield slots,
else:
yield slots
return gen()
class BaseReader(object):
def __init__(
self,
vocab_path,
label_map_config=None,
max_seq_len=512,
total_num=0,
do_lower_case=True,
in_tokens=False,
is_inference=False,
random_seed=None,
tokenizer="FullTokenizer",
for_cn=True,
task_id=0,
):
self.max_seq_len = max_seq_len
self.tokenizer = tokenization.FullTokenizer(vocab_file=vocab_path, do_lower_case=do_lower_case)
self.vocab = self.tokenizer.vocab
self.pad_id = self.vocab["[PAD]"]
self.cls_id = self.vocab["[CLS]"]
self.sep_id = self.vocab["[SEP]"]
self.in_tokens = in_tokens
self.is_inference = is_inference
self.for_cn = for_cn
self.task_id = task_id
np.random.seed(random_seed)
self.current_example = 0
self.current_epoch = 0
self.num_examples = 0
self.total_num = total_num
if label_map_config:
with open(label_map_config, encoding="utf8") as f:
self.label_map = json.load(f)
else:
self.label_map = None
def get_train_progress(self):
"""Gets progress for training phase."""
return self.current_example, self.current_epoch
def _read_tsv(self, input_file, quotechar=None):
"""Reads a tab separated value file."""
with open(input_file, "r", encoding="utf8") as f:
reader = csv_reader(f)
headers = next(reader)
Example = namedtuple("Example", headers)
examples = []
for line in reader:
example = Example(*line)
examples.append(example)
return examples
def _truncate_seq_pair(self, tokens_a, tokens_b, max_length):
"""Truncates a sequence pair in place to the maximum length."""
# This is a simple heuristic which will always truncate the longer sequence
# one token at a time. This makes more sense than truncating an equal percent
# of tokens from each, since if one sequence is very short then each token
# that's truncated likely contains more information than a longer sequence.
while True:
total_length = len(tokens_a) + len(tokens_b)
if total_length <= max_length:
break
if len(tokens_a) > len(tokens_b):
tokens_a.pop()
else:
tokens_b.pop()
def _convert_example_to_record(self, example, max_seq_length, tokenizer):
"""Converts a single `Example` into a single `Record`."""
query = tokenization.convert_to_unicode(example.query)
tokens_a = tokenizer.tokenize(query)
tokens_b = None
title = tokenization.convert_to_unicode(example.title)
tokens_b = tokenizer.tokenize(title)
para = tokenization.convert_to_unicode(example.para)
tokens_para = tokenizer.tokenize(para)
tokens_b.extend(tokens_para)
self._truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)
# The convention in BERT/ERNIE is:
# (a) For sequence pairs:
# tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
# type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
# (b) For single sequences:
# tokens: [CLS] the dog is hairy . [SEP]
# type_ids: 0 0 0 0 0 0 0
#
# Where "type_ids" are used to indicate whether this is the first
# sequence or the second sequence. The embedding vectors for `type=0` and
# `type=1` were learned during pre-training and are added to the wordpiece
# embedding vector (and position vector). This is not *strictly* necessary
# since the [SEP] token unambiguously separates the sequences, but it makes
# it easier for the model to learn the concept of sequences.
#
# For classification tasks, the first vector (corresponding to [CLS]) is
# used as the "sentence vector". Note that this only makes sense because
# the entire model is fine-tuned.
tokens = []
text_type_ids = []
tokens.append("[CLS]")
text_type_ids.append(0)
for token in tokens_a:
tokens.append(token)
text_type_ids.append(0)
tokens.append("[SEP]")
text_type_ids.append(0)
if tokens_b:
for token in tokens_b:
tokens.append(token)
text_type_ids.append(1)
tokens.append("[SEP]")
text_type_ids.append(1)
token_ids = tokenizer.convert_tokens_to_ids(tokens)
position_ids = list(range(len(token_ids)))
if self.is_inference:
Record = namedtuple("Record", ["token_ids", "text_type_ids", "position_ids"])
record = Record(token_ids=token_ids, text_type_ids=text_type_ids, position_ids=position_ids)
else:
if self.label_map:
label_id = self.label_map[example.label]
else:
label_id = example.label
Record = namedtuple("Record", ["token_ids", "text_type_ids", "position_ids", "label_id", "qid"])
qid = None
if "qid" in example._fields:
qid = example.qid
record = Record(
token_ids=token_ids, text_type_ids=text_type_ids, position_ids=position_ids, label_id=label_id, qid=qid
)
return record
def _prepare_batch_data(self, examples, batch_size, phase=None):
"""generate batch records"""
batch_records, max_len = [], 0
for index, example in enumerate(examples):
if phase == "train":
self.current_example = index
record = self._convert_example_to_record(example, self.max_seq_len, self.tokenizer)
max_len = max(max_len, len(record.token_ids))
if self.in_tokens:
to_append = (len(batch_records) + 1) * max_len <= batch_size
else:
to_append = len(batch_records) < batch_size
if to_append:
batch_records.append(record)
else:
yield self._pad_batch_records(batch_records)
batch_records, max_len = [record], len(record.token_ids)
if batch_records:
yield self._pad_batch_records(batch_records)
def get_num_examples(self, input_file):
# examples = self._read_tsv(input_file)
# return len(examples)
return self.num_examples
def data_generator(
self, input_file, batch_size, epoch, dev_count=1, trainer_id=0, trainer_num=1, shuffle=True, phase=None
):
if phase == "train":
# examples = examples[trainer_id: (len(examples) //trainer_num) * trainer_num : trainer_num]
self.num_examples_per_node = self.total_num // trainer_num
self.num_examples = self.num_examples_per_node * trainer_num
examples = self._read_tsv(
input_file, trainer_id=trainer_id, trainer_num=trainer_num, num_examples=self.num_examples_per_node
)
log.info("apply sharding %d/%d" % (trainer_id, trainer_num))
else:
examples = self._read_tsv(input_file)
def wrapper():
all_dev_batches = []
for epoch_index in range(epoch):
if phase == "train":
self.current_example = 0
self.current_epoch = epoch_index
if shuffle:
np.random.shuffle(examples)
for batch_data in self._prepare_batch_data(examples, batch_size, phase=phase):
if len(all_dev_batches) < dev_count:
all_dev_batches.append(batch_data)
if len(all_dev_batches) == dev_count:
for batch in all_dev_batches:
yield batch
all_dev_batches = []
def f():
try:
for i in wrapper():
yield i
except Exception:
import traceback
traceback.print_exc()
return f
class ClassifyReader(BaseReader):
def _read_tsv(self, input_file, quotechar=None, trainer_id=0, trainer_num=1, num_examples=0):
"""Reads a tab separated value file."""
with open(input_file, "r", encoding="utf8") as f:
reader = csv_reader(f, trainer_id=trainer_id, trainer_num=trainer_num)
# headers = next(reader)
headers = "query\ttitle\tpara\tlabel".split("\t")
text_indices = [index for index, h in enumerate(headers) if h != "label"]
Example = namedtuple("Example", headers)
examples = []
for cnt, line in enumerate(reader):
if num_examples != 0 and cnt == num_examples:
break
for index, text in enumerate(line):
if index in text_indices:
if self.for_cn:
line[index] = text.replace(" ", "")
else:
line[index] = text
example = Example(*line)
examples.append(example)
return examples
def _pad_batch_records(self, batch_records):
batch_token_ids = [record.token_ids for record in batch_records]
batch_text_type_ids = [record.text_type_ids for record in batch_records]
batch_position_ids = [record.position_ids for record in batch_records]
if not self.is_inference:
batch_labels = [record.label_id for record in batch_records]
batch_labels = np.array(batch_labels).astype("int64").reshape([-1, 1])
if batch_records[0].qid:
batch_qids = [record.qid for record in batch_records]
batch_qids = np.array(batch_qids).astype("int64").reshape([-1, 1])
else:
batch_qids = np.array([]).astype("int64").reshape([-1, 1])
# padding
padded_token_ids, input_mask = pad_batch_data(batch_token_ids, pad_idx=self.pad_id, return_input_mask=True)
padded_text_type_ids = pad_batch_data(batch_text_type_ids, pad_idx=self.pad_id)
padded_position_ids = pad_batch_data(batch_position_ids, pad_idx=self.pad_id)
padded_task_ids = np.ones_like(padded_token_ids, dtype="int64") * self.task_id
return_list = [padded_token_ids, padded_text_type_ids, padded_position_ids, padded_task_ids, input_mask]
if not self.is_inference:
return_list += [batch_labels, batch_qids]
return return_list

View File

@@ -1,400 +0,0 @@
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tokenization classes."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import collections
import unicodedata
from io import open
def convert_to_unicode(text):
"""Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
def printable_text(text):
"""Returns text encoded in a way suitable for print or `tf.logging`."""
if isinstance(text, str):
return text
elif isinstance(text, bytes):
return text.decode("utf-8", "ignore")
else:
raise ValueError("Unsupported string type: %s" % (type(text)))
def load_vocab(vocab_file):
"""Loads a vocabulary file into a dictionary."""
vocab = collections.OrderedDict()
with open(vocab_file, encoding="utf8") as fin:
for num, line in enumerate(fin):
items = convert_to_unicode(line.strip()).split("\t")
if len(items) > 2:
break
token = items[0]
index = items[1] if len(items) == 2 else num
token = token.strip()
vocab[token] = int(index)
return vocab
def convert_by_vocab(vocab, items):
"""Converts a sequence of [tokens|ids] using the vocab."""
output = []
for item in items:
output.append(vocab[item])
return output
def convert_tokens_to_ids(vocab, tokens):
return convert_by_vocab(vocab, tokens)
def convert_ids_to_tokens(inv_vocab, ids):
return convert_by_vocab(inv_vocab, ids)
def whitespace_tokenize(text):
"""Runs basic whitespace cleaning and splitting on a piece of text."""
text = text.strip()
if not text:
return []
tokens = text.split()
return tokens
class FullTokenizer(object):
"""Runs end-to-end tokenization."""
def __init__(self, vocab_file, do_lower_case=True):
self.vocab = load_vocab(vocab_file)
self.inv_vocab = {v: k for k, v in self.vocab.items()}
self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case)
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
def tokenize(self, text):
split_tokens = []
for token in self.basic_tokenizer.tokenize(text):
for sub_token in self.wordpiece_tokenizer.tokenize(token):
split_tokens.append(sub_token)
return split_tokens
def convert_tokens_to_ids(self, tokens):
return convert_by_vocab(self.vocab, tokens)
def convert_ids_to_tokens(self, ids):
return convert_by_vocab(self.inv_vocab, ids)
class CharTokenizer(object):
"""Runs end-to-end tokenization."""
def __init__(self, vocab_file, do_lower_case=True):
self.vocab = load_vocab(vocab_file)
self.inv_vocab = {v: k for k, v in self.vocab.items()}
self.wordpiece_tokenizer = WordpieceTokenizer(vocab=self.vocab)
def tokenize(self, text):
split_tokens = []
for token in text.lower().split(" "):
for sub_token in self.wordpiece_tokenizer.tokenize(token):
split_tokens.append(sub_token)
return split_tokens
def convert_tokens_to_ids(self, tokens):
return convert_by_vocab(self.vocab, tokens)
def convert_ids_to_tokens(self, ids):
return convert_by_vocab(self.inv_vocab, ids)
class BasicTokenizer(object):
"""Runs basic tokenization (punctuation splitting, lower casing, etc.)."""
def __init__(self, do_lower_case=True):
"""Constructs a BasicTokenizer.
Args:
do_lower_case: Whether to lower case the input.
"""
self.do_lower_case = do_lower_case
def tokenize(self, text):
"""Tokenizes a piece of text."""
text = convert_to_unicode(text)
text = self._clean_text(text)
# This was added on November 1st, 2018 for the multilingual and Chinese
# models. This is also applied to the English models now, but it doesn't
# matter since the English models were not trained on any Chinese data
# and generally don't have any Chinese data in them (there are Chinese
# characters in the vocabulary because Wikipedia does have some Chinese
# words in the English Wikipedia.).
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for token in orig_tokens:
if self.do_lower_case:
token = token.lower()
token = self._run_strip_accents(token)
split_tokens.extend(self._run_split_on_punc(token))
output_tokens = whitespace_tokenize(" ".join(split_tokens))
return output_tokens
def _run_strip_accents(self, text):
"""Strips accents from a piece of text."""
text = unicodedata.normalize("NFD", text)
output = []
for char in text:
cat = unicodedata.category(char)
if cat == "Mn":
continue
output.append(char)
return "".join(output)
def _run_split_on_punc(self, text):
"""Splits punctuation on a piece of text."""
chars = list(text)
i = 0
start_new_word = True
output = []
while i < len(chars):
char = chars[i]
if _is_punctuation(char):
output.append([char])
start_new_word = True
else:
if start_new_word:
output.append([])
start_new_word = False
output[-1].append(char)
i += 1
return ["".join(x) for x in output]
def _tokenize_chinese_chars(self, text):
"""Adds whitespace around any CJK character."""
output = []
for char in text:
cp = ord(char)
if self._is_chinese_char(cp):
output.append(" ")
output.append(char)
output.append(" ")
else:
output.append(char)
return "".join(output)
def _is_chinese_char(self, cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
if (
(cp >= 0x4E00 and cp <= 0x9FFF)
or (cp >= 0x3400 and cp <= 0x4DBF) #
or (cp >= 0x20000 and cp <= 0x2A6DF) #
or (cp >= 0x2A700 and cp <= 0x2B73F) #
or (cp >= 0x2B740 and cp <= 0x2B81F) #
or (cp >= 0x2B820 and cp <= 0x2CEAF) #
or (cp >= 0xF900 and cp <= 0xFAFF)
or (cp >= 0x2F800 and cp <= 0x2FA1F) #
): #
return True
return False
def _clean_text(self, text):
"""Performs invalid character removal and whitespace cleanup on text."""
output = []
for char in text:
cp = ord(char)
if cp == 0 or cp == 0xFFFD or _is_control(char):
continue
if _is_whitespace(char):
output.append(" ")
else:
output.append(char)
return "".join(output)
class WordpieceTokenizer(object):
"""Runs WordPiece tokenization."""
def __init__(self, vocab, unk_token="[UNK]", max_input_chars_per_word=100):
self.vocab = vocab
self.unk_token = unk_token
self.max_input_chars_per_word = max_input_chars_per_word
def tokenize(self, text):
"""Tokenizes a piece of text into its word pieces.
This uses a greedy longest-match-first algorithm to perform tokenization
using the given vocabulary.
For example:
input = "unaffable"
output = ["un", "##aff", "##able"]
Args:
text: A single token or whitespace separated tokens. This should have
already been passed through `BasicTokenizer.
Returns:
A list of wordpiece tokens.
"""
text = convert_to_unicode(text)
output_tokens = []
for token in whitespace_tokenize(text):
chars = list(token)
if len(chars) > self.max_input_chars_per_word:
output_tokens.append(self.unk_token)
continue
is_bad = False
start = 0
sub_tokens = []
while start < len(chars):
end = len(chars)
cur_substr = None
while start < end:
substr = "".join(chars[start:end])
if start > 0:
substr = "##" + substr
if substr in self.vocab:
cur_substr = substr
break
end -= 1
if cur_substr is None:
is_bad = True
break
sub_tokens.append(cur_substr)
start = end
if is_bad:
output_tokens.append(self.unk_token)
else:
output_tokens.extend(sub_tokens)
return output_tokens
def _is_whitespace(char):
"""Checks whether `chars` is a whitespace character."""
# \t, \n, and \r are technically control characters but we treat them
# as whitespace since they are generally considered as such.
if char == " " or char == "\t" or char == "\n" or char == "\r":
return True
cat = unicodedata.category(char)
if cat == "Zs":
return True
return False
def _is_control(char):
"""Checks whether `chars` is a control character."""
# These are technically control characters but we count them as whitespace
# characters.
if char == "\t" or char == "\n" or char == "\r":
return False
cat = unicodedata.category(char)
if cat.startswith("C"):
return True
return False
def _is_punctuation(char):
"""Checks whether `chars` is a punctuation character."""
cp = ord(char)
# We treat all non-letter/number ASCII as punctuation.
# Characters such as "^", "$", and "`" are not in the Unicode
# Punctuation class but we treat them as punctuation anyways, for
# consistency.
if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
return True
cat = unicodedata.category(char)
if cat.startswith("P"):
return True
return False
def tokenize_chinese_chars(text):
"""Adds whitespace around any CJK character."""
def _is_chinese_char(cp):
"""Checks whether CP is the codepoint of a CJK character."""
# This defines a "chinese character" as anything in the CJK Unicode block:
# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)
#
# Note that the CJK Unicode block is NOT all Japanese and Korean characters,
# despite its name. The modern Korean Hangul alphabet is a different block,
# as is Japanese Hiragana and Katakana. Those alphabets are used to write
# space-separated words, so they are not treated specially and handled
# like the all of the other languages.
if (
(cp >= 0x4E00 and cp <= 0x9FFF)
or (cp >= 0x3400 and cp <= 0x4DBF) #
or (cp >= 0x20000 and cp <= 0x2A6DF) #
or (cp >= 0x2A700 and cp <= 0x2B73F) #
or (cp >= 0x2B740 and cp <= 0x2B81F) #
or (cp >= 0x2B820 and cp <= 0x2CEAF) #
or (cp >= 0xF900 and cp <= 0xFAFF)
or (cp >= 0x2F800 and cp <= 0x2FA1F) #
): #
return True
return False
def _is_whitespace(c):
if c == " " or c == "\t" or c == "\r" or c == "\n" or ord(c) == 0x202F:
return True
return False
output = []
buff = ""
for char in text:
cp = ord(char)
if _is_chinese_char(cp) or _is_whitespace(char):
if buff != "":
output.append(buff)
buff = ""
output.append(char)
else:
buff += char
if buff != "":
output.append(buff)
return output

View File

@@ -1,354 +0,0 @@
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Finetuning on classification tasks."""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import multiprocessing
import os
import time
import warnings
# NOTE(paddle-dev): All of these flags should be
# set before `import paddle`. Otherwise, it would
# not take any effect.
os.environ["FLAGS_eager_delete_tensor_gb"] = "0" # enable gc
import paddle # noqa: E402
import paddle.fluid as fluid # noqa: E402
if hasattr(paddle, "enable_static"):
paddle.enable_static()
import paddle.fluid.incubate.fleet.base.role_maker as role_maker # noqa: E402
import reader_ce as reader_ce # noqa: E402
from cross_encoder import create_model, evaluate, predict # noqa: E402
from finetune_args import parser # noqa: E402
from model.ernie import ErnieConfig # noqa: E402
from optimization import optimization # noqa: E402
from paddle.fluid.incubate.fleet.collective import ( # noqa: E402
DistributedStrategy,
fleet,
)
from src.utils.args import check_cuda, prepare_logger, print_arguments # noqa: E402
from src.utils.init import init_checkpoint, init_pretraining_params # noqa: E402
warnings.filterwarnings("ignore")
args = parser.parse_args()
log = logging.getLogger()
def main(args):
ernie_config = ErnieConfig(args.ernie_config_path)
ernie_config.print_config()
if args.use_cuda:
dev_list = fluid.cuda_places()
place = dev_list[0]
dev_count = len(dev_list)
else:
place = fluid.CPUPlace()
dev_count = int(os.environ.get("CPU_NUM", multiprocessing.cpu_count()))
exe = fluid.Executor(place)
reader = reader_ce.ClassifyReader(
vocab_path=args.vocab_path,
label_map_config=args.label_map_config,
max_seq_len=args.max_seq_len,
total_num=args.train_data_size,
do_lower_case=args.do_lower_case,
in_tokens=args.in_tokens,
random_seed=args.random_seed,
tokenizer=args.tokenizer,
for_cn=args.for_cn,
task_id=args.task_id,
)
if not (args.do_train or args.do_val or args.do_test):
raise ValueError("For args `do_train`, `do_val` and `do_test`, at " "least one of them must be True.")
if args.do_test:
assert args.test_save is not None
startup_prog = fluid.Program()
if args.random_seed is not None:
startup_prog.random_seed = args.random_seed
if args.predict_batch_size is None:
args.predict_batch_size = args.batch_size
if args.do_train:
role = role_maker.PaddleCloudRoleMaker(is_collective=True)
fleet.init(role)
dev_count = fleet.worker_num()
train_data_generator = reader.data_generator(
input_file=args.train_set,
batch_size=args.batch_size,
epoch=args.epoch,
dev_count=1,
trainer_id=fleet.worker_index(),
trainer_num=fleet.worker_num(),
shuffle=True,
phase="train",
)
num_train_examples = reader.get_num_examples(args.train_set)
if args.in_tokens:
max_train_steps = args.epoch * num_train_examples // (args.batch_size // args.max_seq_len) // dev_count
else:
max_train_steps = args.epoch * num_train_examples // args.batch_size // dev_count
warmup_steps = int(max_train_steps * args.warmup_proportion)
log.info("Device count: %d" % dev_count)
log.info("Num train examples: %d" % num_train_examples)
log.info("Max train steps: %d" % max_train_steps)
log.info("Num warmup steps: %d" % warmup_steps)
train_program = fluid.Program()
# use fleet api
exec_strategy = fluid.ExecutionStrategy()
if args.use_fast_executor:
exec_strategy.use_experimental_executor = True
exec_strategy.num_threads = dev_count
if args.is_distributed:
exec_strategy.num_threads = 3
exec_strategy.num_iteration_per_drop_scope = args.num_iteration_per_drop_scope
dist_strategy = DistributedStrategy()
dist_strategy.exec_strategy = exec_strategy
dist_strategy.nccl_comm_num = 1
if args.is_distributed:
dist_strategy.nccl_comm_num = 2
dist_strategy.use_hierarchical_allreduce = True
if args.use_mix_precision:
dist_strategy.use_amp = True
with fluid.program_guard(train_program, startup_prog):
with fluid.unique_name.guard():
train_pyreader, graph_vars = create_model(
args, pyreader_name="train_reader", ernie_config=ernie_config
)
scheduled_lr = optimization(
loss=graph_vars["loss"],
warmup_steps=warmup_steps,
num_train_steps=max_train_steps,
learning_rate=args.learning_rate,
train_program=train_program,
startup_prog=startup_prog,
weight_decay=args.weight_decay,
scheduler=args.lr_scheduler,
use_dynamic_loss_scaling=args.use_dynamic_loss_scaling,
incr_every_n_steps=args.incr_every_n_steps,
decr_every_n_nan_or_inf=args.decr_every_n_nan_or_inf,
incr_ratio=args.incr_ratio,
decr_ratio=args.decr_ratio,
dist_strategy=dist_strategy,
)
if args.verbose:
if args.in_tokens:
lower_mem, upper_mem, unit = fluid.contrib.memory_usage(
program=train_program, batch_size=args.batch_size // args.max_seq_len
)
else:
lower_mem, upper_mem, unit = fluid.contrib.memory_usage(
program=train_program, batch_size=args.batch_size
)
log.info("Theoretical memory usage in training: %.3f - %.3f %s" % (lower_mem, upper_mem, unit))
if args.do_val or args.do_test:
test_prog = fluid.Program()
with fluid.program_guard(test_prog, startup_prog):
with fluid.unique_name.guard():
test_pyreader, graph_vars = create_model(
args, pyreader_name="test_reader", ernie_config=ernie_config, is_prediction=True
)
test_prog = test_prog.clone(for_test=True)
train_program = fleet.main_program
exe = fluid.Executor(place)
exe.run(startup_prog)
if args.do_train:
if args.init_checkpoint and args.init_pretraining_params:
log.warning(
"WARNING: args 'init_checkpoint' and 'init_pretraining_params' "
"both are set! Only arg 'init_checkpoint' is made valid."
)
if args.init_checkpoint:
init_checkpoint(exe, args.init_checkpoint, main_program=startup_prog)
elif args.init_pretraining_params:
init_pretraining_params(exe, args.init_pretraining_params, main_program=startup_prog)
elif args.do_val or args.do_test:
if not args.init_checkpoint:
raise ValueError("args 'init_checkpoint' should be set if" "only doing validation or testing!")
init_checkpoint(exe, args.init_checkpoint, main_program=startup_prog)
if args.do_train:
train_exe = exe
train_pyreader.decorate_tensor_provider(train_data_generator)
else:
train_exe = None
test_exe = exe
current_epoch = 0
steps = 0
if args.do_train:
train_pyreader.start()
if warmup_steps > 0:
graph_vars["learning_rate"] = scheduled_lr
ce_info = []
time_begin = time.time()
last_epoch = 0
while True:
try:
steps += 1
if fleet.worker_index() != 0:
train_exe.run(fetch_list=[], program=train_program)
continue
if steps % args.skip_steps != 0:
train_exe.run(fetch_list=[], program=train_program)
else:
outputs = evaluate(
train_exe, train_program, train_pyreader, graph_vars, "train", metric=args.metric
)
if args.verbose:
verbose = "train pyreader queue size: %d, " % train_pyreader.queue.size()
verbose += "learning rate: %f" % (
outputs["learning_rate"] if warmup_steps > 0 else args.learning_rate
)
log.info(verbose)
current_example, current_epoch = reader.get_train_progress()
time_end = time.time()
used_time = time_end - time_begin
log.info(
"epoch: %d, progress: %d/%d, step: %d, ave loss: %f, "
"ave acc: %f, speed: %f steps/s"
% (
current_epoch,
current_example * dev_count,
num_train_examples,
steps,
outputs["loss"],
outputs["accuracy"],
args.skip_steps / used_time,
)
)
ce_info.append([outputs["loss"], outputs["accuracy"], used_time])
time_begin = time.time()
if steps % args.save_steps == 0:
save_path = os.path.join(args.checkpoints, "step_" + str(steps))
fluid.io.save_persistables(exe, save_path, fleet._origin_program)
if steps % args.validation_steps == 0:
# evaluate dev set
if args.do_val:
evaluate_wrapper(args, reader, exe, test_prog, test_pyreader, graph_vars, current_epoch, steps)
if args.do_test:
predict_wrapper(args, reader, exe, test_prog, test_pyreader, graph_vars, current_epoch, steps)
if last_epoch != current_epoch:
last_epoch = current_epoch
except fluid.core.EOFException:
save_path = os.path.join(args.checkpoints, "step_" + str(steps))
fluid.io.save_persistables(exe, save_path, fleet._origin_program)
train_pyreader.reset()
break
# final eval on dev set
if args.do_val:
evaluate_wrapper(args, reader, exe, test_prog, test_pyreader, graph_vars, current_epoch, steps)
# final eval on test set
if args.do_test:
predict_wrapper(args, reader, exe, test_prog, test_pyreader, graph_vars)
# final eval on diagnostic, hack for glue-ax
if args.diagnostic:
test_pyreader.decorate_tensor_provider(
reader.data_generator(args.diagnostic, batch_size=args.batch_size, epoch=1, dev_count=1, shuffle=False)
)
log.info("Final diagnostic")
qids, preds, probs = predict(test_exe, test_prog, test_pyreader, graph_vars)
assert len(qids) == len(preds), "{} v.s. {}".format(len(qids), len(preds))
with open(args.diagnostic_save, "w") as f:
for id, s, p in zip(qids, preds, probs):
f.write("{}\t{}\t{}\n".format(id, s, p))
log.info("Done final diagnostic, saving to {}".format(args.diagnostic_save))
def evaluate_wrapper(args, reader, exe, test_prog, test_pyreader, graph_vars, epoch, steps):
# evaluate dev set
for ds in args.dev_set.split(","):
test_pyreader.decorate_tensor_provider(
reader.data_generator(ds, batch_size=args.predict_batch_size, epoch=1, dev_count=1, shuffle=False)
)
log.info("validation result of dataset {}:".format(ds))
evaluate_info = evaluate(exe, test_prog, test_pyreader, graph_vars, "dev", metric=args.metric)
log.info(evaluate_info + ", file: {}, epoch: {}, steps: {}".format(ds, epoch, steps))
def predict_wrapper(args, reader, exe, test_prog, test_pyreader, graph_vars, epoch=None, steps=None):
test_sets = args.test_set.split(",")
save_dirs = args.test_save.split(",")
assert len(test_sets) == len(save_dirs)
for test_f, save_f in zip(test_sets, save_dirs):
test_pyreader.decorate_tensor_provider(
reader.data_generator(test_f, batch_size=args.predict_batch_size, epoch=1, dev_count=1, shuffle=False)
)
if epoch is not None or steps is not None:
save_path = save_f + "." + str(epoch) + "." + str(steps)
else:
save_path = save_f
log.info("testing {}, save to {}".format(test_f, save_path))
qids, preds, probs = predict(exe, test_prog, test_pyreader, graph_vars)
save_dir = os.path.dirname(save_path)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
else:
log.warning("save dir exists: %s, will skip saving" % save_dir)
with open(save_path, "w") as f:
for p in probs:
f.write("{}\n".format(p[1]))
if __name__ == "__main__":
prepare_logger(log)
print_arguments(args)
check_cuda(args.use_cuda)
main(args)

View File

@@ -1,71 +0,0 @@
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Arguments for configuration."""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
import sys
import paddle.fluid as fluid
import six
from paddlenlp.trainer.argparser import strtobool
log = logging.getLogger(__name__)
def prepare_logger(logger, debug=False, save_to_file=None):
formatter = logging.Formatter(fmt="[%(levelname)s] %(asctime)s [%(filename)12s:%(lineno)5d]:\t%(message)s")
console_hdl = logging.StreamHandler()
console_hdl.setFormatter(formatter)
logger.addHandler(console_hdl)
if save_to_file is not None and not os.path.exists(save_to_file):
file_hdl = logging.FileHandler(save_to_file)
file_hdl.setFormatter(formatter)
logger.addHandler(file_hdl)
logger.setLevel(logging.DEBUG)
logger.propagate = False
class ArgumentGroup(object):
def __init__(self, parser, title, des):
self._group = parser.add_argument_group(title=title, description=des)
def add_arg(self, name, type, default, help, positional_arg=False, **kwargs):
prefix = "" if positional_arg else "--"
type = strtobool if type == bool else type
self._group.add_argument(
prefix + name, default=default, type=type, help=help + " Default: %(default)s.", **kwargs
)
def print_arguments(args):
log.info("----------- Configuration Arguments -----------")
for arg, value in sorted(six.iteritems(vars(args))):
log.info("%s: %s" % (arg, value))
log.info("------------------------------------------------")
def check_cuda(
use_cuda,
err="\nYou can not set use_cuda = True in the model because you are using paddlepaddle-cpu.\n \
Please: 1. Install paddlepaddle-gpu to run your models on GPU or 2. Set use_cuda = False to run models on CPU.\n",
):
try:
if use_cuda is True and fluid.is_compiled_with_cuda() is False:
log.error(err)
sys.exit(1)
except Exception:
pass

View File

@@ -1,52 +0,0 @@
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import os
import paddle.fluid as fluid
log = logging.getLogger(__name__)
def init_checkpoint(exe, init_checkpoint_path, main_program):
assert os.path.exists(init_checkpoint_path), "[%s] cann't be found." % init_checkpoint_path
def existed_persitables(var):
if not fluid.io.is_persistable(var):
return False
if not os.path.exists(os.path.join(init_checkpoint_path, var.name)):
print("Var not exists: [%s]\t%s" % (var.name, os.path.join(init_checkpoint_path, var.name)))
# else:
# print ("Var exists: [%s]" % (var.name))
return os.path.exists(os.path.join(init_checkpoint_path, var.name))
fluid.io.load_vars(exe, init_checkpoint_path, main_program=main_program, predicate=existed_persitables)
log.info("Load model from {}".format(init_checkpoint_path))
def init_pretraining_params(exe, pretraining_params_path, main_program):
assert os.path.exists(pretraining_params_path), "[%s] cann't be found." % pretraining_params_path
def existed_params(var):
if not isinstance(var, fluid.framework.Parameter):
return False
if not os.path.exists(os.path.join(pretraining_params_path, var.name)):
print("Var not exists: [%s]\t%s" % (var.name, os.path.join(pretraining_params_path, var.name)))
# else:
# print ("Var exists: [%s]" % (var.name))
return os.path.exists(os.path.join(pretraining_params_path, var.name))
fluid.io.load_vars(exe, pretraining_params_path, main_program=main_program, predicate=existed_params)
log.info("Load pretraining parameters from {}.".format(pretraining_params_path))

View File

@@ -1,34 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
export CUDA_VISIBLE_DEVICES=0
QUESTION=$1
# Question: NFC咋开门
if [ $# != 1 ];then
echo "USAGE: sh script/run_cross_encoder_test.sh \$QUESTION"
exit 1
fi
# compute scores for QUESTION and OCR parsing results with Rerank module
cd Rerank
bash run_test.sh ${QUESTION}
cd ..
# extraction answer for QUESTION from the top1 of rank
cd Extraction
bash run_test.sh ${QUESTION}
cd ..

View File

@@ -1 +0,0 @@
[ERNIE-Layout](../../../model_zoo/ernie-layout)

View File

@@ -1,171 +0,0 @@
简体中文 | [English](README_en.md)
# 信息抽取应用
**目录**
- [1. 信息抽取应用简介](#1)
- [2. 技术特色](#2)
- [2.1 信息抽取方案全覆盖](#21)
- [2.2 强大的训练基座](#22)
- [2.3 产业级全流程方案](#23)
- [2.4 效果展示](#24)
- [3. 快速开始](#快速开始)
- [3.1 Taskflow开箱即用](#31)
- [3.2 文本信息抽取](#32)
- [3.3 文档信息抽取](#33)
<a name="1"></a>
## 1. 信息抽取应用简介
信息抽取应用针对信息抽取一系列高频场景开源了产业级解决方案,**具备多领域、多任务、跨模态的能力**,打通**数据标注-模型训练-模型调优-预测部署全流程**,可快速实现信息抽取产品落地。
信息抽取通俗地说就是从给定的文本/图片等输入数据中抽取出结构化信息的过程。在信息抽取的落地过程中通常面临领域多变、任务多样、数据稀缺等许多挑战。针对信息抽取领域的难点和痛点,PaddleNLP信息抽取应用**基于UIE统一建模的思想**,提供了信息抽取产业级应用方案,**除支持纯文本场景实体、关系、事件、观点等不同任务抽取外,还支持文档/图片/表格的端到端信息抽取**。该应用**不限定行业领域和抽取目标**,可实现从产品原型研发、业务POC阶段到业务落地、迭代阶段的无缝衔接,助力开发者实现特定领域抽取场景的快速适配与落地。
**信息抽取应用亮点:**
- **覆盖场景全面🎓:** 覆盖信息抽取各类主流任务,面向纯文本和文档场景,支持多语言,满足开发者多样信息抽取落地需求。
- **效果领先🏃:** 以在纯文本、多模态上均有突出效果的UIE系列模型作为训练基座,提供多种尺寸的预训练模型满足不同需求,具有广泛成熟的实践应用性。
- **简单易用⚡:** 通过Taskflow实现三行代码可实现无标注数据的情况下进行快速调用,一行命令即可开启信息抽取训练,轻松完成部署上线,降低信息抽取技术落地门槛。
- **高效调优✊:** 开发者无需机器学习背景知识,即可轻松上手数据标注及模型训练流程。
<a name="2"></a>
## 2. 技术特色
<a name="21"></a>
### 2.1 信息抽取方案全覆盖
多模型选择,满足精度、速度,适配不同信息抽取使用场景。
| 模型名称 | 使用场景 | 支持任务 |
| :----------------------------------------------------------: | :--------------------------------------------------------- | :--------------------------------------------------- |
| `uie-base`<br />`uie-medium`<br />`uie-mini`<br />`uie-micro`<br />`uie-nano` | 面向**纯文本**场景的**抽取式**模型,支持**中文** | 具备实体、关系、事件、评论观点等通用信息抽取能力 |
| `uie-base-en` | 面向**纯文本**场景的**抽取式**模型,支持**英文** | 具备实体、关系、事件、评论观点等通用信息抽取能力 |
| `uie-m-base`<br />`uie-m-large` | 面向**纯文本**场景的**抽取式**模型,支持**中英** | 具备实体、关系、事件、评论观点等通用信息抽取能力 |
| <b>`uie-x-base`</b> | 面向**纯文本**和**文档**场景的**抽取式**模型,支持**中英** | 支持纯文本场景的全部功能,还支持文档/图片/表格的端到端信息抽取 |
<a name="22"></a>
### 2.2 强大的训练基座
信息抽取应用使用ERNIE 3.0轻量级模型作为预训练模型,同时在大量信息抽取数据上进行了二次预训练,从而让模型适配固定prompt。
- 中文文本数据集实验效果
我们在互联网、医疗、金融三大垂类文本自建测试集上进行了实验:
<table>
<tr><th row_span='2'><th colspan='2'>金融<th colspan='2'>医疗<th colspan='2'>互联网
<tr><td><th>0-shot<th>5-shot<th>0-shot<th>5-shot<th>0-shot<th>5-shot
<tr><td>uie-base (12L768H)<td>46.43<td>70.92<td><b>71.83</b><td>85.72<td>78.33<td>81.86
<tr><td>uie-medium (6L768H)<td>41.11<td>64.53<td>65.40<td>75.72<td>78.32<td>79.68
<tr><td>uie-mini (6L384H)<td>37.04<td>64.65<td>60.50<td>78.36<td>72.09<td>76.38
<tr><td>uie-micro (4L384H)<td>37.53<td>62.11<td>57.04<td>75.92<td>66.00<td>70.22
<tr><td>uie-nano (4L312H)<td>38.94<td>66.83<td>48.29<td>76.74<td>62.86<td>72.35
<tr><td>uie-m-large (24L1024H)<td><b>49.35</b><td><b>74.55</b><td>70.50<td><b>92.66</b><td>78.49<td><b>83.02</b>
<tr><td>uie-m-base (12L768H)<td>38.46<td>74.31<td>63.37<td>87.32<td>76.27<td>80.13
<tr><td>🧾 🎓<b>uie-x-base (12L768H)</b><td>48.84<td>73.87<td>65.60<td>88.81<td><b>79.36</b><td>81.65
</table>
0-shot表示无训练数据直接通过```paddlenlp.Taskflow```进行预测,5-shot表示每个类别包含5条标注数据进行模型微调。**实验表明UIE在垂类场景可以通过少量数据(few-shot)进一步提升效果**。
- 多模态数据集实验效果
我们在通用、金融、医疗三大场景自建多模态测试集上对UIE-X的零样本效果进行了实验:
<table>
<tr><th ><th>通用<th>金融<th colspan='2'>医疗
<tr><td>🧾 🎓<b>uie-x-base (12L768H)</b><td>65.03<td>73.51<td>84.24
</table>
通用测试集包含了不同领域的复杂样本,抽取难度最大。
<a name="23"></a>
### 2.3 产业级全流程方案
**调研阶段**
- 该阶段目标需求开放且缺少数据积累。我们提供Taskflow三行代码极简调用的方式,无需标注数据即可在业务场景上快速验证效果。
- [文本抽取 Taskflow使用指南](./taskflow_text.md)
- [文档抽取 Taskflow使用指南](./taskflow_doc.md)
**数据准备阶段**
- 我们推荐在实际的业务场景中定制自己的信息抽取模型。我们提供了不同抽取场景的Label Studio标注解决方案,可基于该方案实现从数据标注到训练数据构造的无缝衔接,大大降低了数据标注、模型定制的时间成本。
- [文本抽取标注指南](./label_studio_text.md)
- [文档抽取标注指南](./label_studio_doc.md)。
**模型微调及封闭域蒸馏**
- 基于UIE优秀的小样本微调能力,实现低成本模型定制适配。同时提供封闭域蒸馏的加速方案,解决抽取速度慢的问题。
- [文本信息抽取全流程示例](./text/README.md)
- [文档信息抽取全流程示例](./document/README.md)
**模型部署**
- 提供HTTP部署方案,快速实现定制模型的部署上线。
- [文本抽取HTTP部署指南](./text/deploy/simple_serving/README.md)
- [文档抽取HTTP部署指南](./document/deploy/simple_serving/README.md)
<a name="24"></a>
### 2.4 效果展示
- 🧾 通过[Huggingface网页](https://huggingface.co/spaces/PaddlePaddle/UIE-X)体验UIE-X功能:
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/207856955-a01cd5dd-fd5c-48ae-b8fd-c69512a88845.png height=500 width=900 hspace='10'/>
</div>
- UIE-X端到端文档抽取产业应用示例
- 报关单
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/205879840-239ada90-1692-40e4-a17f-c5e963fdd204.png height=800 width=500 />
</div>
- Delivery Note(需微调)
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/205922422-f2615050-83cb-4bf5-8887-461f5633e85c.png height=250 width=700 />
</div>
- 增值税发票(需微调)
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/206084942-44ba477c-9244-4ce2-bbb5-ba430c9b926e.png height=550 width=700 />
</div>
- 表单(需微调)
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/207856330-7aa0d158-47e0-477f-a88f-e23a040504a3.png height=400 width=700 />
</div>
<a name="3"></a>
## 3. 快速开始
<a name="31"></a>
### 3.1 Taskflow开箱即用
- 通过Taskflow实现开箱即用
👉 [文本抽取 Taskflow使用指南](./taskflow_text.md)
👉 [文档抽取 Taskflow使用指南](./taskflow_doc.md)
<a name="32"></a>
### 3.2 文本信息抽取
- 快速开启文本信息抽取 👉 [文本信息抽取指南](./text/README.md)
<a name="33"></a>
### 3.3 文档信息抽取
- 快速开启文档信息抽取 👉 [文档信息抽取指南](./document/README.md)

View File

@@ -1,301 +0,0 @@
简体中文 | [English](README_en.md)
# 文档信息抽取
**目录**
- [1. 文档信息抽取应用](#1)
- [2. 快速开始](#2)
- [2.1 代码结构](#代码结构)
- [2.2 数据标注](#数据标注)
- [2.3 模型微调](#模型微调)
- [2.4 模型评估](#模型评估)
- [2.5 定制模型一键预测](#定制模型一键预测)
- [2.6 实验指标](#实验指标)
<a name="1"></a>
## 1. 文档信息抽取应用
本项目提供基于UIE微调的文档抽取端到端应用方案,打通**数据标注-模型训练-模型调优-预测部署全流程**,可快速实现文档信息抽取产品落地。
信息抽取通俗地说就是从给定的文本/图片等输入数据中抽取出结构化信息的过程。在信息抽取的落地过程中通常面临领域多变、任务多样、数据稀缺等许多挑战。针对信息抽取领域的难点和痛点,PaddleNLP信息抽取应用UIE统一建模的思想,提供了文档信息抽取产业级应用方案,支持**文档/图片/表格和纯文本场景下实体、关系、事件、观点等不同任务信息抽取**。该应用**不限定行业领域和抽取目标**,可实现从产品原型研发、业务POC阶段到业务落地、迭代阶段的无缝衔接,助力开发者实现特定领域抽取场景的快速适配与落地。
**文档信息抽取应用亮点:**
- **覆盖场景全面🎓:** 覆盖文档信息抽取各类主流任务,支持多语言,满足开发者多样信息抽取落地需求。
- **效果领先🏃:** 以在多模态信息抽取上有突出效果的模型UIE-X作为训练基座,具有广泛成熟的实践应用性。
- **简单易用⚡:** 通过Taskflow实现三行代码可实现无标注数据的情况下进行快速调用,一行命令即可开启信息抽取训练,轻松完成部署上线,降低信息抽取技术落地门槛。
- **高效调优✊:** 开发者无需机器学习背景知识,即可轻松上手数据标注及模型训练流程。
<a name="2"></a>
## 2. 快速开始
对于简单的抽取目标可以直接使用```paddlenlp.Taskflow```实现零样本(zero-shot)抽取,对于细分场景我们推荐使用定制功能(标注少量数据进行模型微调)以进一步提升效果。
<a name="代码结构"></a>
### 2.1 代码结构
```shell
.
├── deploy # 部署目录
│ └── simple_serving # 基于PaddleNLP SimpleServing 服务化部署
├── utils.py # 数据处理工具
├── finetune.py # 模型微调、压缩脚本
├── evaluate.py # 模型评估脚本
└── README.md
```
<a name="数据标注"></a>
### 2.2 数据标注
我们推荐使用 [Label Studio](https://labelstud.io/) 进行文档信息抽取数据标注,本项目打通了从数据标注到训练的通道,也即Label Studio导出数据可以通过 [label_studio.py](../label_studio.py) 脚本轻松将数据转换为输入模型时需要的形式,实现无缝衔接。标注方法的详细介绍请参考 [Label Studio数据标注指南](../label_studio_doc.md)。
这里我们提供预先标注好的`增值税发票数据集`的文件,可以运行下面的命令行下载数据集,我们将展示如何使用数据转化脚本生成训练/验证/测试集文件,并使用UIE-X模型进行微调。
下载增值税发票数据集:
```shell
wget https://paddlenlp.bj.bcebos.com/datasets/tax.tar.gz
tar -zxvf tax.tar.gz
mv tax data
rm tax.tar.gz
```
生成训练/验证集文件:
```shell
python ../label_studio.py \
--label_studio_file ./data/label_studio.json \
--save_dir ./data \
--splits 0.8 0.2 0 \
--task_type ext
```
生成训练/验证集文件,可以使用PP-Structure的布局分析优化OCR结果的排序:
```shell
python ../label_studio.py \
--label_studio_file ./data/label_studio.json \
--save_dir ./data \
--splits 0.8 0.2 0\
--task_type ext \
--layout_analysis True
```
更多不同类型任务(含实体抽取、关系抽取、文档分类等)的标注规则及参数说明,请参考[Label Studio数据标注指南](../label_studio_doc.md)。
<a name="模型微调"></a>
### 2.3 模型微调
推荐使用 [Trainer API ](https://github.com/PaddlePaddle/PaddleNLP/blob/develop/docs/trainer.md) 对模型进行微调。只需输入模型、数据集等就可以使用 Trainer API 高效快速地进行预训练、微调和模型压缩等任务,可以一键启动多卡训练、混合精度训练、梯度累积、断点重启、日志显示等功能,Trainer API 还针对训练过程的通用训练配置做了封装,比如:优化器、学习率调度等。
使用下面的命令,使用 `uie-x-base` 作为预训练模型进行模型微调,将微调后的模型保存至`./checkpoint/model_best`:
单卡启动:
```shell
python finetune.py \
--device gpu \
--logging_steps 5 \
--save_steps 25 \
--eval_steps 25 \
--seed 42 \
--model_name_or_path uie-x-base \
--output_dir ./checkpoint/model_best \
--train_path data/train.txt \
--dev_path data/dev.txt \
--max_seq_len 512 \
--per_device_train_batch_size 8 \
--per_device_eval_batch_size 8 \
--num_train_epochs 10 \
--learning_rate 1e-5 \
--do_train \
--do_eval \
--do_export \
--export_model_dir ./checkpoint/model_best \
--overwrite_output_dir \
--disable_tqdm True \
--metric_for_best_model eval_f1 \
--load_best_model_at_end True \
--save_total_limit 1
```
如果在GPU环境中使用,可以指定gpus参数进行多卡训练:
```shell
python -u -m paddle.distributed.launch --gpus "0" finetune.py \
--device gpu \
--logging_steps 5 \
--save_steps 25 \
--eval_steps 25 \
--seed 42 \
--model_name_or_path uie-x-base \
--output_dir ./checkpoint/model_best \
--train_path data/train.txt \
--dev_path data/dev.txt \
--max_seq_len 512 \
--per_device_train_batch_size 8 \
--per_device_eval_batch_size 8 \
--num_train_epochs 10 \
--learning_rate 1e-5 \
--do_train \
--do_eval \
--do_export \
--export_model_dir ./checkpoint/model_best \
--overwrite_output_dir \
--disable_tqdm True \
--metric_for_best_model eval_f1 \
--load_best_model_at_end True \
--save_total_limit 1
```
该示例代码中由于设置了参数 `--do_eval`,因此在训练完会自动进行评估。
可配置参数说明:
* `device`: 训练设备,可选择 'cpu'、'gpu'、'npu' 其中的一种;默认为 GPU 训练。
* `logging_steps`: 训练过程中日志打印的间隔 steps 数,默认10。
* `save_steps`: 训练过程中保存模型 checkpoint 的间隔 steps 数,默认100。
* `eval_steps`: 训练过程中保存模型 checkpoint 的间隔 steps 数,默认100。
* `seed`:全局随机种子,默认为 42。
* `model_name_or_path`:进行 few shot 训练使用的预训练模型。默认为 "uie-x-base"。
* `output_dir`:必须,模型训练或压缩后保存的模型目录;默认为 `None` 。
* `train_path`:训练集路径;默认为 `None` 。
* `dev_path`:开发集路径;默认为 `None` 。
* `max_seq_len`:文本最大切分长度,输入超过最大长度时会对输入文本进行自动切分,默认为512。
* `per_device_train_batch_size`:用于训练的每个 GPU 核心/NPU 核心/CPU 的batch大小,默认为8。
* `per_device_eval_batch_size`:用于评估的每个 GPU 核心/NPU 核心/CPU 的batch大小,默认为8。
* `num_train_epochs`: 训练轮次,使用早停法时可以选择 100;默认为10。
* `learning_rate`:训练最大学习率,UIE-X 推荐设置为 1e-5;默认值为3e-5。
* `label_names`:训练数据标签label的名称,UIE-X 设置为'start_positions' 'end_positions';默认值为None。
* `do_train`:是否进行微调训练,设置该参数表示进行微调训练,默认不设置。
* `do_eval`:是否进行评估,设置该参数表示进行评估,默认不设置。
* `do_export`:是否进行导出,设置该参数表示进行静态图导出,默认不设置。
* `export_model_dir`:静态图导出地址,默认为None。
* `overwrite_output_dir`: 如果 `True`,覆盖输出目录的内容。如果 `output_dir` 指向检查点目录,则使用它继续训练。
* `disable_tqdm`: 是否使用tqdm进度条。
* `metric_for_best_model`:最优模型指标,UIE-X 推荐设置为 `eval_f1`,默认为None。
* `load_best_model_at_end`:训练结束后是否加载最优模型,通常与`metric_for_best_model`配合使用,默认为False。
* `save_total_limit`:如果设置次参数,将限制checkpoint的总数。删除旧的checkpoints `输出目录`,默认为None。
<a name="模型评估"></a>
### 2.4 模型评估
```shell
python evaluate.py \
--device "gpu" \
--model_path ./checkpoint/model_best \
--test_path ./data/dev.txt \
--output_dir ./checkpoint/model_best \
--label_names 'start_positions' 'end_positions'\
--max_seq_len 512 \
--per_device_eval_batch_size 16
```
评估方式说明:采用单阶段评价的方式,即关系抽取、事件抽取等需要分阶段预测的任务对每一阶段的预测结果进行分别评价。验证/测试集默认会利用同一层级的所有标签来构造出全部负例。
可开启`debug`模式对每个正例类别分别进行评估,该模式仅用于模型调试:
```shell
python evaluate.py \
--device "gpu" \
--model_path ./checkpoint/model_best \
--test_path ./data/dev.txt \
--output_dir ./checkpoint/model_best \
--label_names 'start_positions' 'end_positions'\
--max_seq_len 512 \
--per_device_eval_batch_size 16 \
--debug True
```
输出结果:
```text
[2022-11-14 09:41:18,424] [ INFO] - ***** Running Evaluation *****
[2022-11-14 09:41:18,424] [ INFO] - Num examples = 160
[2022-11-14 09:41:18,424] [ INFO] - Pre device batch size = 4
[2022-11-14 09:41:18,424] [ INFO] - Total Batch size = 4
[2022-11-14 09:41:18,424] [ INFO] - Total prediction steps = 40
[2022-11-14 09:41:26,451] [ INFO] - -----Evaluate model-------
[2022-11-14 09:41:26,451] [ INFO] - Class Name: ALL CLASSES
[2022-11-14 09:41:26,451] [ INFO] - Evaluation Precision: 0.94521 | Recall: 0.88462 | F1: 0.91391
[2022-11-14 09:41:26,451] [ INFO] - -----------------------------
[2022-11-14 09:41:26,452] [ INFO] - ***** Running Evaluation *****
[2022-11-14 09:41:26,452] [ INFO] - Num examples = 8
[2022-11-14 09:41:26,452] [ INFO] - Pre device batch size = 4
[2022-11-14 09:41:26,452] [ INFO] - Total Batch size = 4
[2022-11-14 09:41:26,452] [ INFO] - Total prediction steps = 2
[2022-11-14 09:41:26,692] [ INFO] - Class Name: 开票日期
[2022-11-14 09:41:26,692] [ INFO] - Evaluation Precision: 1.00000 | Recall: 1.00000 | F1: 1.00000
[2022-11-14 09:41:26,692] [ INFO] - -----------------------------
[2022-11-14 09:41:26,693] [ INFO] - ***** Running Evaluation *****
[2022-11-14 09:41:26,693] [ INFO] - Num examples = 8
[2022-11-14 09:41:26,693] [ INFO] - Pre device batch size = 4
[2022-11-14 09:41:26,693] [ INFO] - Total Batch size = 4
[2022-11-14 09:41:26,693] [ INFO] - Total prediction steps = 2
[2022-11-14 09:41:26,952] [ INFO] - Class Name: 名称
[2022-11-14 09:41:26,952] [ INFO] - Evaluation Precision: 0.87500 | Recall: 0.87500 | F1: 0.87500
[2022-11-14 09:41:26,952] [ INFO] - -----------------------------
...
```
可配置参数:
* `device`: 评估设备,可选择 'cpu'、'gpu'、'npu' 其中的一种;默认为 GPU 评估。
* `model_path`: 进行评估的模型文件夹路径,路径下需包含模型权重文件`model_state.pdparams`及配置文件`model_config.json`。
* `test_path`: 进行评估的测试集文件。
* `label_names`:训练数据标签label的名称,UIE-X 设置为'start_positions' 'end_positions';默认值为None。
* `batch_size`: 批处理大小,请结合机器情况进行调整,默认为16。
* `max_seq_len`: 文本最大切分长度,输入超过最大长度时会对输入文本进行自动切分,默认为512。
* `per_device_eval_batch_size`:用于评估的每个 GPU 核心/NPU 核心/CPU 的batch大小,默认为8。
* `debug`: 是否开启debug模式对每个正例类别分别进行评估,该模式仅用于模型调试,默认关闭。
* `schema_lang`: 选择schema的语言,可选有`ch`和`en`。默认为`ch`,英文数据集请选择`en`。
<a name="定制模型一键预测"></a>
### 2.5 定制模型一键预测
`paddlenlp.Taskflow`装载定制模型,通过`task_path`指定模型权重文件的路径,路径下需要包含训练好的模型权重文件`model_state.pdparams`。
```python
from pprint import pprint
from paddlenlp import Taskflow
from paddlenlp.utils.doc_parser import DocParser
schema = ['开票日期', '名称', '纳税人识别号', '开户行及账号', '金额', '价税合计', 'No', '税率', '地址、电话', '税额']
my_ie = Taskflow("information_extraction", model="uie-x-base", schema=schema, task_path='./checkpoint/model_best', precision='fp16')
```
我们可以根据设置的`schema`,对指定的`doc_path`文档进行信息抽取并进行可视化:
```python
doc_path = "./data/images/b199.jpg"
results = my_ie({"doc": doc_path})
pprint(results)
# 结果可视化
DocParser.write_image_with_results(
doc_path,
result=results[0],
save_path="./image_show.png")
```
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/206084942-44ba477c-9244-4ce2-bbb5-ba430c9b926e.png height=550 width=700 />
</div>
<a name="实验指标"></a>
### 2.6 实验指标
我们在自标注的增值税数据集上进行实验:
| | Precision | Recall | F1 Score |
| :---: | :--------: | :--------: | :--------: |
| 0-shot| 0.44898 | 0.56410 | 0.50000 |
| 5-shot| 0.9000 | 0.9231 | 0.9114 |
| 10-shot| 0.9125 | 0.93590 | 0.9241 |
| 20-shot| 0.9737 | 0.9487 | 0.9610 |
| 30-shot| 0.9744 | 0.9744 | 0.9744 |
| 30-shot+PP-Structure| 1.0 | 0.9625 | 0.9809 |
n-shot表示训练集包含n张标注图片数据进行模型微调,实验表明UIE-X可以通过少量数据(few-shot)和PP-Structure的布局分析进一步提升结果。

View File

@@ -1,57 +0,0 @@
# 基于PaddleNLP SimpleServing 的服务化部署
## 目录
- [环境准备](#环境准备)
- [Server服务启动](#Server服务启动)
- [Client请求启动](#Client请求启动)
- [服务化自定义参数](#服务化自定义参数)
## 环境准备
使用有SimpleServing功能的PaddleNLP版本(或者最新的develop版本)
```shell
pip install paddlenlp >= 2.4.4
```
## Server服务启动
```bash
paddlenlp server server:app --workers 1 --host 0.0.0.0 --port 8189
```
## Client请求启动
```bash
python client.py
```
## 服务化自定义参数
### Server 自定义参数
#### schema替换
```python
# Default schema
schema = ['开票日期', '名称', '纳税人识别号', '开户行及账号', '金额', '价税合计', 'No', '税率', '地址、电话', '税额']
```
#### 设置模型路径
```
# Default task_path
uie = Taskflow('information_extraction', task_path='../../checkpoint/model_best/', schema=schema)
```
#### 多卡服务化预测
PaddleNLP SimpleServing 支持多卡负载均衡预测,主要在服务化注册的时候,注册两个Taskflow的task即可,下面是示例代码
```
uie1 = Taskflow('information_extraction', task_path='../../checkpoint/model_best/', schema=schema, device_id=0)
uie2 = Taskflow('information_extraction', task_path='../../checkpoint/model_best/', schema=schema, device_id=1)
service.register_taskflow('uie', [uie1, uie2])
```
### Client 自定义参数
```python
# Changed to image paths you wanted
image_paths = ['../../data/images/b1.jpg']
```

View File

@@ -1,287 +0,0 @@
# 文本抽取任务Label Studio使用指南
**目录**
- [1. 安装](#1)
- [2. 文本抽取任务标注](#2)
- [2.1 项目创建](#21)
- [2.2 数据上传](#22)
- [2.3 标签构建](#23)
- [2.4 任务标注](#24)
- [2.5 数据导出](#25)
- [2.6 数据转换](#26)
- [2.7 更多配置](#27)
<a name="1"></a>
## 1. 安装
**以下标注示例用到的环境配置:**
- Python 3.8+
- label-studio == 1.6.0
- paddleocr >= 2.6.0.1
在终端(terminal)使用pip安装label-studio:
```shell
pip install label-studio==1.6.0
```
安装完成后,运行以下命令行:
```shell
label-studio start
```
在浏览器打开[http://localhost:8080/](http://127.0.0.1:8080/),输入用户名和密码登录,开始使用label-studio进行标注。
<a name="2"></a>
## 2. 文本抽取任务标注
<a name="21"></a>
#### 2.1 项目创建
点击创建(Create)开始创建一个新的项目,填写项目名称、描述,然后选择``Object Detection with Bounding Boxes``。
- 填写项目名称、描述
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199661377-d9664165-61aa-4462-927d-225118b8535b.png height=230 width=1200 />
</div>
- **命名实体识别、关系抽取、事件抽取、实体/评价维度分类**任务选择``Relation Extraction`。
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199661638-48a870eb-a1df-4db5-82b9-bc8e985f5190.png height=350 width=1200 />
</div>
- **文本分类、句子级情感倾向分类**任务选择``Text Classification``。
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/212617773-34534e68-4544-4b24-8f39-ae7f9573d397.png height=420 width=1200 />
</div>
- 添加标签(也可跳过后续在Setting/Labeling Interface中配置)
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199662737-ed996a2c-7a24-4077-8a36-239c4bfb0a16.png height=380 width=1200 />
</div>
图中展示了实体类型标签的构建,其他类型标签的构建可参考[2.3标签构建](#23)
<a name="22"></a>
#### 2.2 数据上传
先从本地上传txt格式文件,选择``List of tasks``,然后选择导入本项目。
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199667670-1b8f6755-b41f-41c4-8afc-06bb051690b6.png height=210 width=1200 />
</div>
<a name="23"></a>
#### 2.3 标签构建
- Span类型标签
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199667941-04e300c5-3cd7-4b8e-aaf5-561415414891.png height=480 width=1200 />
</div>
- Relation类型标签
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199725229-f5e998bf-367c-4449-b83a-c799f1e3de00.png height=620 width=1200 />
</div>
Relation XML模板:
```xml
<Relations>
<Relation value="歌手"/>
<Relation value="发行时间"/>
<Relation value="所属专辑"/>
</Relations>
```
- 分类类别标签
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199724082-ee82dceb-dab0-496d-a930-a8ecb284d8b2.png height=370 width=1200 />
</div>
<a name="24"></a>
#### 2.4 任务标注
- 实体抽取
标注示例:
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199879957-aeec9d17-d342-4ea0-a840-457b49f6066e.png height=140 width=1000 />
</div>
该标注示例对应的schema为:
```text
schema = [
'时间',
'选手',
'赛事名称',
'得分'
]
```
- 关系抽取
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199879866-03c1ecac-1828-4f35-af70-9ae61701c303.png height=230 width=1200 />
</div>
对于关系抽取,其P的类型设置十分重要,需要遵循以下原则
“{S}的{P}为{O}”需要能够构成语义合理的短语。比如对于三元组(S, 父子, O),关系类别为父子是没有问题的。但按照UIE当前关系类型prompt的构造方式,“S的父子为O”这个表达不是很通顺,因此P改成孩子更好,即“S的孩子为O”。**合理的P类型设置,将显著提升零样本效果**。
该标注示例对应的schema为:
```text
schema = {
'作品名': [
'歌手',
'发行时间',
'所属专辑'
]
}
```
- 事件抽取
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199879776-75abbade-9bea-44dc-ac36-322fecdc03e0.png height=220 width=1200 />
</div>
该标注示例对应的schema为:
```text
schema = {
'地震触发词': [
'时间',
'震级'
]
}
```
- 句子级分类
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199879672-c3f286fe-a217-4888-950f-d4ee45b19f5a.png height=210 width=1000 />
</div>
该标注示例对应的schema为:
```text
schema = '情感倾向[正向,负向]'
```
- 实体/评价维度分类
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199879586-8c6e4826-a3b0-49e0-9920-98ca062dccff.png height=240 width=1200 />
</div>
该标注示例对应的schema为:
```text
schema = {
'评价维度': [
'观点词',
'情感倾向[正向,负向]'
]
}
```
<a name="25"></a>
#### 2.5 数据导出
勾选已标注文本ID,选择导出的文件类型为``JSON``,导出数据:
<div align="center">
<img src=https://user-images.githubusercontent.com/40840292/199891344-023736e2-6f9d-454b-b72a-dec6689f8436.png height=180 width=1200 />
</div>
<a name="26"></a>
#### 2.6 数据转换
将导出的文件重命名为``label_studio.json``后,放入``./data``目录下。通过[label_studio.py](./label_studio.py)脚本可转为UIE的数据格式。
- 抽取式任务
```shell
python label_studio.py \
--label_studio_file ./data/label_studio.json \
--save_dir ./data \
--splits 0.8 0.1 0.1 \
--task_type ext
```
- 句子级分类任务
在数据转换阶段,我们会自动构造用于模型训练的prompt信息。例如句子级情感分类中,prompt为``情感倾向[正向,负向]``,可以通过`prompt_prefix`和`options`参数进行配置。
```shell
python label_studio.py \
--label_studio_file ./data/label_studio.json \
--task_type cls \
--save_dir ./data \
--splits 0.8 0.1 0.1 \
--prompt_prefix "情感倾向" \
--options "正向" "负向"
```
- 实体/评价维度分类任务
在数据转换阶段,我们会自动构造用于模型训练的prompt信息。例如评价维度情感分类中,prompt为``XXX的情感倾向[正向,负向]``,可以通过`prompt_prefix`和`options`参数进行声明。
```shell
python label_studio.py \
--label_studio_file ./data/label_studio.json \
--task_type ext \
--save_dir ./data \
--splits 0.8 0.1 0.1 \
--prompt_prefix "情感倾向" \
--options "正向" "负向" \
--separator "##"
```
<a name="27"></a>
#### 2.7 更多配置
- ``label_studio_file``: 从label studio导出的数据标注文件。
- ``save_dir``: 训练数据的保存目录,默认存储在``data``目录下。
- ``negative_ratio``: 最大负例比例,该参数只对抽取类型任务有效,适当构造负例可提升模型效果。负例数量和实际的标签数量有关,最大负例数量 = negative_ratio * 正例数量。该参数只对训练集有效,默认为5。为了保证评估指标的准确性,验证集和测试集默认构造全负例。
- ``splits``: 划分数据集时训练集、验证集所占的比例。默认为[0.8, 0.1, 0.1]表示按照``8:1:1``的比例将数据划分为训练集、验证集和测试集。
- ``task_type``: 选择任务类型,可选有抽取和分类两种类型的任务。
- ``options``: 指定分类任务的类别标签,该参数只对分类类型任务有效。默认为["正向", "负向"]。
- ``prompt_prefix``: 声明分类任务的prompt前缀信息,该参数只对分类类型任务有效。默认为"情感倾向"。
- ``is_shuffle``: 是否对数据集进行随机打散,默认为True。
- ``seed``: 随机种子,默认为1000.
- ``schema_lang``:选择schema的语言,将会应该训练数据prompt的构造方式,可选有`ch`和`en`。默认为`ch`。
- ``separator``: 实体类别/评价维度与分类标签的分隔符,该参数只对实体/评价维度分类任务有效。默认为"##"。
备注:
- 默认情况下 [label_studio.py](./label_studio.py) 脚本会按照比例将数据划分为 train/dev/test 数据集
- 每次执行 [label_studio.py](./label_studio.py) 脚本,将会覆盖已有的同名数据文件
- 在模型训练阶段我们推荐构造一些负例以提升模型效果,在数据转换阶段我们内置了这一功能。可通过`negative_ratio`控制自动构造的负样本比例;负样本数量 = negative_ratio * 正样本数量。
- 对于从label_studio导出的文件,默认文件中的每条数据都是经过人工正确标注的。
## References
- **[Label Studio](https://labelstud.io/)**

View File

@@ -1,289 +0,0 @@
简体中文 | [English](README_en.md)
# 文本信息抽取
**目录**
- [1. 文本信息抽取应用](#1)
- [2. 快速开始](#2)
- [2.1 代码结构](#代码结构)
- [2.2 数据标注](#数据标注)
- [2.3 模型微调](#模型微调)
- [2.4 模型评估](#模型评估)
- [2.5 定制模型一键预测](#定制模型一键预测)
- [2.6 实验指标](#实验指标)
- [2.7 封闭域蒸馏](#封闭域蒸馏)
<a name="1"></a>
## 1. 文本信息抽取应用
本项目提供基于UIE微调的纯文本抽取端到端应用方案,打通**数据标注-模型训练-模型调优-预测部署全流程**,可快速实现文档信息抽取产品落地。
信息抽取通俗地说就是从给定的文本/图片等输入数据中抽取出结构化信息的过程。在信息抽取的落地过程中通常面临领域多变、任务多样、数据稀缺等许多挑战。针对信息抽取领域的难点和痛点,PaddleNLP信息抽取应用UIE统一建模的思想,提供了文档信息抽取产业级应用方案,支持**文档/图片/表格和纯文本场景下实体、关系、事件、观点等不同任务信息抽取**。该应用**不限定行业领域和抽取目标**,可实现从产品原型研发、业务POC阶段到业务落地、迭代阶段的无缝衔接,助力开发者实现特定领域抽取场景的快速适配与落地。
**文本信息抽取应用亮点:**
- **覆盖场景全面🎓:** 覆盖文本信息抽取各类主流任务,支持多语言,满足开发者多样信息抽取落地需求。
- **效果领先🏃:** 以在纯文本具有突出效果的UIE系列模型作为训练基座,提供多种尺寸的预训练模型满足不同需求,具有广泛成熟的实践应用性。
- **简单易用⚡:** 通过Taskflow实现三行代码可实现无标注数据的情况下进行快速调用,一行命令即可开启信息抽取训练,轻松完成部署上线,降低信息抽取技术落地门槛。
- **高效调优✊:** 开发者无需机器学习背景知识,即可轻松上手数据标注及模型训练流程。
<a name="2"></a>
## 2. 快速开始
对于简单的抽取目标可以直接使用```paddlenlp.Taskflow```实现零样本(zero-shot)抽取,对于细分场景我们推荐使用定制功能(标注少量数据进行模型微调)以进一步提升效果。
<a name="代码结构"></a>
### 2.1 代码结构
```shell
.
├── utils.py # 数据处理工具
├── finetune.py # 模型微调、压缩脚本
├── evaluate.py # 模型评估脚本
└── README.md
```
<a name="数据标注"></a>
### 2.2 数据标注
我们推荐使用 [Label Studio](https://labelstud.io/) 进行文本信息抽取数据标注,本项目打通了从数据标注到训练的通道,也即Label Studio导出数据可以通过 [label_studio.py](../label_studio.py) 脚本轻松将数据转换为输入模型时需要的形式,实现无缝衔接。标注方法的详细介绍请参考 [Label Studio数据标注指南](../label_studio_text.md)。
这里我们提供预先标注好的`军事关系抽取数据集`的文件,可以运行下面的命令行下载数据集,我们将展示如何使用数据转化脚本生成训练/验证/测试集文件,并使用UIE模型进行微调。
下载军事关系抽取数据集:
```shell
wget https://bj.bcebos.com/paddlenlp/datasets/military.tar.gz
tar -xvf military.tar.gz
mv military data
rm military.tar.gz
```
生成训练/验证集文件:
```shell
python ../label_studio.py \
--label_studio_file ./data/label_studio.json \
--save_dir ./data \
--splits 0.76 0.24 0 \
--negative_ratio 3 \
--task_type ext
```
更多不同类型任务(含实体抽取、关系抽取、文档分类等)的标注规则及参数说明,请参考[Label Studio数据标注指南](../label_studio_text.md)。
<a name="模型微调"></a>
### 2.3 模型微调
推荐使用 [Trainer API ](https://github.com/PaddlePaddle/PaddleNLP/blob/develop/docs/trainer.md) 对模型进行微调。只需输入模型、数据集等就可以使用 Trainer API 高效快速地进行预训练、微调和模型压缩等任务,可以一键启动多卡训练、混合精度训练、梯度累积、断点重启、日志显示等功能,Trainer API 还针对训练过程的通用训练配置做了封装,比如:优化器、学习率调度等。
使用下面的命令,使用 `uie-base` 作为预训练模型进行模型微调,将微调后的模型保存至`$finetuned_model`:
单卡启动:
```shell
python finetune.py \
--device gpu \
--logging_steps 10 \
--save_steps 100 \
--eval_steps 100 \
--seed 1000 \
--model_name_or_path uie-base \
--output_dir ./checkpoint/model_best \
--train_path data/train.txt \
--dev_path data/dev.txt \
--max_seq_len 512 \
--per_device_train_batch_size 16 \
--per_device_eval_batch_size 16 \
--num_train_epochs 20 \
--learning_rate 1e-5 \
--do_train \
--do_eval \
--do_export \
--export_model_dir ./checkpoint/model_best \
--overwrite_output_dir \
--disable_tqdm True \
--metric_for_best_model eval_f1 \
--load_best_model_at_end True \
--save_total_limit 1
```
如果在GPU环境中使用,可以指定gpus参数进行多卡训练:
```shell
python -u -m paddle.distributed.launch --gpus "0,1" finetune.py \
--device gpu \
--logging_steps 10 \
--save_steps 100 \
--eval_steps 100 \
--seed 1000 \
--model_name_or_path uie-base \
--output_dir ./checkpoint/model_best \
--train_path data/train.txt \
--dev_path data/dev.txt \
--max_seq_len 512 \
--per_device_train_batch_size 8 \
--per_device_eval_batch_size 8 \
--num_train_epochs 20 \
--learning_rate 1e-5 \
--do_train \
--do_eval \
--do_export \
--export_model_dir ./checkpoint/model_best \
--overwrite_output_dir \
--disable_tqdm True \
--metric_for_best_model eval_f1 \
--load_best_model_at_end True \
--save_total_limit 1
```
该示例代码中由于设置了参数 `--do_eval`,因此在训练完会自动进行评估。
可配置参数说明:
* `device`: 训练设备,可选择 'cpu'、'gpu'、'npu' 其中的一种;默认为 GPU 训练。
* `logging_steps`: 训练过程中日志打印的间隔 steps 数,默认10。
* `save_steps`: 训练过程中保存模型 checkpoint 的间隔 steps 数,默认100。
* `eval_steps`: 训练过程中保存模型 checkpoint 的间隔 steps 数,默认100。
* `seed`:全局随机种子,默认为 42。
* `model_name_or_path`:进行 few shot 训练使用的预训练模型。默认为 "uie-x-base"。
* `output_dir`:必须,模型训练或压缩后保存的模型目录;默认为 `None` 。
* `train_path`:训练集路径;默认为 `None` 。
* `dev_path`:开发集路径;默认为 `None` 。
* `max_seq_len`:文本最大切分长度,输入超过最大长度时会对输入文本进行自动切分,默认为512。
* `per_device_train_batch_size`:用于训练的每个 GPU 核心/CPU 的batch大小,默认为8。
* `per_device_eval_batch_size`:用于评估的每个 GPU 核心/CPU 的batch大小,默认为8。
* `num_train_epochs`: 训练轮次,使用早停法时可以选择 100;默认为10。
* `learning_rate`:训练最大学习率,UIE-X 推荐设置为 1e-5;默认值为3e-5。
* `label_names`:训练数据标签label的名称,UIE-X 设置为'start_positions' 'end_positions';默认值为None。
* `do_train`:是否进行微调训练,设置该参数表示进行微调训练,默认不设置。
* `do_eval`:是否进行评估,设置该参数表示进行评估,默认不设置。
* `do_export`:是否进行导出,设置该参数表示进行静态图导出,默认不设置。
* `export_model_dir`:静态图导出地址,默认为None。
* `overwrite_output_dir`: 如果 `True`,覆盖输出目录的内容。如果 `output_dir` 指向检查点目录,则使用它继续训练。
* `disable_tqdm`: 是否使用tqdm进度条。
* `metric_for_best_model`:最优模型指标,UIE-X 推荐设置为 `eval_f1`,默认为None。
* `load_best_model_at_end`:训练结束后是否加载最优模型,通常与`metric_for_best_model`配合使用,默认为False。
* `save_total_limit`:如果设置次参数,将限制checkpoint的总数。删除旧的checkpoints `输出目录`,默认为None。
<a name="模型评估"></a>
### 2.4 模型评估
通过运行以下命令进行模型评估:
```shell
python evaluate.py \
--model_path ./checkpoint/model_best \
--test_path ./data/dev.txt \
--device gpu \
--batch_size 16 \
--max_seq_len 512
```
通过运行以下命令对 UIE-M 进行模型评估:
```
python evaluate.py \
--model_path ./checkpoint/model_best \
--test_path ./data/dev.txt \
--batch_size 16 \
--device gpu \
--max_seq_len 512 \
--multilingual
```
评估方式说明:采用单阶段评价的方式,即关系抽取、事件抽取等需要分阶段预测的任务对每一阶段的预测结果进行分别评价。验证/测试集默认会利用同一层级的所有标签来构造出全部负例。
可开启`debug`模式对每个正例类别分别进行评估,该模式仅用于模型调试:
```shell
python evaluate.py \
--model_path ./checkpoint/model_best \
--test_path ./data/dev.txt \
--debug
```
输出打印示例:
```text
[2022-11-21 12:48:41,794] [ INFO] - -----------------------------
[2022-11-21 12:48:41,795] [ INFO] - Class Name: 武器名称
[2022-11-21 12:48:41,795] [ INFO] - Evaluation Precision: 0.96667 | Recall: 0.96667 | F1: 0.96667
[2022-11-21 12:48:44,093] [ INFO] - -----------------------------
[2022-11-21 12:48:44,094] [ INFO] - Class Name: X的产国
[2022-11-21 12:48:44,094] [ INFO] - Evaluation Precision: 1.00000 | Recall: 0.99275 | F1: 0.99636
[2022-11-21 12:48:46,474] [ INFO] - -----------------------------
[2022-11-21 12:48:46,475] [ INFO] - Class Name: X的研发单位
[2022-11-21 12:48:46,475] [ INFO] - Evaluation Precision: 0.77519 | Recall: 0.64935 | F1: 0.70671
[2022-11-21 12:48:48,800] [ INFO] - -----------------------------
[2022-11-21 12:48:48,801] [ INFO] - Class Name: X的类型
[2022-11-21 12:48:48,801] [ INFO] - Evaluation Precision: 1.00000 | Recall: 1.00000 | F1: 1.00000
```
可配置参数说明:
- `device`: 评估设备,可选择 'cpu'、'gpu'、'npu' 其中的一种;默认为 GPU 评估。
- `model_path`: 进行评估的模型文件夹路径,路径下需包含模型权重文件`model_state.pdparams`及配置文件`model_config.json`。
- `test_path`: 进行评估的测试集文件。
- `batch_size`: 批处理大小,请结合机器情况进行调整,默认为16。
- `max_seq_len`: 文本最大切分长度,输入超过最大长度时会对输入文本进行自动切分,默认为512。
- `debug`: 是否开启debug模式对每个正例类别分别进行评估,该模式仅用于模型调试,默认关闭。
- `multilingual`: 是否是跨语言模型,默认关闭。
- `schema_lang`: 选择schema的语言,可选有`ch`和`en`。默认为`ch`,英文数据集请选择`en`。
<a name="定制模型一键预测"></a>
### 2.5 定制模型一键预测
`paddlenlp.Taskflow`装载定制模型,通过`task_path`指定模型权重文件的路径,路径下需要包含训练好的模型权重文件`model_state.pdparams`。
```python
>>> from pprint import pprint
>>> from paddlenlp import Taskflow
>>> schema = {"武器名称": ["产国", "类型", "研发单位"]}
# 设定抽取目标和定制化模型权重路径
>>> my_ie = Taskflow("information_extraction", schema=schema, task_path='./checkpoint/model_best')
>>> pprint(my_ie("威尔哥(Virgo)减速炸弹是由瑞典FFV军械公司专门为瑞典皇家空军的攻击机实施低空高速轰炸而研制,1956年开始研制,1963年进入服役,装备于A32“矛盾”、A35“龙”、和AJ134“雷”攻击机,主要用于攻击登陆艇、停放的飞机、高炮、野战火炮、轻型防护装甲车辆以及有生力量。"))
[{'武器名称': [{'end': 14,
'probability': 0.9998632702221926,
'relations': {'产国': [{'end': 18,
'probability': 0.9998815094394331,
'start': 16,
'text': '瑞典'}],
'研发单位': [{'end': 25,
'probability': 0.9995875123178521,
'start': 18,
'text': 'FFV军械公司'}],
'类型': [{'end': 14,
'probability': 0.999877336059086,
'start': 12,
'text': '炸弹'}]},
'start': 0,
'text': '威尔哥(Virgo)减速炸弹'}]}]
```
<a name="实验指标"></a>
### 2.6 实验指标
军事关系抽取数据集实验指标:
| | Precision | Recall | F1 Score |
| :---: | :--------: | :--------: | :--------: |
| 0-shot | 0.64634| 0.53535 | 0.58564 |
| 5-shot | 0.89474 | 0.85000 | 0.87179 |
| 10-shot | 0.92793 | 0.85833 | 0.89177 |
| full-set | 0.93103 | 0.90000 | 0.91525 |
<a name="封闭域蒸馏"></a>
### 2.7 封闭域蒸馏
在一些工业应用场景中对性能的要求较高,模型若不能有效压缩则无法实际应用。因此,我们基于数据蒸馏技术构建了UIE Slim数据蒸馏系统。其原理是通过数据作为桥梁,将UIE模型的知识迁移到封闭域信息抽取小模型,以达到精度损失较小的情况下却能达到大幅度预测速度提升的效果。详细介绍请参考[UIE Slim 数据蒸馏](./data_distill/README.md)

View File

@@ -1,156 +0,0 @@
# UIE Slim 数据蒸馏
在UIE强大的抽取能力背后,同样需要较大的算力支持计算。在一些工业应用场景中对性能的要求较高,若不能有效压缩则无法实际应用。因此,我们基于数据蒸馏技术构建了UIE Slim数据蒸馏系统。其原理是通过数据作为桥梁,将UIE模型的知识迁移到封闭域信息抽取小模型,以达到精度损失较小的情况下却能达到大幅度预测速度提升的效果。
#### UIE数据蒸馏三步
- **Step 1**: 使用UIE模型对标注数据进行finetune,得到Teacher Model。
- **Step 2**: 用户提供大规模无标注数据,需与标注数据同源。使用Taskflow UIE对无监督数据进行预测。
- **Step 3**: 使用标注数据以及步骤2得到的合成数据训练出封闭域Student Model。
## UIE Finetune
参考[UIE关系抽取微调](../README.md)完成模型微调,得到``../checkpoint/model_best``。
## 离线蒸馏
#### 通过训练好的UIE定制模型预测无监督数据的标签
```shell
python data_distill.py \
--data_path ../data \
--save_dir student_data \
--task_type relation_extraction \
--synthetic_ratio 10 \
--model_path ../checkpoint/model_best
```
**NOTE**:schema需要根据标注数据在`data_distill.py`中进行配置,且schema需要包含标注数据中的所有标签类型。
可配置参数说明:
- `data_path`: 标注数据(`doccano_ext.json`)及无监督文本(`unlabeled_data.txt`)路径。
- `model_path`: 训练好的UIE定制模型路径。
- `save_dir`: 学生模型训练数据保存路径。
- `synthetic_ratio`: 控制合成数据的比例。最大合成数据数量=synthetic_ratio*标注数据数量。
- `platform`: 标注数据的所使用的标注平台,可选有`doccano`,`label_studio`,默认为`label_studio`。
- `task_type`: 选择任务类型,可选有`entity_extraction`,`relation_extraction`,`event_extraction`和`opinion_extraction`。因为是封闭域抽取,不同任务的后处理逻辑不同,因此需指定任务类型。
- `seed`: 随机种子,默认为1000。
#### 老师模型评估
UIE微调阶段针对UIE训练格式数据评估模型效果(该评估方式非端到端评估,非关系抽取或事件抽取的标准评估方式),可通过以下评估脚本进行端到端评估。
```shell
python evaluate_teacher.py \
--task_type relation_extraction \
--test_path ./student_data/dev_data.json \
--label_maps_path ./student_data/label_maps.json \
--model_path ../checkpoint/model_best
```
可配置参数说明:
- `model_path`: 训练好的UIE定制模型路径。
- `test_path`: 测试数据集路径。
- `label_maps_path`: 学生模型标签字典。
- `batch_size`: 批处理大小,默认为8。
- `max_seq_len`: 最大文本长度,默认为256。
- `task_type`: 选择任务类型,可选有`entity_extraction`,`relation_extraction`,`event_extraction`和`opinion_extraction`。因为是封闭域信息抽取的评估,需指定任务类型。
#### 学生模型训练
```shell
python train.py \
--task_type relation_extraction \
--train_path student_data/train_data.json \
--dev_path student_data/dev_data.json \
--label_maps_path student_data/label_maps.json \
--num_epochs 50 \
--encoder ernie-3.0-mini-zh
```
可配置参数说明:
- `train_path`: 训练集文件路径。
- `dev_path`: 验证集文件路径。
- `batch_size`: 批处理大小,默认为16。
- `learning_rate`: 学习率,默认为3e-5。
- `save_dir`: 模型存储路径,默认为`./checkpoint`。
- `max_seq_len`: 最大文本长度,默认为256。
- `weight_decay`: 表示AdamW优化器中使用的 weight_decay 的系数。
- `warmup_proportion`: 学习率warmup策略的比例,如果0.1,则学习率会在前10%训练step的过程中从0慢慢增长到learning_rate, 而后再缓慢衰减,默认为0.0。
- `num_epochs`: 训练轮数,默认为100。
- `seed`: 随机种子,默认为1000。
- `encoder`: 选择学生模型的模型底座,默认为`ernie-3.0-mini-zh`。
- `task_type`: 选择任务类型,可选有`entity_extraction`,`relation_extraction`,`event_extraction`和`opinion_extraction`。因为是封闭域信息抽取,需指定任务类型。
- `logging_steps`: 日志打印的间隔steps数,默认10。
- `eval_steps`: evaluate的间隔steps数,默认200。
- `device`: 选用什么设备进行训练,可选cpu或gpu。
- `init_from_ckpt`: 可选,模型参数路径,热启动模型训练;默认为None。
#### 学生模型评估
```shell
python evaluate.py \
--model_path ./checkpoint/model_best \
--test_path student_data/dev_data.json \
--task_type relation_extraction \
--label_maps_path student_data/label_maps.json \
--encoder ernie-3.0-mini-zh
```
可配置参数说明:
- `model_path`: 训练好的UIE定制模型路径。
- `test_path`: 测试数据集路径。
- `label_maps_path`: 学生模型标签字典。
- `batch_size`: 批处理大小,默认为8。
- `max_seq_len`: 最大文本长度,默认为256。
- `encoder`: 选择学生模型的模型底座,默认为`ernie-3.0-mini-zh`。
- `task_type`: 选择任务类型,可选有`entity_extraction`,`relation_extraction`,`event_extraction`和`opinion_extraction`。因为是封闭域信息抽取的评估,需指定任务类型。
## Taskflow部署学生模型
- 通过Taskflow一键部署封闭域信息抽取模型,`task_path`为学生模型路径。
```python
>>> from pprint import pprint
>>> from paddlenlp import Taskflow
>>> my_ie = Taskflow("information_extraction", model="uie-data-distill-gp", task_path="checkpoint/model_best/") # Schema is fixed in closed-domain information extraction
>>> pprint(my_ie("威尔哥(Virgo)减速炸弹是由瑞典FFV军械公司专门为瑞典皇家空军的攻击机实施低空高速轰炸而研制,1956年开始研制,1963年进入服役,装备于A32“矛盾”、A35“龙”、和AJ134“雷”攻击机,主要用于攻击登陆艇、停放的飞机、高炮、野战火炮、轻型防护装甲车辆以及有生力量。"))
[{'武器名称': [{'end': 14,
'probability': 0.9976037,
'relations': {'产国': [{'end': 18,
'probability': 0.9988706,
'relations': {},
'start': 16,
'text': '瑞典'}],
'研发单位': [{'end': 25,
'probability': 0.9978277,
'relations': {},
'start': 18,
'text': 'FFV军械公司'}],
'类型': [{'end': 14,
'probability': 0.99837446,
'relations': {},
'start': 12,
'text': '炸弹'}]},
'start': 0,
'text': '威尔哥(Virgo)减速炸弹'}]}]
```
# References
- **[GlobalPointer](https://kexue.fm/search/globalpointer/)**
- **[GPLinker](https://kexue.fm/archives/8888)**
- **[JunnYu/GPLinker_pytorch](https://github.com/JunnYu/GPLinker_pytorch)**
- **[CBLUE](https://github.com/CBLUEbenchmark/CBLUE)**

View File

@@ -1,58 +0,0 @@
# 基于PaddleNLP SimpleServing 的服务化部署
## 目录
- [环境准备](#环境准备)
- [Server服务启动](#Server服务启动)
- [Client请求启动](#Client请求启动)
- [服务化自定义参数](#服务化自定义参数)
## 环境准备
使用有SimpleServing功能的PaddleNLP版本(或者最新的develop版本)
```shell
pip install paddlenlp >= 2.4.4
```
## Server服务启动
```bash
paddlenlp server server:app --workers 1 --host 0.0.0.0 --port 8189
```
## Client请求启动
```bash
python client.py
```
## 服务化自定义参数
### Server 自定义参数
#### schema替换
```python
# Default schema
schema = {"武器名称": ["产国", "类型", "研发单位"]}
```
#### 设置模型路径
```
# Default task_path
uie = Taskflow('information_extraction', model='uie-data-distill-gp', task_path='../../checkpoint/model_best/', schema=schema)
```
#### 多卡服务化预测
PaddleNLP SimpleServing 支持多卡负载均衡预测,主要在服务化注册的时候,注册两个Taskflow的task即可,下面是示例代码
```
uie1 = Taskflow('information_extraction', model='uie-data-distill-gp', task_path='../../checkpoint/model_best/', schema=schema, device_id=0)
uie2 = Taskflow('information_extraction', model='uie-data-distill-gp', task_path='../../checkpoint/model_best/', schema=schema, device_id=1)
service.register_taskflow('uie', [uie1, uie2])
```
### Client 自定义参数
```python
# Changed to input texts you wanted
texts = ['威尔哥(Virgo)减速炸弹是由瑞典FFV军械公司专门为瑞典皇家空军的攻击机实施低空高速轰炸而研制,1956年开始研制,1963年进入服役,装备于A32“矛盾”、A35“龙”、和AJ134“雷”攻击机,主要用于攻击登陆艇、停放的飞机、高炮、野战火炮、轻型防护装甲车辆以及有生力量。']
```

View File

@@ -1,58 +0,0 @@
# 基于PaddleNLP SimpleServing 的服务化部署
## 目录
- [环境准备](#环境准备)
- [Server服务启动](#Server服务启动)
- [Client请求启动](#Client请求启动)
- [服务化自定义参数](#服务化自定义参数)
## 环境准备
使用有SimpleServing功能的PaddleNLP版本(或者最新的develop版本)
```shell
pip install paddlenlp >= 2.4.4
```
## Server服务启动
```bash
paddlenlp server server:app --workers 1 --host 0.0.0.0 --port 8189
```
## Client请求启动
```bash
python client.py
```
## 服务化自定义参数
### Server 自定义参数
#### schema替换
```python
# Default schema
schema = {"武器名称": ["产国", "类型", "研发单位"]}
```
#### 设置模型路径
```
# Default task_path
uie = Taskflow('information_extraction', task_path='../../checkpoint/model_best/', schema=schema)
```
#### 多卡服务化预测
PaddleNLP SimpleServing 支持多卡负载均衡预测,主要在服务化注册的时候,注册两个Taskflow的task即可,下面是示例代码
```
uie1 = Taskflow('information_extraction', task_path='../../checkpoint/model_best/', schema=schema, device_id=0)
uie2 = Taskflow('information_extraction', task_path='../../checkpoint/model_best/', schema=schema, device_id=1)
service.register_taskflow('uie', [uie1, uie2])
```
### Client 自定义参数
```python
# Changed to input texts you wanted
texts = ['威尔哥(Virgo)减速炸弹是由瑞典FFV军械公司专门为瑞典皇家空军的攻击机实施低空高速轰炸而研制,1956年开始研制,1963年进入服役,装备于A32“矛盾”、A35“龙”、和AJ134“雷”攻击机,主要用于攻击登陆>艇、停放的飞机、高炮、野战火炮、轻型防护装甲车辆以及有生力量。']
```

View File

@@ -1,501 +0,0 @@
# 手把手搭建一个语义检索系统
## 1. 场景概述
检索系统存在于我们日常使用的很多产品中,比如商品搜索系统、学术文献检索系等等,本方案提供了检索系统完整实现。限定场景是用户通过输入检索词 Query,快速在海量数据中查找相似文档。
<div align="center">
<img src="https://user-images.githubusercontent.com/12107462/191490721-90a8f526-ad64-4f2b-b9b4-34ab06c6749b.png" width="500px">
</div>
所谓语义检索(也称基于向量的检索,如上图所示),是指检索系统不再拘泥于用户 Query 字面本身,而是能精准捕捉到用户 Query 后面的真正意图并以此来搜索,从而更准确地向用户返回最符合的结果。通过使用最先进的语义索引模型找到文本的向量表示,在高维向量空间中对它们进行索引,并度量查询向量与索引文档的相似程度,从而解决了关键词索引带来的缺陷。
例如下面两组文本 Pair,如果基于关键词去计算相似度,两组的相似度是相同的。而从实际语义上看,第一组相似度高于第二组。
```
车头如何放置车牌 前牌照怎么装
车头如何放置车牌 后牌照怎么装
```
语义检索系统的关键就在于,采用语义而非关键词方式进行召回,达到更精准、更广泛得召回相似结果的目的。想快速体验搜索的效果,请参考[Pipelines的语义检索实现](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/pipelines/examples/semantic-search)
<div align="center">
<img src="https://user-images.githubusercontent.com/12107462/190302765-663ba441-9dd3-470a-8fee-f7a6f81da615.gif" width="500px">
</div>
## 2. 产品功能介绍
通常检索业务的数据都比较庞大,都会分为召回(索引)、排序两个环节。召回阶段主要是从至少千万级别的候选集合里面,筛选出相关的文档,这样候选集合的数目就会大大降低,在之后的排序阶段就可以使用一些复杂的模型做精细化或者个性化的排序。一般采用多路召回策略(例如关键词召回、热点召回、语义召回结合等),多路召回结果聚合后,经过统一的打分以后选出最优的 TopK 的结果。
### 2.1 系统特色
+ 低门槛
+ 手把手搭建起检索系统
+ 无需标注数据也能构建检索系统
+ 提供 训练、预测、ANN 引擎一站式能力
+ Pipelines 快速实现语义检索系统
+ 效果好
+ 针对多种数据场景的专业方案
+ 仅有无监督数据: SimCSE
+ 仅有有监督数据: InBatchNegative
+ 兼具无监督数据 和 有监督数据:融合模型
+ 进一步优化方案: 面向领域的预训练 Domain-adaptive Pretraining
+ 性能快
+ Paddle Inference 快速抽取向量
+ Milvus 快速查询和高性能建库
+ Paddle Serving服务化部署
### 2.2 功能架构
索引环节有两类方法:基于字面的关键词索引;语义索引。语义索引能够较好地表征语义信息,解决字面不相似但语义相似的情形。本系统给出的是语义索引方案,实际业务中可融合其他方案使用。下面就详细介绍整个方案的架构和功能。
#### 2.2.1 整体介绍
<div align="center">
<img src="https://user-images.githubusercontent.com/12107462/191469309-42a54a67-a3a3-4e43-b6b1-b12be81ddf3d.png" width="800px">
</div>
以上是nerual_search的系统流程图,其中左侧为召回环节,核心是语义向量抽取模块;右侧是排序环节,核心是排序模型。召回环节需要用户通过自己的语料构建向量索引库,用户发起query了之后,就可以检索出相似度最高的向量,然后找出该向量对应的文本;排序环节主要是对召回的文本进行重新排序。下面我们分别介绍召回中的语义向量抽取模块,以及排序模型。
#### 2.2.2 召回模块
召回模块需要从千万量级数据中快速召回候选数据。首先需要抽取语料库中文本的 Embedding,然后借助向量搜索引擎实现高效 ANN,从而实现候选集召回。
我们针对不同的数据情况推出三种语义索引方案,如下图所示,您可以参照此方案,快速建立语义索引:
| ⭐️ 无监督数据 | ⭐️ 有监督数据 | **召回方案** |
| ------------ | ------------ | ------------ |
| 多 | 无 | SimCSE |
| 无 | 多 | In-batch Negatives|
| 有 | 有 | SimCSE+ In-batch Negatives |
最基本的情况是只有无监督数据,我们推荐您使用 SimCSE 进行无监督训练;另一种方案是只有有监督数据,我们推荐您使用 In-batch Negatives 的方法进行有监督训练。
如果想进一步提升模型效果:还可以使用大规模业务数据,对预训练模型进行 Domain-adaptive Pretraining,训练完以后得到预训练模型,再进行无监督的 SimCSE。
此外,如果您同时拥有监督数据和无监督数据,我们推荐将两种方案结合使用,这样能训练出更加强大的语义索引模型。
#### 2.2.3 排序模块
召回模型负责从海量(千万级)候选文本中快速(毫秒级)筛选出与 Query 相关性较高的 TopK Doc,排序模型会在召回模型筛选出的 TopK Doc 结果基础之上针对每一个 (Query, Doc) Pair 对进行两两匹配计算相关性,排序效果更精准。
排序模块有2种选择,第一种基于前沿的预训练模型 ERNIE,训练 Pair-wise 语义匹配模型;第二种是基于RocketQA模型训练的Cross Encoder模形。第一种是Pair-wise的排序算法,基本思路是对样本构建偏序文档对,两两比较,从比较中学习顺序,第二种是Poinet-Wise的算法,只考虑当前Query和每个文档的绝对相关度,并没有考虑其他文档与Query的相关度,但是建模方式比较简单。第一种Pair-wise模型可以说是第二种point-wise模型的改进版本,但对于噪声数据更为敏感,即一个错误的标注会导致多个pair对的错误,用户可以先使用基于Point-wise的Cross Encoder构建一个基础模型,需要进一步优化可以使用Pair-wise的方法优化。
## 3. 文献检索实践
### 3.1 技术方案和评估指标
#### 3.1.1 技术方案
**语义索引**:由于我们既有无监督数据,又有有监督数据,所以结合 SimCSE 和 In-batch Negatives 方案,并采取 Domain-adaptive Pretraining 优化模型效果。
首先是利用 ERNIE模型进行 Domain-adaptive Pretraining,在得到的预训练模型基础上,进行无监督的 SimCSE 训练,最后利用 In-batch Negatives 方法进行微调,得到最终的语义索引模型,把建库的文本放入模型中抽取特征向量,然后把抽取后的向量放到语义索引引擎 milvus 中,利用 milvus 就可以很方便得实现召回了。
**排序**:使用 ERNIE-Gram 的单塔结构/RocketQA的Cross Encoder对召回后的数据精排序。
#### 3.1.2 评估指标
**模型效果指标**
* 在语义索引召回阶段使用的指标是 Recall@K,表示的是预测的前topK(从最后的按得分排序的召回列表中返回前K个结果)结果和语料库中真实的前 K 个相关结果的重叠率,衡量的是检索系统的查全率。
* 在排序阶段使用的指标为AUC,AUC反映的是分类器对样本的排序能力,如果完全随机得对样本分类,那么AUC应该接近0.5。分类器越可能把真正的正样本排在前面,AUC越大,分类性能越好。
**性能指标**
* 基于 Paddle Inference 快速抽取向量
* 建库性能和 ANN 查询性能快
### 3.2 预置数据说明
数据集来源于某文献检索系统,既有大量无监督数据,又有有监督数据。
(1)采用文献的 query, title,keywords,abstract 四个字段内容,构建无标签数据集进行 Domain-adaptive Pretraining;
(2)采用文献的 query,title,keywords 三个字段内容,构造无标签数据集,进行无监督召回训练SimCSE;
(3)使用文献的query, title, keywords,构造带正标签的数据集,不包含负标签样本,基于 In-batch Negatives 策略进行训练;
(4)在排序阶段,使用点击(作为正样本)和展现未点击(作为负样本)数据构造排序阶段的训练集,进行精排训练。
| 阶段 |模型 | 训练集 | 评估集(用于评估模型效果) | 召回库 |测试集 |
| ------------ | ------------ |------------ | ------------ | ------------ | ------------ |
| 召回 | Domain-adaptive Pretraining | 2kw | - | - | - |
| 召回 | 无监督预训练 - SimCSE | 798w | 20000 | 300000| 1000 |
| 召回 | 有监督训练 - In-batch Negatives | 3998 | 20000 |300000 | 1000 |
| 排序 | 有监督训练 - ERNIE-Gram单塔 Pairwise/RocketQA Cross Encoder| 1973538 | 57811 | - | 1000 |
我们将除 Domain-adaptive Pretraining 之外的其他数据集全部开源,下载地址:
- [literature_search_data](https://bj.bcebos.com/v1/paddlenlp/data/literature_search_data.zip)
- [literature_search_rank](https://paddlenlp.bj.bcebos.com/applications/literature_search_rank.zip)
```
├── milvus # milvus建库数据集
├── milvus_data.csv. # 构建召回库的数据(模拟实际业务线上的语料库,实际语料库远大于这里的规模),用于直观演示相关文献召回效果
├── recall # 召回阶段数据集
├── train_unsupervised.csv # 无监督训练集,用于训练 SimCSE
├── train.csv # 有监督训练集,用于训练 In-batch Negative
├── dev.csv # 召回阶段验证集,用于评估召回模型的效果,SimCSE 和 In-batch Negative 共用
├── corpus.csv # 构建召回库的数据(模拟实际业务线上的语料库,实际语料库远大于这里的规模),用于评估召回阶段模型效果,SimCSE 和 In-batch Negative 共用
├── test.csv # 召回阶段测试数据,预测文本之间的相似度,SimCSE 和 In-batch Negative 共用
├── data # RocketQA排序数据集
├── test.csv # 测试集
├── dev_pairwise.csv # 验证集
└── train.csv # 训练集
├── sort # 排序阶段数据集
├── train_pairwise.csv # 排序训练集
├── dev_pairwise.csv # 排序验证集
└── test_pairwise.csv # 排序测试集
```
### 3.3 数据格式
1. 对于无监督SimCSE的训练方法,格式参考`train_unsupervised.csv`,即一行条文本即可,无需任何标注。对于召回模型训练需要规定格式的本地数据集,需要准备训练集文件`train.csv`,验证集`dev.csv`,召回集文件`corpus.csv`。
训练数据集`train.csv`的格式如下:
```
query1 \t 用户点击的title1
query2 \t 用户点击的title2
```
训练集合`train.csv`的文件样例:
```
从《唐律疏义》看唐代封爵贵族的法律特权 从《唐律疏义》看唐代封爵贵族的法律特权《唐律疏义》,封爵贵族,法律特权
宁夏社区图书馆服务体系布局现状分析 宁夏社区图书馆服务体系布局现状分析社区图书馆,社区图书馆服务,社区图书馆服务体系
人口老龄化对京津冀经济 京津冀人口老龄化对区域经济增长的影响京津冀,人口老龄化,区域经济增长,固定效应模型
英语广告中的模糊语 模糊语在英语广告中的应用及其功能模糊语,英语广告,表现形式,语用功能
甘氨酸二肽的合成 甘氨酸二肽合成中缩合剂的选择甘氨酸,缩合剂,二肽
......
```
验证集`dev.csv`的格式如下:
```
query1 \t 用户点击的title1
query2 \t 用户点击的title2
```
验证集合`train.csv`的文件样例:
```
试论我国海岸带经济开发的问题与前景 试论我国海岸带经济开发的问题与前景海岸带,经济开发,问题,前景
外语阅读焦虑与英语成绩及性别的关系 外语阅读焦虑与英语成绩及性别的关系外语阅读焦虑,外语课堂焦虑,英语成绩,性别
加油站风险分级管控 加油站工作危害风险分级研究加油站,工作危害分析(JHA),风险分级管控
```
召回集合`corpus.csv`主要作用是检验测试集合的句子对能否被正确召回,它的构造主要是提取验证集的第二列的句子,然后加入很多无关的句子,用来检验模型能够正确的从这些文本中找出测试集合对应的第二列的句子,格式如下:
```
2002-2017年我国法定传染病发病率和死亡率时间变化趋势传染病,发病率,死亡率,病死率
陕西省贫困地区城乡青春期少女生长发育调查青春期,生长发育,贫困地区
五丈岩水库溢洪道加固工程中的新材料应用碳纤维布,粘钢加固技术,超细水泥,灌浆技术
......
```
2. 对于排序模型的训练,排序模型目前提供了2种,第一种是Pairwise训练的方式,第二种是RocketQA的排序模型,对于第一种排序模型,需要准备训练集`train_pairwise.csv`,验证集`dev_pairwise.csv`两个文件,除此之外还可以准备测试集文件`test.csv`或者`test_pairwise.csv`。
训练数据集`train_pairwise.csv`的格式如下:
```
query1 \t 用户点击的title1 \t 用户未点击的title2
query2 \t 用户点击的title3 \t 用户未点击的title4
```
训练数据集`train_pairwise.csv`的示例如下:
```
英语委婉语引起的跨文化交际障碍 英语委婉语引起的跨文化交际障碍及其翻译策略研究英语委婉语,跨文化交际障碍,翻译策略 委婉语在英语和汉语中的文化差异委婉语,文化,跨文化交际
范迪慧 嘉兴市中医院 滋阴疏肝汤联合八穴隔姜灸治疗肾虚肝郁型卵巢功能低下的临床疗效滋阴疏肝汤,八穴隔姜灸,肾虚肝郁型卵巢功能低下,性脉甾类激素,妊娠 温针灸、中药薰蒸在半月板损伤术后康复中的疗效分析膝损伤,半月板,胫骨,中医康复,温针疗法,薰洗
......
```
验证数据集`dev_pairwise.csv`的格式如下:
```
query1 \t title1 \t label
query2 \t title2 \t label
```
验证数据集`dev_pairwise.csv`的示例如下:
```
作者单位:南州中学 浅谈初中教学管理如何体现人文关怀初中教育,教学管理,人文关怀 1
作者单位:南州中学 高中美术课堂教学中藏区本土民间艺术的融入路径藏区,传统民间艺术,美术课堂 0
作者单位:南州中学 列宁关于资产阶级民主革命向 社会主义革命过渡的理论列宁,直接过渡,间接过渡,资产阶级民主革命,社会主义革命 0
DAA髋关节置换 DAA前侧入路和后外侧入路髋关节置换疗效对比髋关节置换术;直接前侧入路;后外侧入路;髋关节功能;疼痛;并发症 1
DAA髋关节置换 DAA全髋关节置换术治疗髋关节病变对患者髋关节运动功能的影响直接前侧入路全髋关节置换术,髋关节病变,髋关节运动功能 0
DAA髋关节置换 护患沟通技巧在急诊输液护理中的应用分析急诊科,输液护理,护理沟通技巧,应用 0
.......
```
训练数据集`test_pairwise.csv`的格式如下,其中这个score得分是召回算出来的相似度或者距离,仅供参考,可以忽略:
```
query1 \t title1 \t score
query2 \t title2 \t score
```
训练数据集`test_pairwise.csv`的示例如下:
```
中西方语言与文化的差异 中西方文化差异以及语言体现中西方文化,差异,语言体现 0.43203747272491455
中西方语言与文化的差异 论中西方文化差异在非言语交际中的体现中西方文化,差异,非言语交际 0.4644506871700287
中西方语言与文化的差异 中西方体态语文化差异跨文化,体态语,非语言交际,差异 0.4917311668395996
中西方语言与文化的差异 由此便可以发现两种语言以及两种文化的差异。 0.5039259195327759
.......
```
对于第二种基于RocketQA的排序模型。
训练数据集`train.csv`,验证集`dev_pairwise.csv`的格式如下:
```
query1 \t title1 \t label
query2 \t title2 \t label
```
训练数据集`train.csv`,验证集`dev_pairwise.csv`的示例如下:
```
(小学数学教材比较) 关键词:新加坡 新加坡与中国数学教材的特色比较数学教材,教材比较,问题解决 0
徐慧新疆肿瘤医院 头颈部非霍奇金淋巴瘤扩散加权成像ADC值与Ki-67表达相关性分析淋巴瘤,非霍奇金,头颈部肿瘤,磁共振成像 1
抗生素关性腹泻 鼠李糖乳杆菌GG防治消化系统疾病的研究进展鼠李糖乳杆菌,腹泻,功能性胃肠病,肝脏疾病,幽门螺杆菌 0
德州市图书馆 图书馆智慧化建设与融合创新服务研究图书馆;智慧化;阅读服务;融合创新 1
维生素c 综述 维生素C防治2型糖尿病研究进展维生素C;2型糖尿病;氧化应激;自由基;抗氧化剂 0
.......
```
训练数据集`test.csv`的格式如下,其中这个score得分是召回算出来的相似度或者距离,仅供参考,可以忽略:
```
query1 \t title1 \t score
query2 \t title2 \t score
```
训练数据集`test.csv`的示例如下:
```
加强科研项目管理有效促进医学科研工作 科研项目管理策略科研项目,项目管理,实施,必要性,策略 0.32163668
加强科研项目管理有效促进医学科研工作 关于推进我院科研发展进程的相关问题研究医院科研,主体,环境,信息化 0.32922596
加强科研项目管理有效促进医学科研工作 深圳科技计划对高校科研项目资助现状分析与思考基础研究,高校,科技计划,科技创新 0.36869502
加强科研项目管理有效促进医学科研工作 普通高校科研管理模式的优化与创新普通高校,科研,科研管理 0.3688045
.......
```
### 3.4 运行环境和安装说明
(1)运行环境
本实验采用了以下的运行环境进行,详细说明如下,用户也可以在自己 GPU 硬件环境进行:
a. 软件环境:
- python >= 3.6
- paddlenlp >= 2.2.1
- paddlepaddle-gpu >=2.2
- CUDA Version: 10.2
- NVIDIA Driver Version: 440.64.00
- Ubuntu 16.04.6 LTS (Docker)
b. 硬件环境:
- NVIDIA Tesla V100 16GB x4卡
- Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz
c. 依赖安装:
```
pip install -r requirements.txt
```
## 4. Neural Search 快速体验实践
PaddleNLP已经基于ERNIE 1.0训练了一个基线模型,如果想快速搭建Neural Search的完整系统,有两种方法,第一种是请参考下面的实现,包含了服务化的完整流程,另一种是使用Pipelines加载,Pipelines已经支持Neural Search训练的模型的载入,可以使用Pipelines的快速的基于Neural Search模型实现检索系统,详情请参考文档[Pipelines-Neural-Search](https://github.com/PaddlePaddle/PaddleNLP/blob/develop/pipelines/examples/semantic-search/Neural_Search.md)。
### 4.1. 召回
- 召回向量抽取服务的搭建请参考:[In-batch Negatives](./recall/in_batch_negative/), 只需要下载基于ERNIE 1.0的预训练模型,导出成Paddle Serving的格式,然后启动Pipeline Server服务即可
- 召回向量检索服务的搭建请参考:[Milvus](./recall/milvus/), 需要搭建Milvus并且插入检索数据的向量
【注意】如果使用Neural Search训练好的模型,由于该模型是基于ERNIE 1.0训练的,所以需要把 `model_name_or_path`指定为`ernie 1.0`,向量抽取结果才能正常。
### 4.2. 排序
排序服务的搭建请参考 [ernie_matching](./ranking/ernie_matching/),只需要下载基于ERNIE Gram的预训练模型,导出成Paddle Serving的格式,最后需要启动 Pipeline Serving服务
【注意】如果使用Neural Search训练好的模型,由于该模型是基于ERNIE Gram训练的,所以需要把 `model_name_or_path`指定为`ernie-gram-zh`,向量抽取结果才能正常。
### 4.3. 系统运行
以上召回和排序模型都经过Paddle Serving服务化以后,就可以直接使用下面的命令运行体验:
```
python3 run_system.py
```
输出的结果为:
```
PipelineClient::predict pack_data time:1656991375.5521955
PipelineClient::predict before time:1656991375.5529568
Extract feature time to cost :0.0161135196685791 seconds
Search milvus time cost is 0.8139839172363281 seconds
PipelineClient::predict pack_data time:1656991376.3981335
PipelineClient::predict before time:1656991376.3983877
time to cost :0.05616641044616699 seconds
```
会输出2个文件 `recall_result.csv` 是召回检索的结果,`rank_result.csv` 是排序的结果。csv的示例输出下。
召回的结果:
```
中西方语言与文化的差异,港台文化对内地中小学生的负面影响,0.055068351328372955
中西方语言与文化的差异,外来文化在越南的传播与融合,0.05621318891644478
中西方语言与文化的差异,临终关怀中的“仪式”,0.05705389380455017
中西方语言与文化的差异,历史的真实与艺术加工,0.05745899677276611
......
```
排序的结果:
```
中西方语言与文化的差异,论中西方教育差异,0.870943009853363
中西方语言与文化的差异,浅析中西方问候语的差异,0.8468159437179565
中西方语言与文化的差异,文化认同及其根源,0.8288694620132446
中西方语言与文化的差异,从历史文化角度分析中西方学校教育的差异,0.8209370970726013
中西方语言与文化的差异,中西医思维方式的差异,0.8150948882102966
中西方语言与文化的差异,浅析中韩餐桌文化差异,0.7751647233963013
......
```
## 5. 从头开始搭建自己的检索系统
这里展示了能够从头至尾跑通的完整代码,您使用自己的业务数据,照着跑,能搭建出一个给定 Query,返回 topK 相关文档的小型检索系统。您可以参照我们给出的效果和性能数据来检查自己的运行过程是否正确。
### 5.1 召回阶段
**召回模型训练**
我们进行了多组实践,用来对比说明召回阶段各方案的效果:
| 模型 | Recall@1 | Recall@5 |Recall@10 |Recall@20 |Recall@50 |策略简要说明|
| ------------ | ------------ | ------------ |--------- |--------- |--------- |--------- |
| 有监督训练 Baseline | 30.077| 43.513| 48.633 | 53.448 |59.632| 标准 pair-wise 训练范式,通过随机采样产生负样本|
| 有监督训练 In-batch Negatives | 51.301 | 65.309| 69.878| 73.996|78.881| In-batch Negatives 有监督训练|
| 无监督训练 SimCSE | 42.374 | 57.505| 62.641| 67.09|72.331| SimCSE 无监督训练|
| 无监督 + 有监督训练 SimCSE + In-batch Negatives | 55.976 | 71.849| 76.363| 80.49|84.809| SimCSE无监督训练,In-batch Negatives 有监督训练|
| Domain-adaptive Pretraining + SimCSE | 51.031 | 66.648| 71.338 | 75.676 |80.144| ERNIE 预训练,SimCSE 无监督训练|
| Domain-adaptive Pretraining + SimCSE + In-batch Negatives| **58.248** | **75.099**| **79.813**| **83.801**|**87.733**| ERNIE 预训练,SimCSE 无监督训训练,In-batch Negatives 有监督训练|
从上述表格可以看出,首先利用 ERNIE 3.0 做 Domain-adaptive Pretraining ,然后把训练好的模型加载到 SimCSE 上进行无监督训练,最后利用 In-batch Negatives 在有监督数据上进行训练能够获得最佳的性能。[模型下载](https://paddlenlp.bj.bcebos.com/models/inbatch_model_best.zip),模型的使用方式参考[In-batch Negatives](./recall/in_batch_negative/) 。
这里采用 Domain-adaptive Pretraining + SimCSE + In-batch Negatives 方案:
第一步:无监督训练 Domain-adaptive Pretraining
训练用时 16hour55min,可参考:[ERNIE 1.0](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/model_zoo/ernie-1.0)
第二步:无监督训练 SimCSE
训练用时 16hour53min,可参考:[SimCSE](./recall/simcse/)
第三步:有监督训练
几分钟内训练完成,可参考 [In-batch Negatives](./recall/in_batch_negative/)
**召回系统搭建**
召回系统使用索引引擎 Milvus,可参考 [milvus_system](./recall/milvus/)。
我们展示一下系统的效果,输入的文本如下:
```
中西方语言与文化的差异
```
下面是召回的部分结果,第一个是召回的title,第二个数字是计算的相似度距离
```
跨文化中的文化习俗对翻译的影响翻译,跨文化,文化习俗 0.615584135055542
试论翻译过程中的文化差异与语言空缺翻译过程,文化差异,语言空缺,文化对比 0.6155391931533813
中英文化差异及习语翻译习语,文化差异,翻译 0.6153547763824463
英语中的中国文化元素英语,中国文化,语言交流 0.6151996850967407
跨文化交际中的文化误读研究文化误读,影响,中华文化,西方文明 0.6137217283248901
在语言学习中了解中法文化差异文化差异,对话交际,语言 0.6134252548217773
从翻译视角看文化差异影响下的中式英语的应对策略文化差异;中式英语现;汉英翻译;动态对等理论 0.6127341389656067
归化与异化在跨文化传播中的动态平衡归化,异化,翻译策略,跨文化传播,文化外译 0.6127211451530457
浅谈中西言语交际行为中的文化差异交际用语,文化差异,中国,西方 0.6125463843345642
翻译中的文化因素--异化与归化文化翻译,文化因素,异化与归化 0.6111845970153809
历史与文化差异对翻译影响的分析研究历史与文化差异,法汉翻译,翻译方法 0.6107486486434937
从中、韩、美看跨文化交际中的东西方文化差异跨文化交际,东西方,文化差异 0.6091923713684082
试论文化差异对翻译工作的影响文化差异,翻译工作,影响 0.6084284782409668
从归化与异化看翻译中的文化冲突现象翻译,文化冲突,归化与异化,跨文化交际 0.6063553690910339
中西方问候语的文化差异问候语,文化差异,文化背景 0.6054259538650513
中英思维方式的差异对翻译的影响中英文化的差异,中英思维方式的差异,翻译 0.6026732921600342
略论中西方语言文字的特性与差异语言,会意,确意,特性,差异 0.6009351015090942
......
```
### 5.2 排序阶段
排序阶段有2种方案,第一种是[ernie_matching](./ranking/ernie_matching/)使用的模型是 ERNIE-3.0-Medium-zh,用时 20h;第二种是基于RocketQA的排序模型[cross_encoder](./ranking/cross_encoder/),训练用时也是20h左右。
排序阶段的效果评估:
| 模型 | AUC |
| ------------ | ------------ |
| Baseline: In-batch Negatives | 0.582 |
| pairwise ERNIE-Gram |0.801 |
| CrossEncoder:rocketqa-base-cross-encoder |**0.835** |
同样输入文本:
```
中西方语言与文化的差异
```
排序阶段的结果展示如下,第一个是 Title ,第二个数字是计算的概率,显然经排序阶段筛选的文档与 Query 更相关:
```
中西方文化差异以及语言体现中西方文化,差异,语言体现 0.999848484992981
论中西方语言与文化差异的历史渊源中西方语言,中西方文化,差异,历史渊源 0.9998375177383423
从日常生活比较中西方语言与文化的差异中西方,语言,文化,比较 0.9985846281051636
试论中西方语言文化教育的差异比较与融合中西方,语言文化教育,差异 0.9972485899925232
中西方文化差异对英语学习的影响中西方文化,差异,英语,学习 0.9831035137176514
跨文化视域下的中西文化差异研究跨文化,中西,文化差异 0.9781349897384644
中西方文化差异对跨文化交际的影响分析文化差异,跨文化交际,影响 0.9735479354858398
探析跨文化交际中的中西方语言差异跨文化交际,中西方,语言差异 0.9668175578117371
中西方文化差异解读中英文差异表达中西文化,差异表达,跨文化交际 0.9629314541816711
中西方文化差异对英语翻译的影响中西方文化差异,英语翻译,翻译策略,影响 0.9538986086845398
论跨文化交际中的中西方文化冲突跨文化交际,冲突,文化差异,交际策略,全球化 0.9493677616119385
中西方文化差异对英汉翻译的影响中西方文化,文化差异,英汉翻译,影响 0.9430705904960632
中西方文化差异与翻译中西方,文化差异,翻译影响,策略方法,译者素质 0.9401137828826904
外语教学中的中西文化差异外语教学,文化,差异 0.9397934675216675
浅析西语国家和中国的文化差异-以西班牙为例跨文化交际,西语国家,文化差异 0.9373322129249573
中英文化差异在语言应用中的体现中英文化,汉语言,语言应用,语言差异 0.9359155297279358
....
```
## Reference
[1] Tianyu Gao, Xingcheng Yao, Danqi Chen: [SimCSE: Simple Contrastive Learning of Sentence Embeddings](https://arxiv.org/abs/2104.08821). EMNLP (1) 2021: 6894-6910
[2] Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, Wen-tau Yih, [Dense Passage Retrieval for Open-Domain Question Answering](https://arxiv.org/abs/2004.04906). Preprint 2020.
[3] Dongling Xiao, Yu-Kun Li, Han Zhang, Yu Sun, Hao Tian, Hua Wu, Haifeng Wang:
[ERNIE-Gram: Pre-Training with Explicitly N-Gram Masked Language Modeling for Natural Language Understanding](https://arxiv.org/abs/2010.12148). NAACL-HLT 2021: 1702-1715
[4] Yu Sun, Shuohuan Wang, Yu-Kun Li, Shikun Feng, Xuyi Chen, Han Zhang, Xin Tian, Danxiang Zhu, Hao Tian, Hua Wu:
[ERNIE: Enhanced Representation through Knowledge Integration](https://arxiv.org/abs/1904.09223). CoRR abs/1904.09223 (2019)

View File

@@ -1,399 +0,0 @@
**目录**
* [背景介绍](#背景介绍)
* [CrossEncoder](#CrossEncoder)
* [1. 技术方案和评估指标](#技术方案)
* [2. 环境依赖](#环境依赖)
* [3. 代码结构](#代码结构)
* [4. 数据准备](#数据准备)
* [5. 模型训练](#模型训练)
* [6. 评估](#开始评估)
* [7. 预测](#预测)
* [8. 部署](#部署)
<a name="背景介绍"></a>
# 背景介绍
基于RocketQA的CrossEncoder训练的单塔模型,该模型用于搜索的排序阶段,对召回的结果进行重新排序的作用。
<a name="CrossEncoder"></a>
# CrossEncoder
<a name="技术方案"></a>
## 1. 技术方案和评估指标
### 技术方案
加载基于ERNIE 3.0训练过的RocketQA单塔CrossEncoder模型。
### 评估指标
(1)采用 AUC 指标来评估排序模型的排序效果。
**效果评估**
| 训练方式 | 模型 | AUC |
| ------------ | ------------ |------------ |
| pairwise| ERNIE-Gram |0.801 |
| CrossEncoder | rocketqa-base-cross-encoder |**0.835** |
<a name="环境依赖"></a>
## 2. 环境依赖和安装说明
**环境依赖**
* python >= 3.7
* paddlepaddle >= 2.3.7
* paddlenlp >= 2.3
* pandas >= 0.25.1
* scipy >= 1.3.1
<a name="代码结构"></a>
## 3. 代码结构
以下是本项目主要代码结构及说明:
```
ernie_matching/
├── deply # 部署
├── cpp
├── rpc_client.py # RPC 客户端的bash脚本
├── http_client.py # http 客户端的bash文件
└── start_server.sh # 启动C++服务的脚本
└── python
├── deploy.sh # 预测部署bash脚本
├── config_nlp.yml # Pipeline 的配置文件
├── web_service.py # Pipeline 服务端的脚本
├── rpc_client.py # Pipeline RPC客户端的脚本
└── predict.py # python 预测部署示例
|—— scripts
├── export_model.sh # 动态图参数导出静态图参数的bash文件
├── export_to_serving.sh # 导出 Paddle Serving 模型格式的bash文件
├── train_ce.sh # 匹配模型训练的bash文件
├── evaluate_ce.sh # 评估验证文件bash脚本
├── predict_ce.sh # 匹配模型预测脚本的bash文件
├── export_model.py # 动态图参数导出静态图参数脚本
├── export_to_serving.py # 导出 Paddle Serving 模型格式的脚本
├── data.py # 训练样本的转换逻辑
├── train_ce.py # 模型训练脚本
├── evaluate.py # 评估验证文件
├── predict.py # Pair-wise 模型预测脚本,输出文本对是相似度
```
<a name="数据准备"></a>
## 4. 数据准备
### 数据集说明
样例数据如下:
```
(小学数学教材比较) 关键词:新加坡 新加坡与中国数学教材的特色比较数学教材,教材比较,问题解决 0
徐慧新疆肿瘤医院 头颈部非霍奇金淋巴瘤扩散加权成像ADC值与Ki-67表达相关性分析淋巴瘤,非霍奇金,头颈部肿瘤,磁共振成像 1
抗生素关性腹泻 鼠李糖乳杆菌GG防治消化系统疾病的研究进展鼠李糖乳杆菌,腹泻,功能性胃肠病,肝脏疾病,幽门螺杆菌 0
德州市图书馆 图书馆智慧化建设与融合创新服务研究图书馆;智慧化;阅读服务;融合创新 1
维生素c 综述 维生素C防治2型糖尿病研究进展维生素C;2型糖尿病;氧化应激;自由基;抗氧化剂 0
(白藜芦醇) 关键词:2型糖尿病 2型糖尿病大鼠心肌缺血再灌注损伤转录因子E2相关因子2/血红素氧合酶1信号通路的表达及白藜芦醇的干预研究糖尿病,2型,心肌缺血,再灌注损伤,白藜芦醇 1
融资偏好 创新型企业产业风险、融资偏好与融资选择融资偏好;产业风险;融资选择 1
星载激光雷达 星载激光雷达望远镜主镜超轻量化结构设计超轻量化;拓扑优化;集成优化;RMS;有限元仿真 1
```
### 数据集下载
- [literature_search_rank](https://paddlenlp.bj.bcebos.com/applications/literature_search_rank.zip)
```
├── data # 排序数据集
├── test.csv # 测试集
├── dev_pairwise.csv # 验证集
└── train.csv # 训练集
```
<a name="模型训练"></a>
## 5. 模型训练
**排序模型下载链接:**
|Model|训练参数配置|硬件|MD5|
| ------------ | ------------ | ------------ |-----------|
|[ERNIE-Gram-Sort](https://bj.bcebos.com/v1/paddlenlp/models/ernie_gram_sort.zip)|<div style="width: 150pt">epoch:3 lr:5E-5 bs:64 max_len:64 </div>|<div style="width: 100pt">4卡 v100-16g</div>|d24ece68b7c3626ce6a24baa58dd297d|
### 训练环境说明
- NVIDIA Driver Version: 440.64.00
- Ubuntu 16.04.6 LTS (Docker)
- Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz
### 单机单卡训练/单机多卡训练
这里采用单机多卡方式进行训练,通过如下命令,指定 GPU 0,1,2,3 卡。如果采用单机单卡训练,只需要把`--gpu`参数设置成单卡的卡号即可
训练的命令如下:
```
unset CUDA_VISIBLE_DEVICES
python -u -m paddle.distributed.launch --gpus "0,1,2,3" --log_dir="logs" train_ce.py \
--device gpu \
--train_set data/train.csv \
--test_file data/dev_pairwise.csv \
--save_dir ./checkpoints \
--model_name_or_path rocketqa-base-cross-encoder \
--batch_size 32 \
--save_steps 10000 \
--max_seq_len 384 \
--learning_rate 1E-5 \
--weight_decay 0.01 \
--warmup_proportion 0.0 \
--logging_steps 10 \
--seed 1 \
--epochs 3 \
--eval_step 1000
```
也可以运行bash脚本:
```
sh scripts/train_ce.sh
```
<a name="评估"></a>
## 6. 评估
```
python evaluate.py --model_name_or_path rocketqa-base-cross-encoder \
--init_from_ckpt checkpoints/model_80000/model_state.pdparams \
--test_file data/dev_pairwise.csv
```
也可以运行bash脚本:
```
sh scripts/evaluate_ce.sh
```
成功运行后会输出下面的指标:
```
eval_dev auc:0.829
```
<a name="预测"></a>
## 7. 预测
### 准备预测数据
待预测数据为 tab 分隔的 tsv 文件,每一行为 1 个文本 Pair,和文本pair的语义索引相似度,(该相似度由召回模型算出,仅供参考),部分示例如下:
```
中西方语言与文化的差异 第二语言习得的一大障碍就是文化差异。 0.5160342454910278
中西方语言与文化的差异 跨文化视角下中国文化对外传播路径琐谈跨文化,中国文化,传播,翻译 0.5145505666732788
中西方语言与文化的差异 从中西方民族文化心理的差异看英汉翻译语言,文化,民族文化心理,思维方式,翻译 0.5141439437866211
中西方语言与文化的差异 中英文化差异对翻译的影响中英文化,差异,翻译的影响 0.5138794183731079
中西方语言与文化的差异 浅谈文化与语言习得文化,语言,文化与语言的关系,文化与语言习得意识,跨文化交际 0.5131710171699524
```
### 开始预测
以上述 demo 数据为例,运行如下命令基于我们开源的rocketqa模型开始计算文本 Pair 的语义相似度:
```shell
unset CUDA_VISIBLE_DEVICES
python predict.py \
--device 'gpu' \
--params_path checkpoints/model_80000/model_state.pdparams \
--model_name_or_path rocketqa-base-cross-encoder \
--test_set data/test.csv \
--topk 10 \
--batch_size 128 \
--max_seq_length 384
```
也可以直接执行下面的命令:
```
sh scripts/predict_ce.sh
```
得到下面的输出,分别是query,title和对应的预测概率:
```
{'text_a': '加强科研项目管理有效促进医学科研工作', 'text_b': '高校\\十四五\\规划中学科建设要处理好五对关系\\十四五\\规划,学科建设,科技创新,人才培养', 'pred_prob': 0.7076062}
{'text_a': '加强科研项目管理有效促进医学科研工作', 'text_b': '校企科研合作项目管理模式创新校企科研合作项目,管理模式,问题,创新', 'pred_prob': 0.64633846}
{'text_a': '加强科研项目管理有效促进医学科研工作', 'text_b': '科研项目管理策略科研项目,项目管理,实施,必要性,策略', 'pred_prob': 0.63166416}
{'text_a': '加强科研项目管理有效促进医学科研工作', 'text_b': '高校科研项目经费管理流程优化研究——以z大学为例高校,科研项目经费\\全流程\\管理,流程优化', 'pred_prob': 0.60351866}
{'text_a': '加强科研项目管理有效促进医学科研工作', 'text_b': '关于推进我院科研发展进程的相关问题研究医院科研,主体,环境,信息化', 'pred_prob': 0.5688347}
{'text_a': '加强科研项目管理有效促进医学科研工作', 'text_b': '医学临床科研选题原则和方法医学临床,科学研究,选题', 'pred_prob': 0.55190295}
```
<a name="部署"></a>
## 8. 部署
### 动转静导出
首先把动态图模型转换为静态图:
```
python export_model.py \
--params_path checkpoints/model_80000/model_state.pdparams \
--model_name_or_path rocketqa-base-cross-encoder \
--output_path=./output
```
也可以运行下面的bash脚本:
```
sh scripts/export_model.sh
```
### Paddle Inference
使用PaddleInference
```
python deploy/python/predict.py --model_dir ./output \
--input_file data/test.csv \
--model_name_or_path rocketqa-base-cross-encoder
```
也可以运行下面的bash脚本:
```
sh deploy/python/deploy.sh
```
得到下面的输出,输出的是样本的query,title以及对应的概率:
```
Data: {'query': '加强科研项目管理有效促进医学科研工作', 'title': '科研项目管理策略科研项目,项目管理,实施,必要性,策略'} prob: 0.5479063987731934
Data: {'query': '加强科研项目管理有效促进医学科研工作', 'title': '关于推进我院科研发展进程的相关问题研究医院科研,主体,环境,信息化'} prob: 0.5151925086975098
Data: {'query': '加强科研项目管理有效促进医学科研工作', 'title': '深圳科技计划对高校科研项目资助现状分析与思考基础研究,高校,科技计划,科技创新'} prob: 0.42983829975128174
Data: {'query': '加强科研项目管理有效促进医学科研工作', 'title': '普通高校科研管理模式的优化与创新普通高校,科研,科研管理'} prob: 0.465454638004303
```
### Paddle Serving部署
Paddle Serving 的详细文档请参考 [Pipeline_Design](https://github.com/PaddlePaddle/Serving/blob/v0.7.0/doc/Python_Pipeline/Pipeline_Design_CN.md)和[Serving_Design](https://github.com/PaddlePaddle/Serving/blob/v0.7.0/doc/Serving_Design_CN.md),首先把静态图模型转换成Serving的格式:
```
python export_to_serving.py \
--dirname "output" \
--model_filename "inference.pdmodel" \
--params_filename "inference.pdiparams" \
--server_path "serving_server" \
--client_path "serving_client" \
--fetch_alias_names "predict"
```
参数含义说明
* `dirname`: 需要转换的模型文件存储路径,Program 结构文件和参数文件均保存在此目录。
* `model_filename`: 存储需要转换的模型 Inference Program 结构的文件名称。如果设置为 None ,则使用 `__model__` 作为默认的文件名
* `params_filename`: 存储需要转换的模型所有参数的文件名称。当且仅当所有模型参数被保>存在一个单独的二进制文件中,它才需要被指定。如果模型参数是存储在各自分离的文件中,设置它的值为 None
* `server_path`: 转换后的模型文件和配置文件的存储路径。默认值为 serving_server
* `client_path`: 转换后的客户端配置文件存储路径。默认值为 serving_client
* `fetch_alias_names`: 模型输出的别名设置,比如输入的 input_ids 等,都可以指定成其他名字,默认不指定
* `feed_alias_names`: 模型输入的别名设置,比如输出 pooled_out 等,都可以重新指定成其他模型,默认不指定
也可以运行下面的 bash 脚本:
```
sh scripts/export_to_serving.sh
```
Paddle Serving的部署有两种方式,第一种方式是Pipeline的方式,第二种是C++的方式,下面分别介绍这两种方式的用法:
#### Pipeline方式
修改对应预训练模型的`Tokenizer`:
```
self.tokenizer = AutoTokenizer.from_pretrained('rocketqa-base-cross-encoder')
```
启动 Pipeline Server:
```
python web_service.py
```
启动客户端调用 Server。
首先修改rpc_client.py中需要预测的样本:
```
list_data = [{"query":"加强科研项目管理有效促进医学科研工作","title":"科研项目管理策略科研项目,项目管理,实施,必要性,策略"}]`
```
然后运行:
```
python rpc_client.py
```
模型的输出为:
```
PipelineClient::predict pack_data time:1662354188.422532
PipelineClient::predict before time:1662354188.423034
time to cost :0.016808509826660156 seconds
(1,)
[0.5479064]
```
可以看到客户端发送了1条文本,这条文本的相似的概率值。
#### C++的方式
启动C++的Serving:
```
python -m paddle_serving_server.serve --model serving_server --port 8600 --gpu_id 0 --thread 5 --ir_optim True
```
也可以使用脚本:
```
sh deploy/cpp/start_server.sh
```
Client 可以使用 http 或者 rpc 两种方式,rpc 的方式为:
```
python deploy/cpp/rpc_client.py
```
运行的输出为:
```
I0905 05:38:28.876770 28507 general_model.cpp:490] [client]logid=0,client_cost=158.124ms,server_cost=156.385ms.
time to cost :0.15848731994628906 seconds
[0.54790646]
```
可以看到服务端返回了相似度结果
或者使用 http 的客户端访问模式:
```
python deploy/cpp/http_client.py
```
运行的输出为:
```
time to cost :0.13054680824279785 seconds
0.5479064707850817
```
可以看到服务端返回了相似度结果
## Reference
[1] Xiao, Dongling, Yu-Kun Li, Han Zhang, Yu Sun, Hao Tian, Hua Wu, and Haifeng Wang. “ERNIE-Gram: Pre-Training with Explicitly N-Gram Masked Language Modeling for Natural Language Understanding.” ArXiv:2010.12148 [Cs].
[2] Yingqi Qu, Yuchen Ding, Jing Liu, Kai Liu, Ruiyang Ren, Wayne Xin Zhao, Daxiang Dong, Hua Wu, Haifeng Wang:
RocketQA: An Optimized Training Approach to Dense Passage Retrieval for Open-Domain Question Answering. NAACL-HLT 2021: 5835-5847

View File

@@ -1 +0,0 @@
python -m paddle_serving_server.serve --model serving_server --port 8600 --gpu_id 0 --thread 5 --ir_optim True

View File

@@ -1,3 +0,0 @@
python deploy/python/predict.py --model_dir ./output \
--input_file data/test.csv \
--model_name_or_path rocketqa-base-cross-encoder

View File

@@ -1,34 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import numpy as np
from paddle_serving_server.pipeline import PipelineClient
client = PipelineClient()
client.connect(["127.0.0.1:8089"])
list_data = [{"query": "加强科研项目管理有效促进医学科研工作", "title": "科研项目管理策略科研项目,项目管理,实施,必要性,策略"}]
feed = {}
for i, item in enumerate(list_data):
feed[str(i)] = str(item)
print(feed)
start_time = time.time()
ret = client.predict(feed_dict=feed)
end_time = time.time()
print("time to cost :{} seconds".format(end_time - start_time))
result = np.array(eval(ret.value[0]))
print(result.shape)
print(result)

View File

@@ -1,49 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import paddle_serving_client.io as serving_io
# yapf: disable
parser = argparse.ArgumentParser()
parser.add_argument("--dirname", type=str, required=True,
default='./output', help="Path of saved model files. Program file and parameter files are saved in this directory.")
parser.add_argument("--model_filename", type=str, required=True,
default='inference.pdmodel', help="The name of file to load the inference program. If it is None, the default filename __model__ will be used.")
parser.add_argument("--params_filename", type=str, required=True,
default='inference.pdiparams', help="The name of file to load all parameters. It is only used for the case that all parameters were saved in a single binary file. If parameters were saved in separate files, set it as None. Default: None.")
parser.add_argument("--server_path", type=str, default='./serving_server',
help="The path of server parameter in static graph to be saved.")
parser.add_argument("--client_path", type=str, default='./serving_client',
help="The path of client parameter in static graph to be saved.")
parser.add_argument("--feed_alias_names", type=str, default=None,
help='set alias names for feed vars, split by comma \',\', you should run --show_proto to check the number of feed vars')
parser.add_argument("--fetch_alias_names", type=str, default=None,
help='set alias names for fetch vars, split by comma \',\', you should run --show_proto to check the number of fetch vars')
parser.add_argument("--show_proto", type=bool, default=False,
help='If yes, you can preview the proto and then determine your feed var alias name and fetch var alias name.')
# yapf: enable
if __name__ == "__main__":
args = parser.parse_args()
serving_io.inference_model_to_serving(
dirname=args.dirname,
serving_server=args.server_path,
serving_client=args.client_path,
model_filename=args.model_filename,
params_filename=args.params_filename,
show_proto=args.show_proto,
feed_alias_names=args.feed_alias_names,
fetch_alias_names=args.fetch_alias_names,
)

View File

@@ -1,3 +0,0 @@
python evaluate.py --model_name_or_path rocketqa-base-cross-encoder \
--init_from_ckpt checkpoints/model_80000/model_state.pdparams \
--test_file data/dev_pairwise.csv

View File

@@ -1,4 +0,0 @@
python export_model.py \
--params_path checkpoints/model_80000/model_state.pdparams \
--model_name_or_path rocketqa-base-cross-encoder \
--output_path=./output

View File

@@ -1,7 +0,0 @@
python export_to_serving.py \
--dirname "output" \
--model_filename "inference.pdmodel" \
--params_filename "inference.pdiparams" \
--server_path "serving_server" \
--client_path "serving_client" \
--fetch_alias_names "predict"

View File

@@ -1,11 +0,0 @@
#!/bin/bash
unset CUDA_VISIBLE_DEVICES
export CUDA_VISIBLE_DEVICES=0
python predict.py \
--device 'gpu' \
--params_path checkpoints/model_80000/model_state.pdparams \
--model_name_or_path rocketqa-base-cross-encoder \
--test_set data/test.csv \
--topk 10 \
--batch_size 128 \
--max_seq_length 384

View File

@@ -1,18 +0,0 @@
#!/bin/bash
unset CUDA_VISIBLE_DEVICES
python -u -m paddle.distributed.launch --gpus "0,1,2,3" --log_dir="logs" train_ce.py \
--device gpu \
--train_set data/train.csv \
--test_file data/dev_pairwise.csv \
--save_dir ./checkpoints \
--model_name_or_path rocketqa-base-cross-encoder \
--batch_size 32 \
--save_steps 10000 \
--max_seq_len 384 \
--learning_rate 1E-5 \
--weight_decay 0.01 \
--warmup_proportion 0.0 \
--logging_steps 10 \
--seed 1 \
--epochs 3 \
--eval_step 1000

View File

@@ -1,409 +0,0 @@
**目录**
* [背景介绍](#背景介绍)
* [ERNIE-Gram](#ERNIE-Gram)
* [1. 技术方案和评估指标](#技术方案)
* [2. 环境依赖](#环境依赖)
* [3. 代码结构](#代码结构)
* [4. 数据准备](#数据准备)
* [5. 模型训练](#模型训练)
* [6. 评估](#开始评估)
* [7. 预测](#预测)
* [8. 部署](#部署)
<a name="背景介绍"></a>
# 背景介绍
基于ERNIE-Gram训练Pair-wise模型。Pair-wise 匹配模型适合将文本对相似度作为特征之一输入到上层排序模块进行排序的应用场景。
<a name="ERNIE-Gram"></a>
# ERNIE-Gram
<a name="技术方案"></a>
## 1. 技术方案和评估指标
### 技术方案
双塔模型,使用ERNIE-Gram预训练模型,使用margin_ranking_loss训练模型。
### 评估指标
(1)采用 AUC 指标来评估排序模型的排序效果。
**效果评估**
| 模型 | AUC |
| ------------ | ------------ |
| ERNIE-Gram | 0.801 |
<a name="环境依赖"></a>
## 2. 环境依赖和安装说明
**环境依赖**
* python >= 3.x
* paddlepaddle >= 2.1.3
* paddlenlp >= 2.2
* pandas >= 0.25.1
* scipy >= 1.3.1
<a name="代码结构"></a>
## 3. 代码结构
以下是本项目主要代码结构及说明:
```
ernie_matching/
├── deply # 部署
├── cpp
├── rpc_client.py # RPC 客户端的bash脚本
├── http_client.py # http 客户端的bash文件
└── start_server.sh # 启动C++服务的脚本
└── python
├── deploy.sh # 预测部署bash脚本
├── config_nlp.yml # Pipeline 的配置文件
├── web_service.py # Pipeline 服务端的脚本
├── rpc_client.py # Pipeline RPC客户端的脚本
└── predict.py # python 预测部署示例
|—— scripts
├── export_model.sh # 动态图参数导出静态图参数的bash文件
├── export_to_serving.sh # 导出 Paddle Serving 模型格式的bash文件
├── train_pairwise.sh # Pair-wise 单塔匹配模型训练的bash文件
├── evaluate.sh # 评估验证文件bash脚本
├── predict_pairwise.sh # Pair-wise 单塔匹配模型预测脚本的bash文件
├── export_model.py # 动态图参数导出静态图参数脚本
├── export_to_serving.py # 导出 Paddle Serving 模型格式的脚本
├── model.py # Pair-wise 匹配模型组网
├── data.py # Pair-wise 训练样本的转换逻辑 、Pair-wise 生成随机负例的逻辑
├── train_pairwise.py # Pair-wise 单塔匹配模型训练脚本
├── evaluate.py # 评估验证文件
├── predict_pairwise.py # Pair-wise 单塔匹配模型预测脚本,输出文本对是相似度
```
<a name="数据准备"></a>
## 4. 数据准备
### 数据集说明
样例数据如下:
```
个人所得税税务筹划 基于新个税视角下的个人所得税纳税筹划分析新个税;个人所得税;纳税筹划 个人所得税工资薪金税务筹划研究个人所得税,工资薪金,税务筹划
液压支架底座受力分析 ZY4000/09/19D型液压支架的有限元分析液压支架,有限元分析,两端加载,偏载,扭转 基于ANSYS的液压支架多工况受力分析液压支架,四种工况,仿真分析,ANSYS,应力集中,优化
迟发性血管痉挛 西洛他唑治疗动脉瘤性蛛网膜下腔出血后脑血管痉挛的Meta分析西洛他唑,蛛网膜下腔出血,脑血管痉挛,Meta分析 西洛他唑治疗动脉瘤性蛛网膜下腔出血后脑血管痉挛的Meta分析西洛他唑,蛛网膜下腔出血,脑血管痉挛,Meta分析
氧化亚硅 复合溶胶-凝胶一锅法制备锂离子电池氧化亚硅/碳复合负极材料氧化亚硅,溶胶-凝胶法,纳米颗粒,负极,锂离子电池 负载型聚酰亚胺-二氧化硅-银杂化膜的制备和表征聚酰亚胺,二氧化硅,银,杂化膜,促进传输
```
### 数据集下载
- [literature_search_data](https://bj.bcebos.com/v1/paddlenlp/data/literature_search_data.zip)
```
├── milvus # milvus建库数据集
├── milvus_data.csv. # 构建召回库的数据
├── recall # 召回(语义索引)数据集
├── corpus.csv # 用于测试的召回库
├── dev.csv # 召回验证集
├── test.csv # 召回测试集
├── train.csv # 召回训练集
├── train_unsupervised.csv # 无监督训练集
├── sort # 排序数据集
├── test_pairwise.csv # 排序测试集
├── dev_pairwise.csv # 排序验证集
└── train_pairwise.csv # 排序训练集
```
<a name="模型训练"></a>
## 5. 模型训练
**排序模型下载链接:**
|Model|训练参数配置|硬件|MD5|
| ------------ | ------------ | ------------ |-----------|
|[ERNIE-Gram-Sort](https://bj.bcebos.com/v1/paddlenlp/models/ernie_gram_sort.zip)|<div style="width: 150pt">epoch:3 lr:5E-5 bs:64 max_len:64 </div>|<div style="width: 100pt">4卡 v100-16g</div>|d24ece68b7c3626ce6a24baa58dd297d|
### 训练环境说明
- NVIDIA Driver Version: 440.64.00
- Ubuntu 16.04.6 LTS (Docker)
- Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz
### 单机单卡训练/单机多卡训练
这里采用单机多卡方式进行训练,通过如下命令,指定 GPU 0,1,2,3 卡, 基于ERNIE-Gram训练模型,数据量比较大,需要20小时10分钟左右。如果采用单机单卡训练,只需要把`--gpu`参数设置成单卡的卡号即可
训练的命令如下:
```
python -u -m paddle.distributed.launch --gpus "0,1,2,3" train_pairwise.py \
--device gpu \
--save_dir ./checkpoints \
--batch_size 32 \
--learning_rate 2E-5 \
--margin 0.1 \
--eval_step 100 \
--train_file data/train_pairwise.csv \
--test_file data/dev_pairwise.csv
```
也可以运行bash脚本:
```
sh scripts/train_pairwise.sh
```
<a name="评估"></a>
## 6. 评估
```
unset CUDA_VISIBLE_DEVICES
python -u -m paddle.distributed.launch --gpus "0" evaluate.py \
--device gpu \
--batch_size 32 \
--learning_rate 2E-5 \
--init_from_ckpt "./checkpoints/model_30000/model_state.pdparams" \
--test_file data/dev_pairwise.csv
```
也可以运行bash脚本:
```
sh scripts/evaluate.sh
```
成功运行后会输出下面的指标:
```
eval_dev auc:0.796
```
<a name="预测"></a>
## 7. 预测
### 准备预测数据
待预测数据为 tab 分隔的 tsv 文件,每一行为 1 个文本 Pair,和文本pair的语义索引相似度,部分示例如下:
```
中西方语言与文化的差异 第二语言习得的一大障碍就是文化差异。 0.5160342454910278
中西方语言与文化的差异 跨文化视角下中国文化对外传播路径琐谈跨文化,中国文化,传播,翻译 0.5145505666732788
中西方语言与文化的差异 从中西方民族文化心理的差异看英汉翻译语言,文化,民族文化心理,思维方式,翻译 0.5141439437866211
中西方语言与文化的差异 中英文化差异对翻译的影响中英文化,差异,翻译的影响 0.5138794183731079
中西方语言与文化的差异 浅谈文化与语言习得文化,语言,文化与语言的关系,文化与语言习得意识,跨文化交际 0.5131710171699524
```
### 开始预测
以上述 demo 数据为例,运行如下命令基于我们开源的 ERNIE-Gram模型开始计算文本 Pair 的语义相似度:
```shell
python -u -m paddle.distributed.launch --gpus "0" \
predict_pairwise.py \
--device gpu \
--params_path "./checkpoints/model_30000/model_state.pdparams"\
--batch_size 128 \
--max_seq_length 64 \
--input_file 'sort/test_pairwise.csv'
```
也可以直接执行下面的命令:
```
sh scripts/predict_pairwise.sh
```
得到下面的输出,分别是query,title和对应的预测概率:
```
{'query': '中西方语言与文化的差异', 'title': '第二语言习得的一大障碍就是文化差异。', 'pred_prob': 0.85112214}
{'query': '中西方语言与文化的差异', 'title': '跨文化视角下中国文化对外传播路径琐谈跨文化,中国文化,传播,翻译', 'pred_prob': 0.78629625}
{'query': '中西方语言与文化的差异', 'title': '从中西方民族文化心理的差异看英汉翻译语言,文化,民族文化心理,思维方式,翻译', 'pred_prob': 0.91767526}
{'query': '中西方语言与文化的差异', 'title': '中英文化差异对翻译的影响中英文化,差异,翻译的影响', 'pred_prob': 0.8601749}
{'query': '中西方语言与文化的差异', 'title': '浅谈文化与语言习得文化,语言,文化与语言的关系,文化与语言习得意识,跨文化交际', 'pred_prob': 0.8944413}
```
<a name="部署"></a>
## 8. 部署
### 动转静导出
首先把动态图模型转换为静态图:
```
python export_model.py --params_path checkpoints/model_30000/model_state.pdparams \
--output_path=./output \
--model_name_or_path ernie-3.0-medium-zh
```
也可以运行下面的bash脚本:
```
sh scripts/export_model.sh
```
### Paddle Inference
使用PaddleInference:
```
python deploy/python/predict.py --model_dir ./output \
--input_file sort/test_pairwise.csv \
--model_name_or_path ernie-3.0-medium-zh
```
也可以运行下面的bash脚本:
```
sh deploy/python/deploy.sh
```
得到下面的输出,输出的是样本的query,title以及对应的概率:
```
Data: {'query': '中西方语言与文化的差异', 'title': '第二语言习得的一大障碍就是文化差异。'} prob: [0.8511221]
Data: {'query': '中西方语言与文化的差异', 'title': '跨文化视角下中国文化对外传播路径琐谈跨文化,中国文化,传播,翻译'} prob: [0.7862964]
Data: {'query': '中西方语言与文化的差异', 'title': '从中西方民族文化心理的差异看英汉翻译语言,文化,民族文化心理,思维方式,翻译'} prob: [0.91767514]
Data: {'query': '中西方语言与文化的差异', 'title': '中英文化差异对翻译的影响中英文化,差异,翻译的影响'} prob: [0.8601747]
Data: {'query': '中西方语言与文化的差异', 'title': '浅谈文化与语言习得文化,语言,文化与语言的关系,文化与语言习得意识,跨文化交际'} prob: [0.8944413]
```
### Paddle Serving部署
Paddle Serving 的详细文档请参考 [Pipeline_Design](https://github.com/PaddlePaddle/Serving/blob/v0.7.0/doc/Python_Pipeline/Pipeline_Design_CN.md)和[Serving_Design](https://github.com/PaddlePaddle/Serving/blob/v0.7.0/doc/Serving_Design_CN.md),首先把静态图模型转换成Serving的格式:
```
python export_to_serving.py \
--dirname "output" \
--model_filename "inference.predict.pdmodel" \
--params_filename "inference.predict.pdiparams" \
--server_path "serving_server" \
--client_path "serving_client" \
--fetch_alias_names "predict"
```
参数含义说明
* `dirname`: 需要转换的模型文件存储路径,Program 结构文件和参数文件均保存在此目录。
* `model_filename`: 存储需要转换的模型 Inference Program 结构的文件名称。如果设置为 None ,则使用 `__model__` 作为默认的文件名
* `params_filename`: 存储需要转换的模型所有参数的文件名称。当且仅当所有模型参数被保>存在一个单独的二进制文件中,它才需要被指定。如果模型参数是存储在各自分离的文件中,设置它的值为 None
* `server_path`: 转换后的模型文件和配置文件的存储路径。默认值为 serving_server
* `client_path`: 转换后的客户端配置文件存储路径。默认值为 serving_client
* `fetch_alias_names`: 模型输出的别名设置,比如输入的 input_ids 等,都可以指定成其他名字,默认不指定
* `feed_alias_names`: 模型输入的别名设置,比如输出 pooled_out 等,都可以重新指定成其他模型,默认不指定
也可以运行下面的 bash 脚本:
```
sh scripts/export_to_serving.sh
```
Paddle Serving的部署有两种方式,第一种方式是Pipeline的方式,第二种是C++的方式,下面分别介绍这两种方式的用法:
#### Pipeline方式
修改`Tokenizer`
```
self.tokenizer = AutoTokenizer.from_pretrained('ernie-3.0-medium-zh')
```
启动 Pipeline Server:
```
python web_service.py
```
启动客户端调用 Server。
首先修改rpc_client.py中需要预测的样本:
```
list_data = [{"query":"中西方语言与文化的差异","title":"第二语言习得的一大障碍就是文化差异。"}]`
```
然后运行:
```
python rpc_client.py
```
模型的输出为:
```
PipelineClient::predict pack_data time:1656912047.5986433
PipelineClient::predict before time:1656912047.599081
time to cost :0.012039899826049805 seconds
(1, 1)
[[0.85112208]]
```
可以看到客户端发送了1条文本,这条文本的相似的概率值。
#### C++的方式
启动C++的Serving:
```
python -m paddle_serving_server.serve --model serving_server --port 8600 --gpu_id 0 --thread 5 --ir_optim True
```
也可以使用脚本:
```
sh deploy/cpp/start_server.sh
```
Client 可以使用 http 或者 rpc 两种方式,rpc 的方式为:
```
python deploy/cpp/rpc_client.py
```
运行的输出为:
```
I0704 05:19:00.443437 1987 general_model.cpp:490] [client]logid=0,client_cost=8.477ms,server_cost=6.458ms.
time to cost :0.008707761764526367 seconds
{'predict': array([[0.8511221]], dtype=float32)}
```
可以看到服务端返回了相似度结果
或者使用 http 的客户端访问模式:
```
python deploy/cpp/http_client.py
```
运行的输出为:
```
time to cost :0.006819009780883789 seconds
[0.8511220812797546]
```
可以看到服务端返回了相似度结果
也可以使用curl方式发送Http请求:
```
curl -XPOST http://0.0.0.0:8600/GeneralModelService/inference -d ' {"tensor":[{"int64_data":[ 1, 12, 213, 58, 405, 545, 54, 68, 73,
5, 859, 712, 2, 131, 177, 405, 545, 489,
116, 5, 7, 19, 843, 1767, 113, 10, 68,
73, 859, 712, 12043, 2],"elem_type":0,"name":"input_ids","alias_name":"input_ids","shape":[1,32]},
{"int64_data":[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1],"elem_type":0,"name":"token_type_ids","alias_name":"token_type_ids","shape":[1,32]}
],
"fetch_var_names":["sigmoid_2.tmp_0"],
"log_id":0
}'
```
## Reference
[1] Xiao, Dongling, Yu-Kun Li, Han Zhang, Yu Sun, Hao Tian, Hua Wu, and Haifeng Wang. “ERNIE-Gram: Pre-Training with Explicitly N-Gram Masked Language Modeling for Natural Language Understanding.” ArXiv:2010.12148 [Cs].

View File

@@ -1,130 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import paddle
import numpy as np
from paddlenlp.datasets import MapDataset
def create_dataloader(dataset, mode="train", batch_size=1, batchify_fn=None, trans_fn=None):
if trans_fn:
dataset = dataset.map(trans_fn)
shuffle = True if mode == "train" else False
if mode == "train":
batch_sampler = paddle.io.DistributedBatchSampler(dataset, batch_size=batch_size, shuffle=shuffle)
else:
batch_sampler = paddle.io.BatchSampler(dataset, batch_size=batch_size, shuffle=shuffle)
return paddle.io.DataLoader(dataset=dataset, batch_sampler=batch_sampler, collate_fn=batchify_fn, return_list=True)
def read_text_pair(data_path):
"""Reads data."""
with open(data_path, "r", encoding="utf-8") as f:
for line in f:
data = line.rstrip().split("\t")
if len(data) != 3:
continue
yield {"query": data[0], "title": data[1]}
def convert_pointwise_example(example, tokenizer, max_seq_length=512, is_test=False):
query, title = example["query"], example["title"]
encoded_inputs = tokenizer(text=query, text_pair=title, max_seq_len=max_seq_length)
input_ids = encoded_inputs["input_ids"]
token_type_ids = encoded_inputs["token_type_ids"]
if not is_test:
label = np.array([example["label"]], dtype="int64")
return input_ids, token_type_ids, label
else:
return input_ids, token_type_ids
def convert_pairwise_example(example, tokenizer, max_seq_length=512, phase="train"):
if phase == "train":
query, pos_title, neg_title = example["query"], example["title"], example["neg_title"]
pos_inputs = tokenizer(text=query, text_pair=pos_title, max_seq_len=max_seq_length)
neg_inputs = tokenizer(text=query, text_pair=neg_title, max_seq_len=max_seq_length)
pos_input_ids = pos_inputs["input_ids"]
pos_token_type_ids = pos_inputs["token_type_ids"]
neg_input_ids = neg_inputs["input_ids"]
neg_token_type_ids = neg_inputs["token_type_ids"]
return (pos_input_ids, pos_token_type_ids, neg_input_ids, neg_token_type_ids)
else:
query, title = example["query"], example["title"]
inputs = tokenizer(text=query, text_pair=title, max_seq_len=max_seq_length)
input_ids = inputs["input_ids"]
token_type_ids = inputs["token_type_ids"]
if phase == "eval":
return input_ids, token_type_ids, example["label"]
elif phase == "predict":
return input_ids, token_type_ids
else:
raise ValueError("not supported phase:{}".format(phase))
def gen_pair(dataset, pool_size=100):
"""
Generate triplet randomly based on dataset
Args:
dataset: A `MapDataset` or `IterDataset` or a tuple of those.
Each example is composed of 2 texts: example["query"], example["title"]
pool_size: the number of example to sample negative example randomly
Return:
dataset: A `MapDataset` or `IterDataset` or a tuple of those.
Each example is composed of 3 texts: example["query"], example["pos_title"]、example["neg_title"]
"""
if len(dataset) < pool_size:
pool_size = len(dataset)
new_examples = []
pool = []
tmp_examples = []
for example in dataset:
label = example["label"]
# Filter negative example
if label == 0:
continue
tmp_examples.append(example)
pool.append(example["title"])
if len(pool) >= pool_size:
np.random.shuffle(pool)
for idx, example in enumerate(tmp_examples):
example["neg_title"] = pool[idx]
new_examples.append(example)
tmp_examples = []
pool = []
else:
continue
return MapDataset(new_examples)

View File

@@ -1 +0,0 @@
python -m paddle_serving_server.serve --model serving_server --port 8600 --gpu_id 0 --thread 5 --ir_optim True

View File

@@ -1,3 +0,0 @@
python deploy/python/predict.py --model_dir ./output \
--input_file sort/test_pairwise.csv \
--model_name_or_path ernie-3.0-medium-zh

View File

@@ -1,34 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import numpy as np
from paddle_serving_server.pipeline import PipelineClient
client = PipelineClient()
client.connect(["127.0.0.1:8089"])
list_data = [{"query": "中西方语言与文化的差异", "title": "第二语言习得的一大障碍就是文化差异。"}]
feed = {}
for i, item in enumerate(list_data):
feed[str(i)] = str(item)
print(feed)
start_time = time.time()
ret = client.predict(feed_dict=feed)
end_time = time.time()
print("time to cost :{} seconds".format(end_time - start_time))
result = np.array(eval(ret.value[0]))
print(result.shape)
print(result)

View File

@@ -1,49 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import paddle_serving_client.io as serving_io
# yapf: disable
parser = argparse.ArgumentParser()
parser.add_argument("--dirname", type=str, required=True,
default='./output', help="Path of saved model files. Program file and parameter files are saved in this directory.")
parser.add_argument("--model_filename", type=str, required=True,
default='inference.get_pooled_embedding.pdmodel', help="The name of file to load the inference program. If it is None, the default filename __model__ will be used.")
parser.add_argument("--params_filename", type=str, required=True,
default='inference.get_pooled_embedding.pdiparams', help="The name of file to load all parameters. It is only used for the case that all parameters were saved in a single binary file. If parameters were saved in separate files, set it as None. Default: None.")
parser.add_argument("--server_path", type=str, default='./serving_server',
help="The path of server parameter in static graph to be saved.")
parser.add_argument("--client_path", type=str, default='./serving_client',
help="The path of client parameter in static graph to be saved.")
parser.add_argument("--feed_alias_names", type=str, default=None,
help='set alias names for feed vars, split by comma \',\', you should run --show_proto to check the number of feed vars')
parser.add_argument("--fetch_alias_names", type=str, default=None,
help='set alias names for feed vars, split by comma \',\', you should run --show_proto to check the number of fetch vars')
parser.add_argument("--show_proto", type=bool, default=False,
help='If yes, you can preview the proto and then determine your feed var alias name and fetch var alias name.')
# yapf: enable
if __name__ == "__main__":
args = parser.parse_args()
serving_io.inference_model_to_serving(
dirname=args.dirname,
serving_server=args.server_path,
serving_client=args.client_path,
model_filename=args.model_filename,
params_filename=args.params_filename,
show_proto=args.show_proto,
feed_alias_names=args.feed_alias_names,
fetch_alias_names=args.fetch_alias_names,
)

View File

@@ -1,16 +0,0 @@
unset CUDA_VISIBLE_DEVICES
# gpu
python -u -m paddle.distributed.launch --gpus "0" evaluate.py \
--device gpu \
--batch_size 32 \
--learning_rate 2E-5 \
--init_from_ckpt "./checkpoints/model_30000/model_state.pdparams" \
--test_file sort/dev_pairwise.csv
# cpu
# python evaluate.py \
# --device cpu \
# --batch_size 32 \
# --learning_rate 2E-5 \
# --init_from_ckpt "./checkpoints/model_30000/model_state.pdparams" \
# --test_file sort/dev_pairwise.csv

View File

@@ -1,3 +0,0 @@
python export_model.py --params_path checkpoints/model_30000/model_state.pdparams \
--output_path=./output \
--model_name_or_path ernie-3.0-medium-zh

View File

@@ -1,7 +0,0 @@
python export_to_serving.py \
--dirname "output" \
--model_filename "inference.predict.pdmodel" \
--params_filename "inference.predict.pdiparams" \
--server_path "serving_server" \
--client_path "serving_client" \
--fetch_alias_names "predict"

View File

@@ -1,15 +0,0 @@
# gpu
python -u -m paddle.distributed.launch --gpus "0" \
predict_pairwise.py \
--device gpu \
--params_path "./checkpoints/model_30000/model_state.pdparams"\
--batch_size 128 \
--max_seq_length 64 \
--input_file 'sort/test_pairwise.csv'
# cpu
# python predict_pairwise.py \
# --device gpu \
# --params_path "./checkpoints/model_30000/model_state.pdparams"\
# --batch_size 128 \
# --max_seq_length 64 \
# --input_file 'sort/test_pairwise.csv'

View File

@@ -1,21 +0,0 @@
# gpu
python -u -m paddle.distributed.launch --gpus="0,1,2,3" train_pairwise.py \
--device gpu \
--save_dir ./checkpoints \
--batch_size 32 \
--learning_rate 2E-5 \
--margin 0.1 \
--eval_step 100 \
--train_file sort/train_pairwise.csv \
--test_file sort/dev_pairwise.csv
# cpu
# python train_pairwise.py \
# --device cpu \
# --save_dir ./checkpoints \
# --batch_size 32 \
# --learning_rate 2E-5 \
# --margin 0.1 \
# --eval_step 100 \
# --train_file sort/train_pairwise.csv \
# --test_file sort/dev_pairwise.csv

View File

@@ -1,635 +0,0 @@
# In-batch Negatives
**目录**
* [背景介绍](#背景介绍)
* [In-batch Negatives](#In-batchNegatives)
* [1. 技术方案和评估指标](#技术方案)
* [2. 环境依赖](#环境依赖)
* [3. 代码结构](#代码结构)
* [4. 数据准备](#数据准备)
* [5. 模型训练](#模型训练)
* [6. 评估](#开始评估)
* [7. 预测](#预测)
* [8. 部署](#部署)
<a name="背景介绍"></a>
# 背景介绍
语义索引(可通俗理解为向量索引)技术是搜索引擎、推荐系统、广告系统在召回阶段的核心技术之一。语义索引模型的目标是:给定输入文本,模型可以从海量候选召回库中**快速、准确**地召回一批语义相关文本。语义索引模型的效果直接决定了语义相关的物料能否被成功召回进入系统参与上层排序,从基础层面影响整个系统的效果。
在召回阶段,最常见的方式是通过双塔模型,学习Document(简写为Doc)的向量表示,对Doc端建立索引,用ANN召回。我们在这种方式的基础上,引入语义索引策略 [In-batch Negatives](https://arxiv.org/abs/2004.04906),以如下Batch size=4的训练数据为例:
```
我手机丢了,我想换个手机 我想买个新手机,求推荐
求秋色之空漫画全集 求秋色之空全集漫画
学日语软件手机上的 手机学日语的软件
侠盗飞车罪恶都市怎样改车 侠盗飞车罪恶都市怎么改车
```
In-batch Negatives 策略的训练数据为语义相似的 Pair 对,策略核心是在 1 个 Batch 内同时基于 N 个负例进行梯度更新,将Batch 内除自身之外其它所有 Source Text 的相似文本 Target Text 作为负例,例如: 上例中“我手机丢了,我想换个手机” 有 1 个正例(”我想买个新手机,求推荐“),3 个负例(1.求秋色之空全集漫画,2.手机学日语的软件,3.侠盗飞车罪恶都市怎么改车)。
<a name="In-batch Negatives"></a>
# In-batch Negatives
<a name="技术方案"></a>
## 1. 技术方案和评估指标
### 技术方案
双塔模型,在召回训练阶段引入In-batch Negatives 策略,使用hnswlib建立索引库,进行召回测试。
### 评估指标
采用 Recall@1,Recall@5 ,Recall@10 ,Recall@20 和 Recall@50 指标来评估语义索引模型的召回效果。
Recall@K召回率是指预测的前topK(top-k是指从最后的按得分排序的召回列表中返回前k个结果)结果中检索出的相关结果数和库中所有的相关结果数的比率,衡量的是检索系统的查全率。
**效果评估**
| 策略 | 模型 | Recall@1 | Recall@5 |Recall@10 |Recall@20 |Recall@50 |
| ------------ | ------------ | ------------ |--------- |--------- |--------- |--------- |
| In-batch Negatives | ernie 1.0 | 51.301 | 65.309| 69.878| 73.996|78.881|
| In-batch Negatives | rocketqa-zh-base-query-encoder | **59.622** | **75.089**| **79.668**| **83.404**|**87.773**|
<a name="环境依赖"></a>
## 2. 环境依赖
推荐使用GPU进行训练,在预测阶段使用CPU或者GPU均可。
**环境依赖**
* python >= 3.6.2
* paddlepaddle >= 2.2.3
* paddlenlp >= 2.2
* [hnswlib](https://github.com/nmslib/hnswlib) >= 0.5.2
* visualdl >= 2.2.2
<a name="代码结构"></a>
## 3. 代码结构
```
|—— data.py # 数据读取、数据转换等预处理逻辑
|—— base_model.py # 语义索引模型基类
|—— train_batch_neg.py # In-batch Negatives 策略的训练主脚本
|—— batch_negative
|—— model.py # In-batch Negatives 策略核心网络结构
|—— ann_util.py # Ann 建索引库相关函数
|—— recall.py # 基于训练好的语义索引模型,从召回库中召回给定文本的相似文本
|—— evaluate.py # 根据召回结果和评估集计算评估指标
|—— predict.py # 给定输入文件,计算文本 pair 的相似度
|—— export_model.py # 动态图转换成静态图
|—— scripts
|—— export_model.sh # 动态图转换成静态图脚本
|—— predict.sh # 预测 bash 版本
|—— evaluate.sh # 评估 bash 版本
|—— run_build_index.sh # 构建索引 bash 版本
|—— train_batch_neg.sh # 训练 bash 版本
|—— export_to_serving.sh # Paddle Inference 转 Serving 的 bash 脚本
|—— deploy
|—— python
|—— predict.py # PaddleInference
|—— deploy.sh # Paddle Inference 部署脚本
|—— rpc_client.py # Paddle Serving 的 Client 端
|—— web_service.py # Paddle Serving 的 Serving 端
|—— config_nlp.yml # Paddle Serving 的配置文件
|—— inference.py # 动态图抽取向量
|—— export_to_serving.py # 静态图转 Serving
```
<a name="数据准备"></a>
## 4. 数据准备
### 数据集说明
我们基于某文献检索平台数据,构造面向语义索引的训练集、测试集、召回库。
**训练集** 和 **验证集** 格式一致,训练集4k条,测试集2w条,每行由一对语义相似的文本Pair构成,以tab符分割,第一列是检索query,第二列由相关文献标题(+关键词)构成。样例数据如下:
```
宁夏社区图书馆服务体系布局现状分析 宁夏社区图书馆服务体系布局现状分析社区图书馆,社区图书馆服务,社区图书馆服务体系
人口老龄化对京津冀经济 京津冀人口老龄化对区域经济增长的影响京津冀,人口老龄化,区域经济增长,固定效应模型
英语广告中的模糊语 模糊语在英语广告中的应用及其功能模糊语,英语广告,表现形式,语用功能
甘氨酸二肽的合成 甘氨酸二肽合成中缩合剂的选择甘氨酸,缩合剂,二肽
```
**召回库** 用于模拟业务线上的全量语料库,评估模型的召回效果,计算相应的Recall指标。召回库总共30万条样本,每行由一列构成,文献标题(+关键词),样例数据如下:
```
陕西省贫困地区城乡青春期少女生长发育调查青春期,生长发育,贫困地区
五丈岩水库溢洪道加固工程中的新材料应用碳纤维布,粘钢加固技术,超细水泥,灌浆技术
木塑复合材料在儿童卫浴家具中的应用探索木塑复合材料,儿童,卫浴家具
泡沫铝准静态轴向压缩有限元仿真泡沫铝,准静态,轴向压缩,力学特性
```
### 数据集下载
- [literature_search_data](https://bj.bcebos.com/v1/paddlenlp/data/literature_search_data.zip)
```
├── milvus # milvus建库数据集
├── milvus_data.csv. # 构建召回库的数据
├── recall # 召回(语义索引)数据集
├── corpus.csv # 用于测试的召回库
├── dev.csv # 召回验证集
├── test.csv # 召回测试集
├── train.csv # 召回训练集
├── train_unsupervised.csv # 无监督训练集
├── sort # 排序数据集
├── test_pairwise.csv # 排序测试集
├── dev_pairwise.csv # 排序验证集
└── train_pairwise.csv # 排序训练集
```
<a name="模型训练"></a>
## 5. 模型训练
**语义索引训练模型下载链接:**
以下模型结构参数为: `TrasformerLayer:12, Hidden:768, Heads:12, OutputEmbSize: 256`
|Model|训练参数配置|硬件|MD5|
| ------------ | ------------ | ------------ |-----------|
|[batch_neg](https://bj.bcebos.com/v1/paddlenlp/models/inbatch_model.zip)|<div style="width: 150pt">ernie 1.0 margin:0.2 scale:30 epoch:3 lr:5E-5 bs:64 max_len:64 </div>|<div style="width: 100pt">4卡 v100-16g</div>|f3e5c7d7b0b718c2530c5e1b136b2d74|
### 训练环境说明
- NVIDIA Driver Version: 440.64.00
- Ubuntu 16.04.6 LTS (Docker)
- Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz
### 单机单卡训练/单机多卡训练
这里采用单机多卡方式进行训练,通过如下命令,指定 GPU 0,1,2,3 卡, 基于 In-batch Negatives 策略训练模型,数据量比较小,几分钟就可以完成。如果采用单机单卡训练,只需要把`--gpus`参数设置成单卡的卡号即可。
如果使用CPU进行训练,则需要吧`--gpus`参数去除,然后吧`device`设置成cpu即可,详细请参考train_batch_neg.sh文件的训练设置
然后运行下面的命令使用GPU训练,得到语义索引模型:
```
root_path=inbatch
python -u -m paddle.distributed.launch --gpus "0,1,2,3" \
train_batch_neg.py \
--device gpu \
--save_dir ./checkpoints/${root_path} \
--batch_size 64 \
--learning_rate 5E-5 \
--epochs 3 \
--output_emb_size 256 \
--model_name_or_path rocketqa-zh-base-query-encoder \
--save_steps 10 \
--max_seq_length 64 \
--margin 0.2 \
--train_set_file recall/train.csv \
--recall_result_dir "recall_result_dir" \
--recall_result_file "recall_result.txt" \
--hnsw_m 100 \
--hnsw_ef 100 \
--recall_num 50 \
--similar_text_pair_file "recall/dev.csv" \
--corpus_file "recall/corpus.csv"
```
参数含义说明
* `device`: 使用 cpu/gpu 进行训练
* `save_dir`: 模型存储路径
* `batch_size`: 训练的batch size的大小
* `learning_rate`: 训练的学习率的大小
* `epochs`: 训练的epoch数
* `output_emb_size`: Transformer 顶层输出的文本向量维度
* `model_name_or_path`: 预训练模型,用于模型和`Tokenizer`的参数初始化
* `save_steps`: 模型存储 checkpoint 的间隔 steps 个数
* `max_seq_length`: 输入序列的最大长度
* `margin`: 正样本相似度与负样本之间的目标 Gap
* `train_set_file`: 训练集文件
* `evaluate`: 是否开启边训练边评估模型训练效果,默认开启
* `recall_result_dir`: 召回结果存储目录
* `recall_result_file`: 召回结果的文件名
* `hnsw_m`: hnsw 算法相关参数,保持默认即可
* `hnsw_ef`: hnsw 算法相关参数,保持默认即可
* `recall_num`: 对 1 个文本召回的相似文本数量
* `similar_text_pair_file`: 由相似文本对构成的评估集
* `corpus_file`: 召回库数据 corpus_file
* `use_recompute`: 使用Recompute策略,用于节省显存,是一种以时间换空间的技术
* `use_gradient_cache`: 使用Gradient Cache策略,用于节省显存,是一种以时间换空间的技术
* `chunk_numbers`: 使用Gradient Cache策略的参数,表示的是同一个批次的样本分几次执行
也可以使用bash脚本:
```
sh scripts/train.sh
```
<a name="评估"></a>
## 6. 评估
效果评估分为 4 个步骤:
a. 获取Doc端Embedding
基于语义索引模型抽取出Doc样本库的文本向量。
b. 采用hnswlib对Doc端Embedding建库
使用 ANN 引擎构建索引库(这里基于 [hnswlib](https://github.com/nmslib/hnswlib) 进行 ANN 索引)
c. 获取Query的Embedding并查询相似结果
基于语义索引模型抽取出评估集 *Source Text* 的文本向量,在第 2 步中建立的索引库中进行 ANN 查询,召回 Top50 最相似的 *Target Text*, 产出评估集中 *Source Text* 的召回结果 `recall_result` 文件。
d. 评估
基于评估集 `dev.csv` 和召回结果 `recall_result` 计算评估指标 Recall@k,其中k取值1,5,10,20,50。
运行如下命令进行 ANN 建库、召回,产出召回结果数据 `recall_result`
```
root_dir="checkpoints/inbatch"
python -u -m paddle.distributed.launch --gpus "3" --log_dir "recall_log/" \
recall.py \
--device gpu \
--recall_result_dir "recall_result_dir" \
--recall_result_file "recall_result.txt" \
--params_path "${root_dir}/model_40/model_state.pdparams" \
--model_name_or_path rocketqa-zh-base-query-encoder \
--hnsw_m 100 \
--hnsw_ef 100 \
--batch_size 64 \
--output_emb_size 256\
--max_seq_length 60 \
--recall_num 50 \
--similar_text_pair "recall/dev.csv" \
--corpus_file "recall/corpus.csv"
```
参数含义说明
* `device`: 使用 cpu/gpu 进行训练
* `recall_result_dir`: 召回结果存储目录
* `recall_result_file`: 召回结果的文件名
* `params_path`: 待评估模型的参数文件名
* `model_name_or_path`: 预训练模型,用于模型和`Tokenizer`的参数初始化
* `hnsw_m`: hnsw 算法相关参数,保持默认即可
* `hnsw_ef`: hnsw 算法相关参数,保持默认即可
* `output_emb_size`: Transformer 顶层输出的文本向量维度
* `recall_num`: 对 1 个文本召回的相似文本数量
* `similar_text_pair`: 由相似文本对构成的评估集
* `corpus_file`: 召回库数据 corpus_file
也可以使用下面的bash脚本:
```
sh scripts/run_build_index.sh
```
run_build_index.sh还包含cpu和gpu运行的脚本,默认是gpu的脚本
成功运行结束后,会在 `./recall_result_dir/` 目录下产出 `recall_result.txt` 文件
```
热处理对尼龙6 及其与聚酰胺嵌段共聚物共混体系晶体熔融行为和结晶结构的影响 热处理对尼龙6及其与聚酰胺嵌段共聚物共混体系晶体熔融行为和结晶结构的影响尼龙6,聚酰胺嵌段共聚物,芳香聚酰胺,热处理 0.9831992387771606
热处理对尼龙6 及其与聚酰胺嵌段共聚物共混体系晶体熔融行为和结晶结构的影响 热处理方法对高强高模聚乙烯醇纤维性能的影响聚乙烯醇纤维,热处理,性能,热拉伸,热定型 0.8438636660575867
热处理对尼龙6 及其与聚酰胺嵌段共聚物共混体系晶体熔融行为和结晶结构的影响 制备工艺对PVC/ABS合金力学性能和维卡软化温度的影响PVC,ABS,正交试验,力学性能,维卡软化温度 0.8130228519439697
.....
```
接下来,运行如下命令进行效果评估,产出Recall@1, Recall@5, Recall@10, Recall@20 和 Recall@50 指标:
```
python -u evaluate.py \
--similar_text_pair "recall/dev.csv" \
--recall_result_file "./recall_result_dir/recall_result.txt" \
--recall_num 50
```
也可以使用下面的bash脚本:
```
sh scripts/evaluate.sh
```
参数含义说明
* `similar_text_pair`: 由相似文本对构成的评估集 semantic_similar_pair.tsv
* `recall_result_file`: 针对评估集中第一列文本 *Source Text* 的召回结果
* `recall_num`: 对 1 个文本召回的相似文本数量
成功运行结束后,会输出如下评估指标:
```
recall@1=51.261
recall@5=65.279
recall@10=69.848
recall@20=73.971
recall@50=78.84
```
<a name="预测"></a>
## 7. 预测
我们可以基于语义索引模型预测文本的语义向量或者计算文本 Pair 的语义相似度。
### 7.1 功能一:抽取文本的语义向量
修改 inference.py 文件里面输入文本 id2corpus 和模型路径 params_path :
```
params_path='checkpoints/inbatch/model_40/model_state.pdparams'
id2corpus={0:'国有企业引入非国有资本对创新绩效的影响——基于制造业国有上市公司的经验证据'}
```
然后运行:
```
python inference.py
```
预测结果为256维的向量:
```
[1, 256]
[[ 0.07766181 -0.13780491 0.03388524 -0.14910668 -0.0334941 0.06780092
0.0104043 0.03168401 0.02605671 0.02088691 0.05520441 -0.0852212
.....
```
### 7.2 功能二:计算文本 Pair 的语义相似度
### 准备预测数据
待预测数据为 tab 分隔的 csv 文件,每一行为 1 个文本 Pair,部分示例如下:
```
试论我国海岸带经济开发的问题与前景 试论我国海岸带经济开发的问题与前景海岸带,经济开发,问题,前景
外语阅读焦虑与英语成绩及性别的关系 外语阅读焦虑与英语成绩及性别的关系外语阅读焦虑,外语课堂焦虑,英语成绩,性别
数字图书馆 智能化图书馆
网络健康可信性研究 网络成瘾少年
```
### 开始预测
以上述 demo 数据为例,运行如下命令基于我们开源的 [In-batch Negatives](https://arxiv.org/abs/2004.04906) 策略语义索引模型开始计算文本 Pair 的语义相似度:
```
root_dir="checkpoints/inbatch"
python -u -m paddle.distributed.launch --gpus "0" \
predict.py \
--device gpu \
--params_path "${root_dir}/model_40/model_state.pdparams" \
--model_name_or_path rocketqa-zh-base-query-encoder \
--output_emb_size 256 \
--batch_size 128 \
--max_seq_length 64 \
--text_pair_file "recall/test.csv"
```
参数含义说明
* `device`: 使用 cpu/gpu 进行训练
* `params_path`: 预训练模型的参数文件名
* `model_name_or_path`: 预训练模型,用于模型和`Tokenizer`的参数初始化
* `output_emb_size`: Transformer 顶层输出的文本向量维度
* `text_pair_file`: 由文本 Pair 构成的待预测数据集
也可以运行下面的bash脚本:
```
sh scripts/predict.sh
```
predict.sh文件包含了cpu和gpu运行的脚本,默认是gpu运行的脚本
产出如下结果
```
0.9717282652854919
0.9371012449264526
0.7968897223472595
0.30377304553985596
```
<a name="部署"></a>
## 8. 部署
### 动转静导出
首先把动态图模型转换为静态图:
```
python export_model.py --params_path checkpoints/inbatch/model_40/model_state.pdparams \
--model_name_or_path rocketqa-zh-base-query-encoder \
--output_path=./output
```
也可以运行下面的bash脚本:
```
sh scripts/export_model.sh
```
### Paddle Inference预测
预测既可以抽取向量也可以计算两个文本的相似度。
修改id2corpus的样本:
```
# 抽取向量
id2corpus={0:'国有企业引入非国有资本对创新绩效的影响——基于制造业国有上市公司的经验证据'}
# 计算相似度
corpus_list=[['中西方语言与文化的差异','中西方文化差异以及语言体现中西方文化,差异,语言体现'],
['中西方语言与文化的差异','飞桨致力于让深度学习技术的创新与应用更简单']]
```
然后使用PaddleInference
```
python deploy/python/predict.py \
--model_dir=./output \
--model_name_or_path rocketqa-zh-base-query-encoder
```
也可以运行下面的bash脚本:
```
sh deploy.sh
```
最终输出的是256维度的特征向量和句子对的预测概率:
```
(1, 256)
[[-0.0394925 -0.04474756 -0.065534 0.00939134 0.04359895 0.14659195
-0.0091779 -0.07303623 0.09413272 -0.01255222 -0.08685658 0.02762237
0.10138468 0.00962821 0.10888419 0.04553023 0.05898942 0.00694253
....
[0.959269642829895, 0.04725276678800583]
```
### Paddle Serving部署
Paddle Serving 的详细文档请参考 [Pipeline_Design](https://github.com/PaddlePaddle/Serving/blob/v0.7.0/doc/Python_Pipeline/Pipeline_Design_CN.md)和[Serving_Design](https://github.com/PaddlePaddle/Serving/blob/v0.7.0/doc/Serving_Design_CN.md),首先把静态图模型转换成Serving的格式:
```
python export_to_serving.py \
--dirname "output" \
--model_filename "inference.get_pooled_embedding.pdmodel" \
--params_filename "inference.get_pooled_embedding.pdiparams" \
--server_path "./serving_server" \
--client_path "./serving_client" \
--fetch_alias_names "output_embedding"
```
参数含义说明
* `dirname`: 需要转换的模型文件存储路径,Program 结构文件和参数文件均保存在此目录。
* `model_filename`: 存储需要转换的模型 Inference Program 结构的文件名称。如果设置为 None ,则使用 `__model__` 作为默认的文件名
* `params_filename`: 存储需要转换的模型所有参数的文件名称。当且仅当所有模型参数被保>存在一个单独的二进制文件中,它才需要被指定。如果模型参数是存储在各自分离的文件中,设置它的值为 None
* `server_path`: 转换后的模型文件和配置文件的存储路径。默认值为 serving_server
* `client_path`: 转换后的客户端配置文件存储路径。默认值为 serving_client
* `fetch_alias_names`: 模型输出的别名设置,比如输入的 input_ids 等,都可以指定成其他名字,默认不指定
* `feed_alias_names`: 模型输入的别名设置,比如输出 pooled_out 等,都可以重新指定成其他模型,默认不指定
也可以运行下面的 bash 脚本:
```
sh scripts/export_to_serving.sh
```
Paddle Serving的部署有两种方式,第一种方式是Pipeline的方式,第二种是C++的方式,下面分别介绍这两种方式的用法:
#### Pipeline方式
修改模型需要用到的`Tokenizer`
```
self.tokenizer = AutoTokenizer.from_pretrained("rocketqa-zh-base-query-encoder")
```
然后启动 Pipeline Server:
```
cd deploy/python
python web_service.py
```
启动客户端调用 Server。
首先修改rpc_client.py中需要预测的样本:
```
list_data = [
"国有企业引入非国有资本对创新绩效的影响——基于制造业国有上市公司的经验证据",
"试论翻译过程中的文化差异与语言空缺翻译过程,文化差异,语言空缺,文化对比"
]
```
然后运行:
```
python deploy/python/rpc_client.py
```
模型的输出为:
```
{'0': '国有企业引入非国有资本对创新绩效的影响——基于制造业国有上市公司的经验证据', '1': '试论翻译过程中的文化差异与语言空缺翻译过程,文化差异,语言空缺,文化对比'}
PipelineClient::predict pack_data time:1641450851.3752182
PipelineClient::predict before time:1641450851.375738
['output_embedding']
(2, 256)
[[ 0.07830612 -0.14036864 0.03433796 -0.14967982 -0.03386067 0.06630666
0.01357943 0.03531194 0.02411093 0.02000859 0.05724002 -0.08119463
......
```
可以看到客户端发送了2条文本,返回了2个 embedding 向量
#### C++的方式
启动C++的Serving:
```
python -m paddle_serving_server.serve --model serving_server --port 9393 --gpu_id 2 --thread 5 --ir_optim True --use_trt --precision FP16
```
也可以使用脚本:
```
sh deploy/cpp/start_server.sh
```
Client 可以使用 http 或者 rpc 两种方式,rpc 的方式为:
```
python deploy/cpp/rpc_client.py
```
运行的输出为:
```
I0209 20:40:07.978225 20896 general_model.cpp:490] [client]logid=0,client_cost=395.695ms,server_cost=392.559ms.
time to cost :0.3960278034210205 seconds
{'output_embedding': array([[ 9.01343748e-02, -1.21870913e-01, 1.32834800e-02,
-1.57673359e-01, -2.60387752e-02, 6.98455423e-02,
1.58108603e-02, 3.89952064e-02, 3.22783105e-02,
3.49135026e-02, 7.66086206e-02, -9.12970975e-02,
6.25643134e-02, 7.21886680e-02, 7.03565404e-02,
5.44054210e-02, 3.25332815e-03, 5.01751155e-02,
......
```
可以看到服务端返回了向量
或者使用 http 的客户端访问模式:
```
python deploy/cpp/http_client.py
```
运行的输出为:
```
(2, 64)
(2, 64)
outputs {
tensor {
float_data: 0.09013437479734421
float_data: -0.12187091261148453
float_data: 0.01328347995877266
float_data: -0.15767335891723633
......
```
可以看到服务端返回了向量
## FAQ
#### 如何基于无监督SimCSE训练出的模型参数作为参数初始化继续做有监督 In-Batch Negative 训练?
+ 使用 `--init_from_ckpt` 参数加载即可,下面是使用示例:
```
python -u -m paddle.distributed.launch --gpus "0,1,2,3" \
train_batch_neg.py \
--device gpu \
--save_dir ./checkpoints/simcse_inbatch_negative \
--model_name_or_path rocketqa-zh-base-query-encoder \
--batch_size 64 \
--learning_rate 5E-5 \
--epochs 3 \
--output_emb_size 256 \
--save_steps 10 \
--max_seq_length 64 \
--margin 0.2 \
--train_set_file recall/train.csv \
--init_from_ckpt simcse/model_20000/model_state.pdparams
```
## Reference
[1] Vladimir Karpukhin, Barlas Oğuz, Sewon Min, Patrick Lewis, Ledell Wu, Sergey Edunov, Danqi Chen, Wen-tau Yih, Dense Passage Retrieval for Open-Domain Question Answering, Preprint 2020.

View File

@@ -1,57 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# coding=UTF-8
import numpy as np
import hnswlib
from paddlenlp.utils.log import logger
def build_index(args, data_loader, model):
index = hnswlib.Index(space="ip", dim=args.output_emb_size if args.output_emb_size > 0 else 768)
# Initializing index
# max_elements - the maximum number of elements (capacity). Will throw an exception if exceeded
# during insertion of an element.
# The capacity can be increased by saving/loading the index, see below.
#
# ef_construction - controls index search speed/build speed tradeoff
#
# M - is tightly connected with internal dimensionality of the data. Strongly affects memory consumption (~M)
# Higher M leads to higher accuracy/run_time at fixed ef/efConstruction
index.init_index(max_elements=args.hnsw_max_elements, ef_construction=args.hnsw_ef, M=args.hnsw_m)
# Controlling the recall by setting ef:
# higher ef leads to better accuracy, but slower search
index.set_ef(args.hnsw_ef)
# Set number of threads used during batch search/construction
# By default using all available cores
index.set_num_threads(16)
logger.info("start build index..........")
all_embeddings = []
for text_embeddings in model.get_semantic_embedding(data_loader):
all_embeddings.append(text_embeddings.numpy())
all_embeddings = np.concatenate(all_embeddings, axis=0)
index.add_items(all_embeddings)
logger.info("Total index number:{}".format(index.get_current_count()))
return index

View File

@@ -1,109 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import paddle
import paddle.nn.functional as F
from base_model import SemanticIndexBase
class SemanticIndexBatchNeg(SemanticIndexBase):
def __init__(self, pretrained_model, dropout=None, margin=0.3, scale=30, output_emb_size=None):
super().__init__(pretrained_model, dropout, output_emb_size)
self.margin = margin
# Used scaling cosine similarity to ease converge
self.sacle = scale
def forward(
self,
query_input_ids,
title_input_ids,
query_token_type_ids=None,
query_position_ids=None,
query_attention_mask=None,
title_token_type_ids=None,
title_position_ids=None,
title_attention_mask=None,
):
query_cls_embedding = self.get_pooled_embedding(
query_input_ids, query_token_type_ids, query_position_ids, query_attention_mask
)
title_cls_embedding = self.get_pooled_embedding(
title_input_ids, title_token_type_ids, title_position_ids, title_attention_mask
)
cosine_sim = paddle.matmul(query_cls_embedding, title_cls_embedding, transpose_y=True)
# Substract margin from all positive samples cosine_sim()
margin_diag = paddle.full(
shape=[query_cls_embedding.shape[0]], fill_value=self.margin, dtype=paddle.get_default_dtype()
)
cosine_sim = cosine_sim - paddle.diag(margin_diag)
# Scale cosine to ease training converge
cosine_sim *= self.sacle
labels = paddle.arange(0, query_cls_embedding.shape[0], dtype="int64")
labels = paddle.reshape(labels, shape=[-1, 1])
loss = F.cross_entropy(input=cosine_sim, label=labels)
return loss
class SemanticIndexCacheNeg(SemanticIndexBase):
def __init__(self, pretrained_model, dropout=None, margin=0.3, scale=30, output_emb_size=None):
super().__init__(pretrained_model, dropout, output_emb_size)
self.margin = margin
# Used scaling cosine similarity to ease converge
self.sacle = scale
def forward(
self,
query_input_ids,
title_input_ids,
query_token_type_ids=None,
query_position_ids=None,
query_attention_mask=None,
title_token_type_ids=None,
title_position_ids=None,
title_attention_mask=None,
):
query_cls_embedding = self.get_pooled_embedding(
query_input_ids, query_token_type_ids, query_position_ids, query_attention_mask
)
title_cls_embedding = self.get_pooled_embedding(
title_input_ids, title_token_type_ids, title_position_ids, title_attention_mask
)
cosine_sim = paddle.matmul(query_cls_embedding, title_cls_embedding, transpose_y=True)
# Substract margin from all positive samples cosine_sim()
margin_diag = paddle.full(shape=[query_cls_embedding.shape[0]], fill_value=self.margin, dtype=cosine_sim.dtype)
cosine_sim = cosine_sim - paddle.diag(margin_diag)
# Scale cosine to ease training converge
cosine_sim *= self.sacle
labels = paddle.arange(0, query_cls_embedding.shape[0], dtype="int64")
labels = paddle.reshape(labels, shape=[-1, 1])
return [cosine_sim, labels, query_cls_embedding, title_cls_embedding]

View File

@@ -1,154 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import paddle
from paddlenlp.utils.log import logger
def create_dataloader(dataset, mode="train", batch_size=1, batchify_fn=None, trans_fn=None):
if trans_fn:
dataset = dataset.map(trans_fn)
shuffle = True if mode == "train" else False
if mode == "train":
batch_sampler = paddle.io.DistributedBatchSampler(dataset, batch_size=batch_size, shuffle=shuffle)
else:
batch_sampler = paddle.io.BatchSampler(dataset, batch_size=batch_size, shuffle=shuffle)
return paddle.io.DataLoader(dataset=dataset, batch_sampler=batch_sampler, collate_fn=batchify_fn, return_list=True)
def convert_example(example, tokenizer, max_seq_length=512, pad_to_max_seq_len=False):
"""
Builds model inputs from a sequence.
A BERT sequence has the following format:
- single sequence: ``[CLS] X [SEP]``
Args:
example(obj:`list(str)`): The list of text to be converted to ids.
tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer`
which contains most of the methods. Users should refer to the superclass for more information regarding methods.
max_seq_len(obj:`int`): The maximum total input sequence length after tokenization.
Sequences longer than this will be truncated, sequences shorter will be padded.
is_test(obj:`False`, defaults to `False`): Whether the example contains label or not.
Returns:
input_ids(obj:`list[int]`): The list of query token ids.
token_type_ids(obj: `list[int]`): List of query sequence pair mask.
"""
result = []
for key, text in example.items():
encoded_inputs = tokenizer(text=text, max_seq_len=max_seq_length, pad_to_max_seq_len=pad_to_max_seq_len)
input_ids = encoded_inputs["input_ids"]
token_type_ids = encoded_inputs["token_type_ids"]
result += [input_ids, token_type_ids]
return result
def read_text_pair(data_path):
"""Reads data."""
with open(data_path, "r", encoding="utf-8") as f:
for line in f:
data = line.rstrip().split("\t")
if len(data) != 2:
continue
yield {"text_a": data[0], "text_b": data[1]}
def read_text_triplet(data_path):
"""Reads data."""
with open(data_path, "r", encoding="utf-8") as f:
for line in f:
data = line.rstrip().split("\t")
if len(data) != 3:
continue
yield {"text": data[0], "pos_sample": data[1], "neg_sample": data[2]}
# ANN - active learning ------------------------------------------------------
def get_latest_checkpoint(args):
"""
Return: (latest_checkpoint_path, global_step)
"""
if not os.path.exists(args.save_dir):
return args.init_from_ckpt, 0
subdirectories = list(next(os.walk(args.save_dir))[1])
def valid_checkpoint(checkpoint):
chk_path = os.path.join(args.save_dir, checkpoint)
scheduler_path = os.path.join(chk_path, "model_state.pdparams")
succeed_flag_file = os.path.join(chk_path, "succeed_flag_file")
return os.path.exists(scheduler_path) and os.path.exists(succeed_flag_file)
trained_steps = [int(s) for s in subdirectories if valid_checkpoint(s)]
if len(trained_steps) > 0:
return os.path.join(args.save_dir, str(max(trained_steps)), "model_state.pdparams"), max(trained_steps)
return args.init_from_ckpt, 0
# ANN - active learning ------------------------------------------------------
def get_latest_ann_data(ann_data_dir):
if not os.path.exists(ann_data_dir):
return None, -1
subdirectories = list(next(os.walk(ann_data_dir))[1])
def valid_checkpoint(step):
ann_data_file = os.path.join(ann_data_dir, step, "new_ann_data")
# succeed_flag_file is an empty file that indicates ann data has been generated
succeed_flag_file = os.path.join(ann_data_dir, step, "succeed_flag_file")
return os.path.exists(succeed_flag_file) and os.path.exists(ann_data_file)
ann_data_steps = [int(s) for s in subdirectories if valid_checkpoint(s)]
if len(ann_data_steps) > 0:
latest_ann_data_file = os.path.join(ann_data_dir, str(max(ann_data_steps)), "new_ann_data")
logger.info("Using latest ann_data_file:{}".format(latest_ann_data_file))
return latest_ann_data_file, max(ann_data_steps)
logger.info("no new ann_data, return (None, -1)")
return None, -1
def gen_id2corpus(corpus_file):
id2corpus = {}
with open(corpus_file, "r", encoding="utf-8") as f:
for idx, line in enumerate(f):
id2corpus[idx] = line.rstrip()
return id2corpus
def gen_text_file(similar_text_pair_file):
text2similar_text = {}
texts = []
with open(similar_text_pair_file, "r", encoding="utf-8") as f:
for line in f:
splited_line = line.rstrip().split("\t")
if len(splited_line) != 2:
continue
text, similar_text = line.rstrip().split("\t")
if not text or not similar_text:
continue
text2similar_text[text] = similar_text
texts.append({"text": text})
return texts, text2similar_text

View File

@@ -1 +0,0 @@
python -m paddle_serving_server.serve --model serving_server --port 9393 --gpu_id 2 --thread 5 --ir_optim True --use_trt --precision FP16

View File

@@ -1 +0,0 @@
python predict.py --model_dir=../../output

View File

@@ -1,265 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import os
import sys
import paddle
from paddle import inference
from scipy import spatial
from paddlenlp.data import Pad, Tuple
from paddlenlp.transformers import AutoTokenizer
from paddlenlp.utils.log import logger
sys.path.append(".")
# yapf: disable
parser = argparse.ArgumentParser()
parser.add_argument("--model_dir", type=str, required=True, help="The directory to static model.")
parser.add_argument("--max_seq_length", default=128, type=int, help="The maximum total input sequence length after tokenization. Sequences longer than this will be truncated, sequences shorter will be padded.")
parser.add_argument("--batch_size", default=15, type=int, help="Batch size per GPU/CPU for training.")
parser.add_argument('--device', choices=['cpu', 'gpu', 'xpu'], default="gpu", help="Select which device to train model, defaults to gpu.")
parser.add_argument('--model_name_or_path', default="rocketqa-zh-base-query-encoder", help="model name.")
parser.add_argument('--use_tensorrt', default=False, type=eval, choices=[True, False], help='Enable to use tensorrt to speed up.')
parser.add_argument("--precision", default="fp32", type=str, choices=["fp32", "fp16", "int8"], help='The tensorrt precision.')
parser.add_argument('--cpu_threads', default=10, type=int, help='Number of threads to predict when using cpu.')
parser.add_argument('--enable_mkldnn', default=False, type=eval, choices=[True, False], help='Enable to use mkldnn to speed up when using cpu.')
parser.add_argument("--benchmark", type=eval, default=False, help="To log some information about environment and running.")
parser.add_argument("--save_log_path", type=str, default="./log_output/", help="The file path to save log.")
args = parser.parse_args()
# yapf: enable
def convert_example(example, tokenizer, max_seq_length=512, pad_to_max_seq_len=False):
"""
Builds model inputs from a sequence.
A BERT sequence has the following format:
- single sequence: ``[CLS] X [SEP]``
Args:
example(obj:`list(str)`): The list of text to be converted to ids.
tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer`
which contains most of the methods. Users should refer to the superclass for more information regarding methods.
max_seq_len(obj:`int`): The maximum total input sequence length after tokenization.
Sequences longer than this will be truncated, sequences shorter will be padded.
is_test(obj:`False`, defaults to `False`): Whether the example contains label or not.
Returns:
input_ids(obj:`list[int]`): The list of query token ids.
token_type_ids(obj: `list[int]`): List of query sequence pair mask.
"""
result = []
for key, text in example.items():
encoded_inputs = tokenizer(text=text, max_seq_len=max_seq_length, pad_to_max_seq_len=pad_to_max_seq_len)
input_ids = encoded_inputs["input_ids"]
token_type_ids = encoded_inputs["token_type_ids"]
result += [input_ids, token_type_ids]
return result
class Predictor(object):
def __init__(
self,
model_dir,
device="gpu",
max_seq_length=128,
batch_size=32,
use_tensorrt=False,
precision="fp32",
cpu_threads=10,
enable_mkldnn=False,
):
self.max_seq_length = max_seq_length
self.batch_size = batch_size
model_file = model_dir + "/inference.pdmodel"
params_file = model_dir + "/inference.pdiparams"
if not os.path.exists(model_file):
raise ValueError("not find model file path {}".format(model_file))
if not os.path.exists(params_file):
raise ValueError("not find params file path {}".format(params_file))
config = paddle.inference.Config(model_file, params_file)
if device == "gpu":
# set GPU configs accordingly
# such as initialize the gpu memory, enable tensorrt
config.enable_use_gpu(100, 0)
precision_map = {
"fp16": inference.PrecisionType.Half,
"fp32": inference.PrecisionType.Float32,
"int8": inference.PrecisionType.Int8,
}
precision_mode = precision_map[precision]
if args.use_tensorrt:
config.enable_tensorrt_engine(
max_batch_size=batch_size, min_subgraph_size=30, precision_mode=precision_mode
)
elif device == "cpu":
# set CPU configs accordingly,
# such as enable_mkldnn, set_cpu_math_library_num_threads
config.disable_gpu()
if args.enable_mkldnn:
# cache 10 different shapes for mkldnn to avoid memory leak
config.set_mkldnn_cache_capacity(10)
config.enable_mkldnn()
config.set_cpu_math_library_num_threads(args.cpu_threads)
elif device == "xpu":
# set XPU configs accordingly
config.enable_xpu(100)
config.switch_use_feed_fetch_ops(False)
self.predictor = paddle.inference.create_predictor(config)
self.input_handles = [self.predictor.get_input_handle(name) for name in self.predictor.get_input_names()]
self.output_handle = self.predictor.get_output_handle(self.predictor.get_output_names()[0])
if args.benchmark:
import auto_log
pid = os.getpid()
self.autolog = auto_log.AutoLogger(
model_name=args.model_name_or_path,
model_precision=precision,
batch_size=self.batch_size,
data_shape="dynamic",
save_path=args.save_log_path,
inference_config=config,
pids=pid,
process_name=None,
gpu_ids=0,
time_keys=["preprocess_time", "inference_time", "postprocess_time"],
warmup=0,
logger=logger,
)
def extract_embedding(self, data, tokenizer):
"""
Predicts the data labels.
Args:
data (obj:`List(str)`): The batch data whose each element is a raw text.
tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer`
which contains most of the methods. Users should refer to the superclass for more information regarding methods.
Returns:
results(obj:`dict`): All the feature vectors.
"""
if args.benchmark:
self.autolog.times.start()
examples = []
for text in data:
input_ids, segment_ids = convert_example(text, tokenizer)
examples.append((input_ids, segment_ids))
batchify_fn = lambda samples, fn=Tuple(
Pad(axis=0, pad_val=tokenizer.pad_token_id), # input
Pad(axis=0, pad_val=tokenizer.pad_token_id), # segment
): fn(samples)
if args.benchmark:
self.autolog.times.stamp()
input_ids, segment_ids = batchify_fn(examples)
self.input_handles[0].copy_from_cpu(input_ids)
self.input_handles[1].copy_from_cpu(segment_ids)
self.predictor.run()
logits = self.output_handle.copy_to_cpu()
if args.benchmark:
self.autolog.times.stamp()
if args.benchmark:
self.autolog.times.end(stamp=True)
return logits
def predict(self, data, tokenizer):
"""
Predicts the data labels.
Args:
data (obj:`List(str)`): The batch data whose each element is a raw text.
tokenizer(obj:`PretrainedTokenizer`): This tokenizer inherits from :class:`~paddlenlp.transformers.PretrainedTokenizer`
which contains most of the methods. Users should refer to the superclass for more information regarding methods.
Returns:
results(obj:`dict`): All the predictions probs.
"""
if args.benchmark:
self.autolog.times.start()
examples = []
for idx, text in enumerate(data):
input_ids, segment_ids = convert_example({idx: text[0]}, tokenizer)
title_ids, title_segment_ids = convert_example({idx: text[1]}, tokenizer)
examples.append((input_ids, segment_ids, title_ids, title_segment_ids))
batchify_fn = lambda samples, fn=Tuple(
Pad(axis=0, pad_val=tokenizer.pad_token_id), # input
Pad(axis=0, pad_val=tokenizer.pad_token_id), # segment
Pad(axis=0, pad_val=tokenizer.pad_token_id), # segment
Pad(axis=0, pad_val=tokenizer.pad_token_id), # segment
): fn(samples)
if args.benchmark:
self.autolog.times.stamp()
query_ids, query_segment_ids, title_ids, title_segment_ids = batchify_fn(examples)
self.input_handles[0].copy_from_cpu(query_ids)
self.input_handles[1].copy_from_cpu(query_segment_ids)
self.predictor.run()
query_logits = self.output_handle.copy_to_cpu()
self.input_handles[0].copy_from_cpu(title_ids)
self.input_handles[1].copy_from_cpu(title_segment_ids)
self.predictor.run()
title_logits = self.output_handle.copy_to_cpu()
if args.benchmark:
self.autolog.times.stamp()
if args.benchmark:
self.autolog.times.end(stamp=True)
result = [float(1 - spatial.distance.cosine(arr1, arr2)) for arr1, arr2 in zip(query_logits, title_logits)]
return result
if __name__ == "__main__":
# Define predictor to do prediction.
predictor = Predictor(
args.model_dir,
args.device,
args.max_seq_length,
args.batch_size,
args.use_tensorrt,
args.precision,
args.cpu_threads,
args.enable_mkldnn,
)
# ErnieTinyTokenizer is special for ernie-tiny pretained model.
output_emb_size = 256
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
id2corpus = {0: "国有企业引入非国有资本对创新绩效的影响——基于制造业国有上市公司的经验证据"}
corpus_list = [{idx: text} for idx, text in id2corpus.items()]
res = predictor.extract_embedding(corpus_list, tokenizer)
print(res.shape)
print(res)
corpus_list = [["中西方语言与文化的差异", "中西方文化差异以及语言体现中西方文化,差异,语言体现"], ["中西方语言与文化的差异", "飞桨致力于让深度学习技术的创新与应用更简单"]]
res = predictor.predict(corpus_list, tokenizer)
print(res)

View File

@@ -1,36 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import numpy as np
from paddle_serving_server.pipeline import PipelineClient
client = PipelineClient()
client.connect(["127.0.0.1:8080"])
list_data = ["国有企业引入非国有资本对创新绩效的影响——基于制造业国有上市公司的经验证据", "试论翻译过程中的文化差异与语言空缺翻译过程,文化差异,语言空缺,文化对比"]
feed = {}
for i, item in enumerate(list_data):
feed[str(i)] = item
print(feed)
start_time = time.time()
ret = client.predict(feed_dict=feed)
end_time = time.time()
print("time to cost :{} seconds".format(end_time - start_time))
result = np.array(eval(ret.value[0]))
print(ret.key)
print(result.shape)
print(result)

View File

@@ -1,88 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import numpy as np
import time
parser = argparse.ArgumentParser()
parser.add_argument("--similar_text_pair", type=str,
default='', help="The full path of similar pair file")
parser.add_argument("--recall_result_file", type=str,
default='', help="The full path of recall result file")
parser.add_argument("--recall_num", type=int, default=10,
help="Most similar number of doc recalled from corpus per query")
args = parser.parse_args()
def recall(rs, N=10):
"""
Ratio of recalled Ground Truth at topN Recalled Docs
>>> rs = [[0, 0, 1], [0, 1, 0], [1, 0, 0]]
>>> recall(rs, N=1)
0.333333
>>> recall(rs, N=2)
>>> 0.6666667
>>> recall(rs, N=3)
>>> 1.0
Args:
rs: Iterator of recalled flag()
Returns:
Recall@N
"""
recall_flags = [np.sum(r[0:N]) for r in rs]
return np.mean(recall_flags)
if __name__ == "__main__":
text2similar = {}
with open(args.similar_text_pair, "r", encoding="utf-8") as f:
for line in f:
text, similar_text = line.rstrip().split("\t")
text2similar[text] = similar_text
rs = []
with open(args.recall_result_file, "r", encoding="utf-8") as f:
relevance_labels = []
for index, line in enumerate(f):
if index % args.recall_num == 0 and index != 0:
rs.append(relevance_labels)
relevance_labels = []
text, recalled_text, cosine_sim = line.rstrip().split("\t")
if text2similar[text] == recalled_text:
relevance_labels.append(1)
else:
relevance_labels.append(0)
recall_N = []
recall_num = [1, 5, 10, 20, 50]
for topN in recall_num:
R = round(100 * recall(rs, N=topN), 3)
recall_N.append(str(R))
result = open("result.tsv", "a")
res = []
timestamp = time.strftime("%Y%m%d-%H%M%S", time.localtime())
res.append(timestamp)
for key, val in zip(recall_num, recall_N):
print("recall@{}={}".format(key, val))
res.append(str(val))
result.write("\t".join(res) + "\n")

View File

@@ -1,49 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import paddle_serving_client.io as serving_io
# yapf: disable
parser = argparse.ArgumentParser()
parser.add_argument("--dirname", type=str, required=True,
default='./output', help="Path of saved model files. Program file and parameter files are saved in this directory.")
parser.add_argument("--model_filename", type=str, required=True,
default='inference.get_pooled_embedding.pdmodel', help="The name of file to load the inference program. If it is None, the default filename __model__ will be used.")
parser.add_argument("--params_filename", type=str, required=True,
default='inference.get_pooled_embedding.pdiparams', help="The name of file to load all parameters. It is only used for the case that all parameters were saved in a single binary file. If parameters were saved in separate files, set it as None. Default: None.")
parser.add_argument("--server_path", type=str, default='./serving_server',
help="The path of server parameter in static graph to be saved.")
parser.add_argument("--client_path", type=str, default='./serving_client',
help="The path of client parameter in static graph to be saved.")
parser.add_argument("--feed_alias_names", type=str, default=None,
help='set alias names for feed vars, split by comma \',\', you should run --show_proto to check the number of feed vars')
parser.add_argument("--fetch_alias_names", type=str, default=None,
help='set alias names for feed vars, split by comma \',\', you should run --show_proto to check the number of fetch vars')
parser.add_argument("--show_proto", type=bool, default=False,
help='If yes, you can preview the proto and then determine your feed var alias name and fetch var alias name.')
# yapf: enable
if __name__ == "__main__":
args = parser.parse_args()
serving_io.inference_model_to_serving(
dirname=args.dirname,
serving_server=args.server_path,
serving_client=args.client_path,
model_filename=args.model_filename,
params_filename=args.params_filename,
show_proto=args.show_proto,
feed_alias_names=args.feed_alias_names,
fetch_alias_names=args.fetch_alias_names,
)

View File

@@ -1,75 +0,0 @@
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from functools import partial
import os
import paddle
from paddlenlp.data import Tuple, Pad
from paddlenlp.datasets import MapDataset
from paddlenlp.transformers import AutoModel, AutoTokenizer
from base_model import SemanticIndexBaseStatic
from data import convert_example, create_dataloader
if __name__ == "__main__":
device = "gpu"
max_seq_length = 64
output_emb_size = 256
batch_size = 1
params_path = "checkpoints/inbatch/model_40/model_state.pdparams"
id2corpus = {0: "国有企业引入非国有资本对创新绩效的影响——基于制造业国有上市公司的经验证据"}
model_name_or_path = "rocketqa-zh-base-query-encoder"
paddle.set_device(device)
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
trans_func = partial(convert_example, tokenizer=tokenizer, max_seq_length=max_seq_length)
batchify_fn = lambda samples, fn=Tuple( # noqa: E731
Pad(axis=0, pad_val=tokenizer.pad_token_id), # text_input
Pad(axis=0, pad_val=tokenizer.pad_token_type_id), # text_segment
): [data for data in fn(samples)]
pretrained_model = AutoModel.from_pretrained(model_name_or_path)
model = SemanticIndexBaseStatic(pretrained_model, output_emb_size=output_emb_size)
# Load pretrained semantic model
if params_path and os.path.isfile(params_path):
state_dict = paddle.load(params_path)
model.set_dict(state_dict)
print("Loaded parameters from %s" % params_path)
else:
raise ValueError("Please set --params_path with correct pretrained model file")
# convert_example function's input must be dict
corpus_list = [{idx: text} for idx, text in id2corpus.items()]
corpus_ds = MapDataset(corpus_list)
corpus_data_loader = create_dataloader(
corpus_ds, mode="predict", batch_size=batch_size, batchify_fn=batchify_fn, trans_fn=trans_func
)
all_embeddings = []
model.eval()
with paddle.no_grad():
for batch_data in corpus_data_loader:
input_ids, token_type_ids = batch_data
text_embeddings = model.get_pooled_embedding(input_ids, token_type_ids)
all_embeddings.append(text_embeddings)
text_embedding = all_embeddings[0]
print(text_embedding.shape)
print(text_embedding.numpy())

View File

@@ -1,134 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# coding=UTF-8
import argparse
import os
from functools import partial
import paddle
from ann_util import build_index
from base_model import SemanticIndexBase
from data import convert_example, create_dataloader, gen_id2corpus, gen_text_file
from paddlenlp.data import Pad, Tuple
from paddlenlp.datasets import MapDataset
from paddlenlp.transformers import AutoModel, AutoTokenizer
from paddlenlp.utils.log import logger
# yapf: disable
parser = argparse.ArgumentParser()
parser.add_argument("--corpus_file", type=str, required=True,
help="The full path of input file")
parser.add_argument("--similar_text_pair_file", type=str,
required=True, help="The full path of similar text pair file")
parser.add_argument("--recall_result_dir", type=str, default='recall_result',
help="The full path of recall result file to save")
parser.add_argument("--recall_result_file", type=str,
default='recall_result_file', help="The file name of recall result")
parser.add_argument("--params_path", type=str, required=True,
help="The path to model parameters to be loaded.")
parser.add_argument("--max_seq_length", default=64, type=int, help="The maximum total input sequence length after tokenization. "
"Sequences longer than this will be truncated, sequences shorter will be padded.")
parser.add_argument("--batch_size", default=32, type=int,
help="Batch size per GPU/CPU for training.")
parser.add_argument("--output_emb_size", default=None,
type=int, help="output_embedding_size")
parser.add_argument("--recall_num", default=10, type=int,
help="Recall number for each query from Ann index.")
parser.add_argument('--model_name_or_path', default="rocketqa-zh-base-query-encoder", help="The pretrained model used for training")
parser.add_argument("--hnsw_m", default=100, type=int,
help="Recall number for each query from Ann index.")
parser.add_argument("--hnsw_ef", default=100, type=int,
help="Recall number for each query from Ann index.")
parser.add_argument("--hnsw_max_elements", default=1000000,
type=int, help="Recall number for each query from Ann index.")
parser.add_argument('--device', choices=['cpu', 'gpu'], default="gpu",
help="Select which device to train model, defaults to gpu.")
args = parser.parse_args()
# yapf: enable
if __name__ == "__main__":
paddle.set_device(args.device)
rank = paddle.distributed.get_rank()
if paddle.distributed.get_world_size() > 1:
paddle.distributed.init_parallel_env()
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path)
trans_func = partial(convert_example, tokenizer=tokenizer, max_seq_length=args.max_seq_length)
batchify_fn = lambda samples, fn=Tuple(
Pad(axis=0, pad_val=tokenizer.pad_token_id, dtype="int64"), # text_input
Pad(axis=0, pad_val=tokenizer.pad_token_type_id, dtype="int64"), # text_segment
): [data for data in fn(samples)]
pretrained_model = AutoModel.from_pretrained(args.model_name_or_path)
model = SemanticIndexBase(pretrained_model, output_emb_size=args.output_emb_size)
model = paddle.DataParallel(model)
# Load pretrained semantic model
if args.params_path and os.path.isfile(args.params_path):
state_dict = paddle.load(args.params_path)
model.set_dict(state_dict)
logger.info("Loaded parameters from %s" % args.params_path)
else:
raise ValueError("Please set --params_path with correct pretrained model file")
id2corpus = gen_id2corpus(args.corpus_file)
# conver_example function's input must be dict
corpus_list = [{idx: text} for idx, text in id2corpus.items()]
corpus_ds = MapDataset(corpus_list)
corpus_data_loader = create_dataloader(
corpus_ds, mode="predict", batch_size=args.batch_size, batchify_fn=batchify_fn, trans_fn=trans_func
)
# Need better way to get inner model of DataParallel
inner_model = model._layers
final_index = build_index(args, corpus_data_loader, inner_model)
text_list, text2similar_text = gen_text_file(args.similar_text_pair_file)
query_ds = MapDataset(text_list)
query_data_loader = create_dataloader(
query_ds, mode="predict", batch_size=args.batch_size, batchify_fn=batchify_fn, trans_fn=trans_func
)
query_embedding = inner_model.get_semantic_embedding(query_data_loader)
if not os.path.exists(args.recall_result_dir):
os.mkdir(args.recall_result_dir)
recall_result_file = os.path.join(args.recall_result_dir, args.recall_result_file)
with open(recall_result_file, "w", encoding="utf-8") as f:
for batch_index, batch_query_embedding in enumerate(query_embedding):
recalled_idx, cosine_sims = final_index.knn_query(batch_query_embedding.numpy(), args.recall_num)
batch_size = len(cosine_sims)
for row_index in range(batch_size):
text_index = args.batch_size * batch_index + row_index
for idx, doc_idx in enumerate(recalled_idx[row_index]):
f.write(
"{}\t{}\t{}\n".format(
text_list[text_index]["text"], id2corpus[doc_idx], 1.0 - cosine_sims[row_index][idx]
)
)

View File

@@ -1,4 +0,0 @@
python -u evaluate.py \
--similar_text_pair "recall/dev.csv" \
--recall_result_file "./recall_result_dir/recall_result.txt" \
--recall_num 50

View File

@@ -1,3 +0,0 @@
python export_model.py --params_path checkpoints/inbatch/model_40/model_state.pdparams \
--model_name_or_path rocketqa-zh-base-query-encoder \
--output_path=./output

View File

@@ -1,7 +0,0 @@
python export_to_serving.py \
--dirname "output" \
--model_filename "inference.get_pooled_embedding.pdmodel" \
--params_filename "inference.get_pooled_embedding.pdiparams" \
--server_path "serving_server" \
--client_path "serving_client" \
--fetch_alias_names "output_embedding"

View File

@@ -1,22 +0,0 @@
# gpu version
root_dir="checkpoints/inbatch"
python -u -m paddle.distributed.launch --gpus "0" \
predict.py \
--device gpu \
--params_path "${root_dir}/model_40/model_state.pdparams" \
--model_name_or_path rocketqa-zh-base-query-encoder \
--output_emb_size 256 \
--batch_size 128 \
--max_seq_length 64 \
--text_pair_file "recall/test.csv"
# cpu
# root_dir="checkpoints/inbatch"
# python predict.py \
# --device cpu \
# --params_path "${root_dir}/model_40/model_state.pdparams" \
# --output_emb_size 256 \
# --batch_size 128 \
# --max_seq_length 64 \
# --text_pair_file "recall/test.csv"

View File

@@ -1,220 +0,0 @@
**目录**
* [背景介绍](#背景介绍)
* [Milvus召回](#Milvus召回)
* [1. 技术方案和评估指标](#技术方案)
* [2. 环境依赖](#环境依赖)
* [3. 代码结构](#代码结构)
* [4. 数据准备](#数据准备)
* [5. 向量检索](#向量检索)
<a name="背景介绍"></a>
# 背景介绍
基于某检索平台开源的数据集构造生成了面向语义索引的召回库。
<a name="Milvus召回"></a>
# Milvus召回
<a name="技术方案"></a>
## 1. 技术方案和评估指标
### 技术方案
使用 Milvus 搭建召回系统,然后使用训练好的语义索引模型,抽取向量,插入到 Milvus 中,然后进行检索。
<a name="环境依赖"></a>
## 2. 环境依赖和安装说明
**环境依赖**
* python >= 3.6.2
* paddlepaddle >= 2.2
* paddlenlp >= 2.2
* milvus >= 2.1.0
* pymilvus >= 2.1.0
<a name="代码结构"></a>
## 3. 代码结构
## 代码结构:
```
|—— scripts
|—— feature_extract.sh 提取特征向量的bash脚本
|—— search.sh 插入向量和向量检索bash脚本
├── base_model.py # 语义索引模型基类
├── config.py # milvus配置文件
├── data.py # 数据处理函数
├── milvus_ann_search.py # 向量插入和检索的脚本
├── inference.py # 动态图模型向量抽取脚本
├── feature_extract.py # 批量抽取向量脚本
├── milvus_util.py # milvus的工具类
└── README.md
```
<a name="数据准备"></a>
## 4. 数据准备
数据集的样例如下,有两种,第一种是 title+keywords 进行拼接;第二种是一句话。
```
煤矸石-污泥基活性炭介导强化污水厌氧消化煤矸石,污泥,复合基活性炭,厌氧消化,直接种间电子传递
睡眠障碍与常见神经系统疾病的关系睡眠觉醒障碍,神经系统疾病,睡眠,快速眼运动,细胞增殖,阿尔茨海默病
城市道路交通流中观仿真研究智能运输系统;城市交通管理;计算机仿真;城市道路;交通流;路径选择
....
```
### 数据集下载
- [literature_search_data](https://bj.bcebos.com/v1/paddlenlp/data/literature_search_data.zip)
```
├── milvus # milvus建库数据集
├── milvus_data.csv. # 构建召回库的数据
├── recall # 召回(语义索引)数据集
├── corpus.csv # 用于测试的召回库
├── dev.csv # 召回验证集
├── test.csv # 召回测试集
├── train.csv # 召回训练集
├── train_unsupervised.csv # 无监督训练集
├── sort # 排序数据集
├── test_pairwise.csv # 排序测试集
├── dev_pairwise.csv # 排序验证集
└── train_pairwise.csv # 排序训练集
```
<a name="向量检索"></a>
## 5. 向量检索
### 5.1 基于Milvus的向量检索系统搭建
数据准备结束以后,我们开始搭建 Milvus 的语义检索引擎,用于语义向量的快速检索,我们使用[Milvus](https://milvus.io/)开源工具进行召回,Milvus 的搭建教程请参考官方教程 [Milvus官方安装教程](https://milvus.io/docs/v2.1.x/install_standalone-docker.md)本案例使用的是 Milvus 的2.1版本,建议使用官方的 Docker 安装方式,简单快捷。
Milvus 搭建完系统以后就可以插入和检索向量了,首先生成 embedding 向量,每个样本生成256维度的向量,使用的是32GB的V100的卡进行的提取:
```
CUDA_VISIBLE_DEVICES=0 python feature_extract.py \
--model_dir=./output \
--model_name_or_path rocketqa-zh-base-query-encoder \
--corpus_file "data/milvus_data.csv"
```
其中 output 目录下存放的是召回的 Paddle Inference 静态图模型。
| 数据量 | 时间 |
| ------------ | ------------ |
|1000万条|3hour40min39s|
运行结束后会生成 corpus_embedding.npy
生成了向量后,需要把数据插入到 Milvus 库中,首先修改配置:
修改 config.py 的配置 ip 和端口,本项目使用的是8530端口,而 Milvus 默认的是19530,需要根据情况进行修改:
```
MILVUS_HOST='your milvus ip'
MILVUS_PORT = 8530
```
然后运行下面的命令把向量插入到Milvus库中:
```
python milvus_ann_search.py --data_path milvus/milvus_data.csv \
--embedding_path corpus_embedding.npy \
--batch_size 100000 \
--insert
```
参数含义说明
* `data_path`: 数据的路径
* `embedding_path`: 数据对应向量的路径
* `index`: 选择检索向量的索引,用于向量检索
* `insert`: 是否插入向量
* `search`: 是否检索向量
* `batch_size`: 表示的是一次性插入的向量的数量
| 数据量 | 时间 |
| ------------ | ------------ |
|1000万条|21min12s|
另外,Milvus提供了可视化的管理界面,可以很方便的查看数据,安装地址为[Attu](https://github.com/zilliztech/attu).
![](../../img/attu.png)
运行召回脚本:
```
python milvus_ann_search.py --data_path milvus/milvus_data.csv \
--embedding_path corpus_embedding.npy \
--batch_size 100000 \
--index 18 \
--search
```
运行以后的结果的输出为:
```
hit: (distance: 0.0, id: 18), text field: 吉林铁合金集团资产管理现状分析及对策资产管理;资金控制;应收帐款风险;造价控制;集中化财务控制
hit: (distance: 0.45325806736946106, id: 7611689), text field: 哈药集团应收账款分析应收账款,流动资产,财务报告
hit: (distance: 0.5440893769264221, id: 4297885), text field: 宝钢集团负债经营风险控制策略研究钢铁行业;负债经营;风险控制
hit: (distance: 0.5455711483955383, id: 5661135), text field: 浅谈电网企业固定资产风险管理大数据,固定资产,风险管理
...
```
返回的是向量的距离,向量的id,以及对应的文本。
也可以一键执行上述的过程:
```
sh scripts/search.sh
```
### 5.2 文本检索
首先修改代码的模型路径和样本:
```
params_path='checkpoints/model_40/model_state.pdparams'
id2corpus={0:'国有企业引入非国有资本对创新绩效的影响——基于制造业国有上市公司的经验证据'}
```
运行命令
```
python3 inference.py
```
运行的输出为,分别是抽取的向量和召回的结果:
```
[1, 256]
Tensor(shape=[1, 256], dtype=float32, place=Place(gpu:0), stop_gradient=True,
[[ 0.07830613, -0.14036864, 0.03433795, -0.14967985, -0.03386058,
0.06630671, 0.01357946, 0.03531205, 0.02411086, 0.02000865,
0.05724005, -0.08119474, 0.06286906, 0.06509133, 0.07193415,
....
hit: (distance: 0.40141725540161133, id: 2742485), text field: 完善国有企业技术创新投入机制的探讨--基于经济责任审计实践国有企业,技术创新,投
入机制
hit: (distance: 0.40258315205574036, id: 1472893), text field: 企业技术创新与组织冗余--基于国有企业与非国有企业的情境研究
hit: (distance: 0.4121206998825073, id: 51831), text field: 企业创新影响对外直接投资决策—基于中国制造业上市公司的研究企业创新;对外直接投资;
制造业;上市公司
hit: (distance: 0.42234909534454346, id: 8682312), text field: 政治关联对企业创新绩效的影响——国有企业与民营企业的对比政治关联,创新绩效,国有
企业,民营企业,双重差分
hit: (distance: 0.46187296509742737, id: 9324797), text field: 财务杠杆、股权激励与企业创新——基于中国A股制造业经验数据制造业;上市公司;股权激
励;财务杠杆;企业创新
....
```
## FAQ
#### 抽取文本语义向量后,利用 Milvus 进行 ANN 检索查询到了完全相同的文本,但是计算出的距离为什么不是 0?
使用的是近似索引,详情请参考Milvus官方文档,[索引创建机制](https://milvus.io/cn/docs/v2.0.x/index.md)

View File

@@ -1,6 +0,0 @@
CUDA_VISIBLE_DEVICES=2 python feature_extract.py \
--model_dir ./output \
--model_name_or_path rocketqa-zh-base-query-encoder \
--batch_size 512 \
--corpus_file "milvus/milvus_data.csv"

View File

@@ -1,6 +0,0 @@
python milvus_ann_search.py --data_path milvus/milvus_data.csv \
--embedding_path corpus_embedding.npy \
--batch_size 100000 \
--index 18 \
--insert \
--search

View File

@@ -1,448 +0,0 @@
**目录**
* [背景介绍](#背景介绍)
* [SimCSE](#SimCSE)
* [1. 技术方案和评估指标](#技术方案)
* [2. 环境依赖](#环境依赖)
* [3. 代码结构](#代码结构)
* [4. 数据准备](#数据准备)
* [5. 模型训练](#模型训练)
* [6. 评估](#开始评估)
* [7. 预测](#预测)
* [8. 部署](#部署)
<a name="背景介绍"></a>
# 背景介绍
语义索引(可通俗理解为向量索引)技术是搜索引擎、推荐系统、广告系统在召回阶段的核心技术之一。语义索引模型的目标是:给定输入文本,模型可以从海量候选召回库中**快速、准确**地召回一批语义相关文本。语义索引模型的效果直接决定了语义相关的物料能否被成功召回进入系统参与上层排序,从基础层面影响整个系统的效果。
在召回阶段,最常见的方式是通过双塔模型,学习Document(简写为Doc)的向量表示,对Doc端建立索引,用ANN召回。我们在这种方式的基础上,引入无监督预训练策略,以如下训练数据为例:
```
我手机丢了,我想换个手机 我想买个新手机,求推荐
求秋色之空漫画全集 求秋色之空全集漫画
学日语软件手机上的 手机学日语的软件
侠盗飞车罪恶都市怎样改车 侠盗飞车罪恶都市怎么改车
```
SimCSE 模型适合缺乏监督数据,但是又有大量无监督数据的匹配和检索场景。
<a name="SimCSE"></a>
# SimCSE
<a name="技术方案"></a>
## 1. 技术方案和评估指标
### 技术方案
双塔模型,采用ERNIE1.0热启,在召回阶段引入 SimCSE 策略。
### 评估指标
(1)采用 Recall@1,Recall@5 ,Recall@10 ,Recall@20 和 Recall@50 指标来评估语义索引模型的召回效果。
**效果评估**
| 策略 | 模型| Recall@1 | Recall@5 |Recall@10 |Recall@20 |Recall@50 |
| ------------ | ------------ | ------------ |--------- |--------- |--------- |--------- |
| SimCSE | ernie 1.0 |42.374 | 57.505| 62.641| 67.09|72.331|
| SimCSE | rocketqa-zh-base-query-encoder |**50.108** | **64.005**| **68.288**| **72.306**|**77.306**|
<a name="环境依赖"></a>
## 2. 环境依赖和安装说明
**环境依赖**
* python >= 3.6
* paddlepaddle >= 2.1.3
* paddlenlp >= 2.2
* [hnswlib](https://github.com/nmslib/hnswlib) >= 0.5.2
* visualdl >= 2.2.2
<a name="代码结构"></a>
## 3. 代码结构
以下是本项目主要代码结构及说明:
```
simcse/
├── model.py # SimCSE 模型组网代码
|—— deploy
|—— python
|—— predict.py # PaddleInference
├── deploy.sh # Paddle Inference的bash脚本
|—— scripts
├── export_model.sh # 动态图转静态图bash脚本
├── predict.sh # 预测的bash脚本
├── evaluate.sh # 召回评估bash脚本
├── run_build_index.sh # 索引的构建脚本
├── train.sh # 训练的bash脚本
|—— ann_util.py # Ann 建索引库相关函数
├── data.py # 无监督语义匹配训练数据、测试数据的读取逻辑
├── export_model.py # 动态图转静态图
├── predict.py # 基于训练好的无监督语义匹配模型计算文本 Pair 相似度
├── evaluate.py # 根据召回结果和评估集计算评估指标
|—— inference.py # 动态图抽取向量
|—— recall.py # 基于训练好的语义索引模型,从召回库中召回给定文本的相似文本
└── train.py # SimCSE 模型训练、评估逻辑
```
<a name="数据准备"></a>
## 4. 数据准备
### 数据集说明
我们基于开源的语义匹配数据集构造生成了面向语义索引的训练集、评估集、召回库。
样例数据如下:
```
睡眠障碍与常见神经系统疾病的关系睡眠觉醒障碍,神经系统疾病,睡眠,快速眼运动,细胞增殖,阿尔茨海默病
城市道路交通流中观仿真研究
城市道路交通流中观仿真研究智能运输系统;城市交通管理;计算机仿真;城市道路;交通流;路径选择
网络健康可信性研究
网络健康可信性研究网络健康信息;可信性;评估模式
脑瘫患儿家庭复原力的影响因素及干预模式雏形 研究
脑瘫患儿家庭复原力的影响因素及干预模式雏形研究脑瘫患儿;家庭功能;干预模式
地西他滨与HA方案治疗骨髓增生异常综合征转化的急性髓系白血病患者近期疗效比较
地西他滨与HA方案治疗骨髓增生异常综合征转化的急性髓系白血病患者近期疗效比较
个案工作 社会化
个案社会工作介入社区矫正再社会化研究——以东莞市清溪镇为例社会工作者;社区矫正人员;再社会化;角色定位
圆周运动加速度角速度
圆周运动向心加速度物理意义的理论分析匀速圆周运动,向心加速度,物理意义,角速度,物理量,线速度,周期
```
召回集,验证集,测试集与inbatch-negative实验的数据保持一致
### 数据集下载
- [literature_search_data](https://bj.bcebos.com/v1/paddlenlp/data/literature_search_data.zip)
```
├── milvus # milvus建库数据集
├── milvus_data.csv. # 构建召回库的数据
├── recall # 召回(语义索引)数据集
├── corpus.csv # 用于测试的召回库
├── dev.csv # 召回验证集
├── test.csv # 召回测试集
├── train.csv # 召回训练集
├── train_unsupervised.csv # 无监督训练集
├── sort # 排序数据集
├── test_pairwise.csv # 排序测试集
├── dev_pairwise.csv # 排序验证集
└── train_pairwise.csv # 排序训练集
```
<a name="模型训练"></a>
## 5. 模型训练
**语义索引预训练模型下载链接:**
以下模型结构参数为: `TrasformerLayer:12, Hidden:768, Heads:12, OutputEmbSize: 256`
|Model|训练参数配置|硬件|MD5|
| ------------ | ------------ | ------------ |-----------|
|[SimCSE](https://bj.bcebos.com/v1/paddlenlp/models/simcse_model.zip)|<div style="width: 150pt">ernie 1.0 epoch:3 lr:5E-5 bs:64 max_len:64 </div>|<div style="width: 100pt">4卡 v100-16g</div>|7c46d9b15a214292e3897c0eb70d0c9f|
### 训练环境说明
+ NVIDIA Driver Version: 440.64.00
+ Ubuntu 16.04.6 LTS (Docker)
+ Intel(R) Xeon(R) Gold 6148 CPU @ 2.40GHz
### 单机单卡训练/单机多卡训练
这里采用单机多卡方式进行训练,通过如下命令,指定 GPU 0,1,2,3 卡, 基于SimCSE训练模型,无监督的数据量比较大,4卡的训练的时长在16个小时左右。如果采用单机单卡训练,只需要把`--gpu`参数设置成单卡的卡号即可。
训练的命令如下:
```shell
$ unset CUDA_VISIBLE_DEVICES
python -u -m paddle.distributed.launch --gpus '0,1,2,3' \
train.py \
--device gpu \
--save_dir ./checkpoints/ \
--batch_size 64 \
--learning_rate 5E-5 \
--epochs 3 \
--save_steps 2000 \
--eval_steps 100 \
--max_seq_length 64 \
--infer_with_fc_pooler \
--dropout 0.2 \
--output_emb_size 256 \
--train_set_file "./recall/train_unsupervised.csv" \
--test_set_file "./recall/dev.csv" \
--model_name_or_path "rocketqa-zh-base-query-encoder"
```
也可以使用bash脚本:
```
sh scripts/train.sh
```
可支持配置的参数:
* `infer_with_fc_pooler`:可选,在预测阶段计算文本 embedding 表示的时候网络前向是否会过训练阶段最后一层的 fc; 建议打开模型效果最好。
* `scale`:可选,在计算 cross_entropy loss 之前对 cosine 相似度进行缩放的因子;默认为 20。
* `dropout`:可选,SimCSE 网络前向使用的 dropout 取值;默认 0.1。
* `save_dir`:可选,保存训练模型的目录;默认保存在当前目录checkpoints文件夹下。
* `max_seq_length`:可选,ERNIE-Gram 模型使用的最大序列长度,最大不能超过512, 若出现显存不足,请适当调低这一参数;默认为128。
* `batch_size`:可选,批处理大小,请结合显存情况进行调整,若出现显存不足,请适当调低这一参数;默认为32。
* `learning_rate`:可选,Fine-tune的最大学习率;默认为5e-5。
* `weight_decay`:可选,控制正则项力度的参数,用于防止过拟合,默认为0.0。
* `epochs`: 训练轮次,默认为1。
* `warmup_proption`:可选,学习率warmup策略的比例,如果0.1,则学习率会在前10%训练step的过程中从0慢慢增长到learning_rate, 而后再缓慢衰减,默认为0.0。
* `init_from_ckpt`:可选,模型参数路径,热启动模型训练;默认为None。
* `seed`:可选,随机种子,默认为1000.
* `device`: 选用什么设备进行训练,可选cpu或gpu。如使用gpu训练则参数gpus指定GPU卡号。
* `model_name_or_path`: 预训练模型,用于模型和`Tokenizer`的参数初始化。
程序运行时将会自动进行训练,评估。同时训练过程中会自动保存模型在指定的`save_dir`中。
如:
```text
checkpoints/
├── model_100
│   ├── model_state.pdparams
│   ├── tokenizer_config.json
│   └── vocab.txt
└── ...
```
<a name="评估"></a>
## 6. 评估
效果评估分为 4 个步骤:
a. 获取Doc端Embedding
基于语义索引模型抽取出Doc样本库的文本向量,
b. 采用hnswlib对Doc端Embedding建库
使用 ANN 引擎构建索引库(这里基于 [hnswlib](https://github.com/nmslib/hnswlib) 进行 ANN 索引)
c. 获取Query的Embedding并查询相似结果
基于语义索引模型抽取出评估集 *Source Text* 的文本向量,在第 2 步中建立的索引库中进行 ANN 查询,召回 Top50 最相似的 *Target Text*, 产出评估集中 *Source Text* 的召回结果 `recall_result` 文件
d. 评估
基于评估集 `dev.csv` 和召回结果 `recall_result` 计算评估指标 Recall@k,其中k取值1,5,10,20,50.
运行如下命令进行 ANN 建库、召回,产出召回结果数据 `recall_result`
```
python -u -m paddle.distributed.launch --gpus "6" --log_dir "recall_log/" \
recall.py \
--device gpu \
--recall_result_dir "recall_result_dir" \
--recall_result_file "recall_result.txt" \
--params_path "checkpoints/model_12000/model_state.pdparams" \
--model_name_or_path rocketqa-zh-base-query-encoder \
--hnsw_m 100 \
--hnsw_ef 100 \
--batch_size 64 \
--output_emb_size 256\
--max_seq_length 60 \
--recall_num 50 \
--similar_text_pair "recall/dev.csv" \
--corpus_file "recall/corpus.csv"
```
也可以使用下面的bash脚本:
```
sh scripts/run_build_index.sh
```
run_build_index.sh还包含cpu和gpu运行的脚本,默认是gpu的脚本
接下来,运行如下命令进行效果评估,产出Recall@1, Recall@5, Recall@10, Recall@20 和 Recall@50 指标:
```
python -u evaluate.py \
--similar_text_pair "recall/dev.csv" \
--recall_result_file "./recall_result_dir/recall_result.txt" \
--recall_num 50
```
也可以使用下面的bash脚本:
```
bash scripts/evaluate.sh
```
参数含义说明
* `similar_text_pair`: 由相似文本对构成的评估集
* `recall_result_file`: 针对评估集中第一列文本 *Source Text* 的召回结果
* `recall_num`: 对 1 个文本召回的相似文本数量
成功运行结束后,会输出如下评估指标:
```
recall@1=45.183
recall@5=60.444
recall@10=65.224
recall@20=69.562
recall@50=74.848
```
<a name="预测"></a>
## 7. 预测
我们可以基于语义索引模型预测文本的语义向量或者计算文本 Pair 的语义相似度。
### 7.1 功能一:抽取文本的语义向量
修改 inference.py 文件里面输入文本 id2corpus 和模型路径 params_path:
```
params_path='checkpoints/model_12000/model_state.pdparams'
id2corpus={0:'国有企业引入非国有资本对创新绩效的影响——基于制造业国有上市公司的经验证据'}
```
然后运行
```
python inference.py
```
预测结果位256维的向量:
```
[1, 256]
[[-6.70653954e-02 -6.46878220e-03 -6.78317016e-03 1.66617986e-02
7.20006675e-02 -9.79134627e-03 -1.38441555e-03 4.37440760e-02
4.78116237e-02 1.33881181e-01 1.82927232e-02 3.23656350e-02
...
```
### 7.2 功能二:计算文本 Pair 的语义相似度
### 准备预测数据
待预测数据为 tab 分隔的 tsv 文件,每一行为 1 个文本 Pair,部分示例如下:
```
热处理对尼龙6 及其与聚酰胺嵌段共聚物共混体系晶体熔融行为和结晶结构的影响 热处理对尼龙6及其与聚酰胺嵌段共聚物共混体系晶体熔融行为和结晶结构的影响尼龙6,聚酰胺嵌段共聚物,芳香聚酰胺,热处理
面向生态系统服务的生态系统分类方案研发与应用. 面向生态系统服务的生态系统分类方案研发与应用
huntington舞蹈病的动物模型 Huntington舞蹈病的动物模型
试论我国海岸带经济开发的问题与前景 试论我国海岸带经济开发的问题与前景海岸带,经济开发,问题,前景
```
### 开始预测
以上述 demo 数据为例,运行如下命令基于我们开源的 SimCSE无监督语义索引模型开始计算文本 Pair 的语义相似度:
```
root_dir="checkpoints"
python -u -m paddle.distributed.launch --gpus "3" \
predict.py \
--device gpu \
--params_path "${root_dir}/model_12000/model_state.pdparams" \
--model_name_or_path rocketqa-zh-base-query-encoder \
--output_emb_size 256 \
--batch_size 128 \
--max_seq_length 64 \
--text_pair_file "recall/test.csv"
```
参数含义说明
* `device`: 使用 cpu/gpu 进行训练
* `params_path`: 预训练模型的参数文件名
* `model_name_or_path`: 预训练模型,用于模型和`Tokenizer`的参数初始化。
* `output_emb_size`: Transformer 顶层输出的文本向量维度
* `text_pair_file`: 由文本 Pair 构成的待预测数据集
也可以运行下面的bash脚本:
```
sh scripts/predict.sh
```
产出如下结果
```
0.6477588415145874
0.9698382019996643
1.0
0.1787596344947815
```
<a name="部署"></a>
## 8. 部署
### 动转静导出
首先把动态图模型转换为静态图:
```
python export_model.py --params_path checkpoints/model_12000/model_state.pdparams \
--model_name_or_path rocketqa-zh-base-query-encoder \
--output_path=./output
```
也可以运行下面的bash脚本:
```
sh scripts/export_model.sh
```
### Paddle Inference预测
预测既可以抽取向量也可以计算两个文本的相似度。
修改id2corpus的样本:
```
# 抽取向量
id2corpus={0:'国有企业引入非国有资本对创新绩效的影响——基于制造业国有上市公司的经验证据'}
# 计算相似度
corpus_list=[['中西方语言与文化的差异','中西方文化差异以及语言体现中西方文化,差异,语言体现'],
['中西方语言与文化的差异','飞桨致力于让深度学习技术的创新与应用更简单']]
```
然后使用PaddleInference
```
python deploy/python/predict.py --model_dir=./output
```
也可以运行下面的bash脚本:
```
sh deploy.sh
```
最终输出的是256维度的特征向量和句子对的预测概率
```
(1, 256)
[[-6.70653731e-02 -6.46873191e-03 -6.78317575e-03 1.66618153e-02
7.20006898e-02 -9.79136024e-03 -1.38439541e-03 4.37440872e-02
4.78115827e-02 1.33881137e-01 1.82927139e-02 3.23656537e-02
.......
[0.5649663209915161, 0.03284594044089317]
```
## FAQ
#### SimCSE模型怎么部署?
+ SimCSE使用的模型跟 In-batch Negatives 训练出来的模型网络结构是一样的,使用 In-batch Negatives 的部署流程即可,参考[In-batch Negatives](https://github.com/PaddlePaddle/PaddleNLP/tree/develop/applications/neural_search/recall/in_batch_negative/deploy/python)
## Reference
[1] Gao, Tianyu, Xingcheng Yao, and Danqi Chen. “SimCSE: Simple Contrastive Learning of Sentence Embeddings.” ArXiv:2104.08821 [Cs], April 18, 2021. http://arxiv.org/abs/2104.08821.

View File

@@ -1,57 +0,0 @@
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# coding=UTF-8
import numpy as np
import hnswlib
from paddlenlp.utils.log import logger
def build_index(args, data_loader, model):
index = hnswlib.Index(space="ip", dim=args.output_emb_size)
# Initializing index
# max_elements - the maximum number of elements (capacity). Will throw an exception if exceeded
# during insertion of an element.
# The capacity can be increased by saving/loading the index, see below.
#
# ef_construction - controls index search speed/build speed tradeoff
#
# M - is tightly connected with internal dimensionality of the data. Strongly affects memory consumption (~M)
# Higher M leads to higher accuracy/run_time at fixed ef/efConstruction
index.init_index(max_elements=args.hnsw_max_elements, ef_construction=args.hnsw_ef, M=args.hnsw_m)
# Controlling the recall by setting ef:
# higher ef leads to better accuracy, but slower search
index.set_ef(args.hnsw_ef)
# Set number of threads used during batch search/construction
# By default using all available cores
index.set_num_threads(16)
logger.info("start build index..........")
all_embeddings = []
for text_embeddings in model.get_semantic_embedding(data_loader):
all_embeddings.append(text_embeddings.numpy())
all_embeddings = np.concatenate(all_embeddings, axis=0)
index.add_items(all_embeddings)
logger.info("Total index number:{}".format(index.get_current_count()))
return index

Some files were not shown because too many files have changed in this diff Show More