pai_flow_operator_v5_2.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732
  1. # -*- coding: utf-8 -*-
  2. """PAI 广告模型更新工作流 v5_2(piaoquan_ad_rank_dnn_v15_2):训练用最近一个月,评估用最近一天。"""
  3. import functools
  4. import os
  5. import re
  6. import sys
  7. import time
  8. import json
  9. from alibabacloud_paistudio20210202.client import Client as PaiStudio20210202Client
  10. from alibabacloud_tea_openapi import models as open_api_models
  11. from alibabacloud_paistudio20210202 import models as pai_studio_20210202_models
  12. from alibabacloud_tea_util import models as util_models
  13. from alibabacloud_tea_util.client import Client as UtilClient
  14. from alibabacloud_eas20210701.client import Client as eas20210701Client
  15. from alibabacloud_paiflow20210202 import models as paiflow_20210202_models
  16. from alibabacloud_paiflow20210202.client import Client as PAIFlow20210202Client
  17. from datetime import datetime, timedelta
  18. from odps import ODPS
  19. from ad_monitor_util import _monitor
  20. import alibabacloud_oss_v2 as oss
  21. target_names = {
  22. '样本shuffle',
  23. '评估shuffle',
  24. '生成CID文件',
  25. '模型训练-样本shufle',
  26. '模型导出-2',
  27. '更新EAS服务(Beta)-1',
  28. '虚拟起始节点',
  29. '二分类评估-1',
  30. '二分类评估-2',
  31. '预测结果对比'
  32. }
  33. WORKFLOW_NAME = "piaoquan_ad_rank_dnn_v15_2"
  34. EXPERIMENT_ID = "draft-uf7vnc5h5wygurixam"
  35. ACCESS_KEY_ID = "LTAI5tFGqgC8f3mh1fRCrAEy"
  36. ACCESS_KEY_SECRET = "XhOjK9XmTYRhVAtf6yii4s4kZwWzvV"
  37. MAX_RETRIES = 3
  38. TRAIN_DAYS = 30
  39. EVAL_OFFSET_DAYS = 1
  40. ONLINE_SERVICE_NAME = 'ad_rank_dnn_v11_easyrec_v6'
  41. def retry(func):
  42. @functools.wraps(func)
  43. def wrapper(*args, **kwargs):
  44. retries = 0
  45. while retries < MAX_RETRIES:
  46. try:
  47. result = func(*args, **kwargs)
  48. if result is not False:
  49. return result
  50. except Exception as e:
  51. print(f"函数 {func.__name__} 执行时发生异常: {e},重试第 {retries + 1} 次")
  52. retries += 1
  53. print(f"函数 {func.__name__} 重试 {MAX_RETRIES} 次后仍失败。")
  54. return False
  55. return wrapper
  56. def get_odps_instance(project):
  57. odps = ODPS(
  58. access_id=ACCESS_KEY_ID,
  59. secret_access_key=ACCESS_KEY_SECRET,
  60. project=project,
  61. endpoint='http://service.cn.maxcompute.aliyun.com/api',
  62. )
  63. return odps
  64. def get_data_from_odps(project, table, num):
  65. odps = get_odps_instance(project)
  66. try:
  67. sql = f'select * from {table} limit {num}'
  68. with odps.execute_sql(sql).open_reader() as reader:
  69. df = reader.to_pandas()
  70. if len(df) < num:
  71. return None
  72. return df
  73. except Exception as e:
  74. print(f"发生错误: {e}")
  75. def get_dict_from_odps(project, table):
  76. odps = get_odps_instance(project)
  77. try:
  78. sql = f'select * from {table}'
  79. with odps.execute_sql(sql).open_reader() as reader:
  80. data = {}
  81. for record in reader:
  82. record_list = list(record)
  83. key = record_list[0][1]
  84. value = record_list[1][1]
  85. data[key] = value
  86. return data
  87. except Exception as e:
  88. print(f"发生错误: {e}")
  89. def load_holiday_dates():
  90. current_dir = os.getcwd()
  91. file_path = os.path.join(current_dir, 'ad', 'holidays.txt')
  92. try:
  93. with open(file_path, 'r', encoding='utf-8') as file:
  94. dates = set()
  95. for line in file:
  96. token = line.strip()
  97. if re.fullmatch(r'\d{8}', token):
  98. dates.add(token)
  99. return dates
  100. except FileNotFoundError:
  101. raise Exception(f"错误:未找到 {file_path} 文件。")
  102. except Exception as e:
  103. raise Exception(f"错误:读取节假日文件失败: {e}")
  104. def yyyymmdd_ago(days):
  105. return (datetime.now() - timedelta(days=days)).strftime('%Y%m%d')
  106. def get_eval_date():
  107. """评估日期:昨天 1 天。"""
  108. return yyyymmdd_ago(EVAL_OFFSET_DAYS)
  109. def get_eval_dates():
  110. """评估shuffle:昨天 1 天。"""
  111. dates = [get_eval_date()]
  112. print(f"v5_2 评估shuffle日期(1天): {dates}")
  113. return dates
  114. def get_train_dates():
  115. """样本shuffle:评估日(昨天)之前再往前取 TRAIN_DAYS 个非节假日,不与评估数据重叠。"""
  116. holidays = load_holiday_dates()
  117. dates = []
  118. offset = EVAL_OFFSET_DAYS + 1
  119. while len(dates) < TRAIN_DAYS:
  120. day = yyyymmdd_ago(offset)
  121. if day not in holidays:
  122. dates.append(day)
  123. offset += 1
  124. if offset > 120:
  125. raise Exception(f"无法凑齐 {TRAIN_DAYS} 天训练日期,请检查 holidays.txt")
  126. dates.sort()
  127. print(f"v5_2 样本shuffle日期({TRAIN_DAYS}天): {dates}")
  128. return dates
  129. def replace_sql_dt_in(sql, dates):
  130. """用指定日期列表替换 SQL 中第一次出现的 where dt in (...)。"""
  131. quoted = ','.join(f"'{d}'" for d in dates)
  132. marker = 'where dt in ('
  133. start_index = sql.find(marker)
  134. if start_index == -1:
  135. return None
  136. value_start = start_index + len(marker)
  137. value_end = sql.find(')', value_start)
  138. if value_end == -1:
  139. return None
  140. return sql[:value_start] + quoted + sql[value_end:]
  141. def is_created_today(time_str):
  142. time_obj = datetime.fromisoformat(time_str)
  143. today_start = datetime.combine(datetime.now().date(), datetime.min.time())
  144. return time_obj.timestamp() > today_start.timestamp()
  145. def replace_odps_table_arg(cmd, flag, table):
  146. odps_table = 'odps://pai_algo/tables/' + table
  147. marker = f'-D{flag}="'
  148. start_index = cmd.find(marker)
  149. if start_index == -1:
  150. return None
  151. value_start = start_index + len(marker)
  152. value_end = cmd.find('"', value_start)
  153. if value_end == -1:
  154. return None
  155. return cmd[:value_start] + odps_table + cmd[value_end:]
  156. class PAIClient:
  157. def __init__(self):
  158. pass
  159. @staticmethod
  160. def create_client() -> PaiStudio20210202Client:
  161. config = open_api_models.Config(
  162. access_key_id=ACCESS_KEY_ID,
  163. access_key_secret=ACCESS_KEY_SECRET
  164. )
  165. config.endpoint = f'pai.cn-hangzhou.aliyuncs.com'
  166. return PaiStudio20210202Client(config)
  167. @staticmethod
  168. def create_eas_client() -> eas20210701Client:
  169. config = open_api_models.Config(
  170. access_key_id=ACCESS_KEY_ID,
  171. access_key_secret=ACCESS_KEY_SECRET
  172. )
  173. config.endpoint = f'pai-eas.cn-hangzhou.aliyuncs.com'
  174. return eas20210701Client(config)
  175. @staticmethod
  176. def create_flow_client() -> PAIFlow20210202Client:
  177. config = open_api_models.Config(
  178. access_key_id=ACCESS_KEY_ID,
  179. access_key_secret=ACCESS_KEY_SECRET
  180. )
  181. config.endpoint = f'paiflow.cn-hangzhou.aliyuncs.com'
  182. return PAIFlow20210202Client(config)
  183. @staticmethod
  184. def get_work_flow_draft(experiment_id: str):
  185. client = PAIClient.create_client()
  186. runtime = util_models.RuntimeOptions()
  187. headers = {}
  188. try:
  189. resp = client.get_experiment_with_options(experiment_id, headers, runtime)
  190. return resp.body.to_map()
  191. except Exception as error:
  192. raise Exception(f"get_work_flow_draft error {error}")
  193. @staticmethod
  194. def get_describe_service(service_name: str):
  195. client = PAIClient.create_eas_client()
  196. runtime = util_models.RuntimeOptions()
  197. headers = {}
  198. try:
  199. resp = client.describe_service_with_options('cn-hangzhou', service_name, headers, runtime)
  200. return resp.body.to_map()
  201. except Exception as error:
  202. raise Exception(f"get_describe_service error {error}")
  203. @staticmethod
  204. def update_experiment_content(experiment_id: str, content: str, version: int):
  205. client = PAIClient.create_client()
  206. update_experiment_content_request = pai_studio_20210202_models.UpdateExperimentContentRequest(
  207. content=content, version=version)
  208. runtime = util_models.RuntimeOptions()
  209. headers = {}
  210. try:
  211. resp = client.update_experiment_content_with_options(
  212. experiment_id, update_experiment_content_request, headers, runtime)
  213. print(resp.body.to_map())
  214. except Exception as error:
  215. raise Exception(f"update_experiment_content error {error}")
  216. @staticmethod
  217. def create_job(experiment_id: str, node_id: str, execute_type: str):
  218. client = PAIClient.create_client()
  219. create_job_request = pai_studio_20210202_models.CreateJobRequest()
  220. create_job_request.experiment_id = experiment_id
  221. create_job_request.node_id = node_id
  222. create_job_request.execute_type = execute_type
  223. runtime = util_models.RuntimeOptions()
  224. headers = {}
  225. try:
  226. resp = client.create_job_with_options(create_job_request, headers, runtime)
  227. return resp.body.to_map()
  228. except Exception as error:
  229. raise Exception(f"create_job error {error}")
  230. @staticmethod
  231. def get_jobs_list(experiment_id: str, order='DESC'):
  232. client = PAIClient.create_client()
  233. list_jobs_request = pai_studio_20210202_models.ListJobsRequest(
  234. experiment_id=experiment_id,
  235. order=order
  236. )
  237. runtime = util_models.RuntimeOptions()
  238. headers = {}
  239. try:
  240. resp = client.list_jobs_with_options(list_jobs_request, headers, runtime)
  241. return resp.body.to_map()
  242. except Exception as error:
  243. raise Exception(f"get_jobs_list error {error}")
  244. @staticmethod
  245. def get_job_detail(job_id: str, verbose=False):
  246. client = PAIClient.create_client()
  247. get_job_request = pai_studio_20210202_models.GetJobRequest(
  248. verbose=verbose
  249. )
  250. runtime = util_models.RuntimeOptions()
  251. headers = {}
  252. try:
  253. resp = client.get_job_with_options(job_id, get_job_request, headers, runtime)
  254. return resp.body.to_map()
  255. except Exception as error:
  256. print(error.message)
  257. print(error.data.get("Recommend"))
  258. UtilClient.assert_as_string(error.message)
  259. @staticmethod
  260. def get_flow_out_put(pipeline_run_id: str, node_id: str, depth: int):
  261. client = PAIClient.create_flow_client()
  262. list_pipeline_run_node_outputs_request = paiflow_20210202_models.ListPipelineRunNodeOutputsRequest(
  263. depth=depth
  264. )
  265. runtime = util_models.RuntimeOptions()
  266. headers = {}
  267. try:
  268. resp = client.list_pipeline_run_node_outputs_with_options(
  269. pipeline_run_id, node_id, list_pipeline_run_node_outputs_request, headers, runtime)
  270. return resp.body.to_map()
  271. except Exception as error:
  272. print(error.message)
  273. print(error.data.get("Recommend"))
  274. UtilClient.assert_as_string(error.message)
  275. def extract_date_yyyymmdd(input_string):
  276. pattern = r'\d{8}'
  277. matches = re.findall(pattern, input_string)
  278. if matches:
  279. return matches[0]
  280. return None
  281. def get_online_model_config(service_name: str):
  282. model_config = {}
  283. model_detail = PAIClient.get_describe_service(service_name)
  284. service_config_str = model_detail['ServiceConfig']
  285. service_config = json.loads(service_config_str)
  286. model_path = service_config['model_path']
  287. model_config['model_path'] = model_path
  288. model_config['online_date'] = extract_date_yyyymmdd(model_path)
  289. return model_config
  290. def get_shuffle_output_table(node_name, node_dict, job_dict):
  291. job_id = job_dict[node_name]
  292. job_detail = wait_job_end(job_id)
  293. if job_detail['Status'] != 'Succeeded':
  294. return None
  295. flow_out_put_detail = PAIClient.get_flow_out_put(job_detail['RunId'], job_detail['PaiflowNodeId'], 2)
  296. outputs = flow_out_put_detail['Outputs']
  297. for output in outputs:
  298. if output["Producer"] == node_dict[node_name] and output["Name"] == "outputTable":
  299. value = json.loads(output["Info"]['value'])
  300. table = value['location']['table']
  301. print(f"{node_name} outputTable: {table}")
  302. return table
  303. return None
  304. def bind_shuffle_tables(train_table, eval_table):
  305. draft = PAIClient.get_work_flow_draft(EXPERIMENT_ID)
  306. print(json.dumps(draft, ensure_ascii=False))
  307. content = draft['Content']
  308. version = draft['Version']
  309. content_json = json.loads(content)
  310. nodes = content_json.get('nodes')
  311. predict_node_names = {'模型预测', '线上模型预测'}
  312. for node in nodes:
  313. name = node['name']
  314. for property in node['properties']:
  315. if property['name'] != 'sql':
  316. continue
  317. cmd = property['value']
  318. if name == '模型训练-样本shufle':
  319. new_cmd = replace_odps_table_arg(cmd, 'train_tables', train_table)
  320. if new_cmd is None:
  321. print("replace Dtrain_tables error")
  322. new_cmd = cmd
  323. new_cmd = replace_odps_table_arg(new_cmd, 'eval_tables', eval_table)
  324. if new_cmd is None:
  325. print("replace Deval_tables error")
  326. property['value'] = new_cmd
  327. elif name in predict_node_names:
  328. new_cmd = replace_odps_table_arg(cmd, 'input_table', train_table)
  329. if new_cmd is None:
  330. print(f"replace Dinput_table error for {name}")
  331. else:
  332. property['value'] = new_cmd
  333. print(f"{name} Dinput_table -> {train_table}")
  334. new_content = json.dumps(content_json, ensure_ascii=False)
  335. PAIClient.update_experiment_content(EXPERIMENT_ID, new_content, version)
  336. def wait_job_end(job_id: str, check_interval=300):
  337. while True:
  338. job_detail = PAIClient.get_job_detail(job_id)
  339. print(job_detail)
  340. statue = job_detail['Status']
  341. if (statue == 'Initialized' or statue == 'Starting' or statue == 'WorkflowServiceStarting'
  342. or statue == 'Running' or statue == 'ReadyToSchedule'):
  343. time.sleep(check_interval)
  344. continue
  345. if statue == 'Failed' or statue == 'Terminating' or statue == 'Unknown' or statue == 'Skipped' or statue == 'Succeeded':
  346. return job_detail
  347. def get_node_dict():
  348. draft = PAIClient.get_work_flow_draft(EXPERIMENT_ID)
  349. content = draft['Content']
  350. content_json = json.loads(content)
  351. nodes = content_json.get('nodes')
  352. node_dict = {}
  353. for node in nodes:
  354. name = node['name']
  355. if name in target_names:
  356. node_dict[name] = node['id']
  357. return node_dict
  358. def get_job_dict():
  359. job_dict = {}
  360. jobs_list = PAIClient.get_jobs_list(EXPERIMENT_ID)
  361. for job in jobs_list['Jobs']:
  362. if not is_created_today(job['GmtCreateTime']):
  363. break
  364. job_id = job['JobId']
  365. job_detail = PAIClient.get_job_detail(job_id, verbose=True)
  366. for name in target_names:
  367. if job_detail['Status'] != 'Succeeded':
  368. continue
  369. if name in job_dict:
  370. continue
  371. if name in job_detail['RunInfo']:
  372. job_dict[name] = job_detail['JobId']
  373. return job_dict
  374. @retry
  375. def update_online_flow():
  376. try:
  377. online_model_config = get_online_model_config(ONLINE_SERVICE_NAME)
  378. draft = PAIClient.get_work_flow_draft(EXPERIMENT_ID)
  379. print(json.dumps(draft, ensure_ascii=False))
  380. content = draft['Content']
  381. version = draft['Version']
  382. print(content)
  383. content_json = json.loads(content)
  384. nodes = content_json.get('nodes')
  385. global_params = content_json.get('globalParams')
  386. eval_date = get_eval_date()
  387. train_dates = get_train_dates()
  388. eval_dates = get_eval_dates()
  389. for global_param in global_params:
  390. try:
  391. if global_param['name'] == 'bizdate':
  392. global_param['value'] = eval_date
  393. if global_param['name'] == 'online_version_dt':
  394. global_param['value'] = online_model_config['online_date']
  395. if global_param['name'] == 'eval_date':
  396. global_param['value'] = eval_date
  397. if global_param['name'] == 'online_model_path':
  398. global_param['value'] = online_model_config['model_path']
  399. except KeyError:
  400. raise Exception("在处理全局参数时,字典中缺少必要的键")
  401. shuffle_dates = {
  402. '样本shuffle': train_dates,
  403. '评估shuffle': eval_dates,
  404. }
  405. for node in nodes:
  406. try:
  407. if node['name'] not in shuffle_dates:
  408. continue
  409. for property in node['properties']:
  410. if property['name'] != 'sql':
  411. continue
  412. new_value = replace_sql_dt_in(property['value'], shuffle_dates[node['name']])
  413. if new_value is None:
  414. print(f"error replace dt for {node['name']}")
  415. property['value'] = new_value
  416. except KeyError:
  417. raise Exception("在处理节点属性时,字典中缺少必要的键")
  418. new_content = json.dumps(content_json, ensure_ascii=False)
  419. PAIClient.update_experiment_content(EXPERIMENT_ID, new_content, version)
  420. return True
  421. except json.JSONDecodeError:
  422. raise Exception("JSON 解析错误,可能是草稿内容格式不正确")
  423. except Exception as e:
  424. raise Exception(f"发生未知错误: {e}")
  425. @retry
  426. def shuffle_table():
  427. try:
  428. node_dict = get_node_dict()
  429. if '生成CID文件' not in node_dict:
  430. raise Exception("工作流中未找到节点 生成CID文件")
  431. train_res = PAIClient.create_job(EXPERIMENT_ID, node_dict['样本shuffle'], 'EXECUTE_FROM_HERE')
  432. eval_res = PAIClient.create_job(EXPERIMENT_ID, node_dict['评估shuffle'], 'EXECUTE_ONE')
  433. train_job_detail = wait_job_end(train_res['JobId'], 10)
  434. eval_job_detail = wait_job_end(eval_res['JobId'], 10)
  435. if train_job_detail['Status'] != 'Succeeded' or eval_job_detail['Status'] != 'Succeeded':
  436. return False
  437. job_verbose = PAIClient.get_job_detail(train_res['JobId'], verbose=True)
  438. run_info = job_verbose.get('RunInfo') or ''
  439. if '生成CID文件' not in run_info:
  440. print(f"样本shuffle 未带上生成CID文件, RunInfo={run_info}")
  441. return False
  442. print("样本shuffle 已触发生成CID文件")
  443. return True
  444. except Exception as e:
  445. error_message = f"在执行 shuffle_table 函数时发生异常: {str(e)}"
  446. print(error_message)
  447. raise Exception(error_message)
  448. @retry
  449. def shuffle_train_model():
  450. try:
  451. node_dict = get_node_dict()
  452. job_dict = get_job_dict()
  453. train_table = get_shuffle_output_table('样本shuffle', node_dict, job_dict)
  454. eval_table = get_shuffle_output_table('评估shuffle', node_dict, job_dict)
  455. if train_table is None or eval_table is None:
  456. print(f"shuffle 输出表缺失 train_table={train_table}, eval_table={eval_table}")
  457. return False
  458. bind_shuffle_tables(train_table, eval_table)
  459. node_dict = get_node_dict()
  460. train_node_id = node_dict['模型训练-样本shufle']
  461. execute_type = 'EXECUTE_ONE'
  462. train_res = PAIClient.create_job(EXPERIMENT_ID, train_node_id, execute_type)
  463. train_job_id = train_res['JobId']
  464. train_job_detail = wait_job_end(train_job_id)
  465. if train_job_detail['Status'] == 'Succeeded':
  466. return True
  467. return False
  468. except Exception as e:
  469. error_message = f"在执行 shuffle_train_model 函数时发生异常: {str(e)}"
  470. print(error_message)
  471. raise Exception(error_message)
  472. @retry
  473. def export_model():
  474. try:
  475. node_dict = get_node_dict()
  476. export_node_id = node_dict['模型导出-2']
  477. execute_type = 'EXECUTE_ONE'
  478. export_res = PAIClient.create_job(EXPERIMENT_ID, export_node_id, execute_type)
  479. export_job_id = export_res['JobId']
  480. export_job_detail = wait_job_end(export_job_id)
  481. if export_job_detail['Status'] == 'Succeeded':
  482. return True
  483. return False
  484. except Exception as e:
  485. error_message = f"在执行 export_model 函数时发生异常: {str(e)}"
  486. print(error_message)
  487. raise Exception(error_message)
  488. def update_online_model():
  489. try:
  490. node_dict = get_node_dict()
  491. train_node_id = node_dict['更新EAS服务(Beta)-1']
  492. execute_type = 'EXECUTE_ONE'
  493. train_res = PAIClient.create_job(EXPERIMENT_ID, train_node_id, execute_type)
  494. train_job_id = train_res['JobId']
  495. train_job_detail = wait_job_end(train_job_id)
  496. if train_job_detail['Status'] == 'Succeeded':
  497. return True
  498. return False
  499. except Exception as e:
  500. error_message = f"在执行 update_online_model 函数时发生异常: {str(e)}"
  501. print(error_message)
  502. raise Exception(error_message)
  503. @retry
  504. def get_validate_model_data():
  505. try:
  506. node_dict = get_node_dict()
  507. train_node_id = node_dict['虚拟起始节点']
  508. execute_type = 'EXECUTE_FROM_HERE'
  509. validate_res = PAIClient.create_job(EXPERIMENT_ID, train_node_id, execute_type)
  510. validate_job_id = validate_res['JobId']
  511. validate_job_detail = wait_job_end(validate_job_id)
  512. if validate_job_detail['Status'] == 'Succeeded':
  513. return True
  514. return False
  515. except Exception as e:
  516. error_message = f"在执行 get_validate_model_data 函数时出现异常: {e}"
  517. print(error_message)
  518. raise Exception(error_message)
  519. def validate_model_data_accuracy():
  520. try:
  521. table_dict = {}
  522. node_dict = get_node_dict()
  523. job_dict = get_job_dict()
  524. job_id = job_dict['虚拟起始节点']
  525. validate_job_detail = wait_job_end(job_id)
  526. if validate_job_detail['Status'] == 'Succeeded':
  527. pipeline_run_id = validate_job_detail['RunId']
  528. node_id = validate_job_detail['PaiflowNodeId']
  529. flow_out_put_detail = PAIClient.get_flow_out_put(pipeline_run_id, node_id, 3)
  530. print(flow_out_put_detail)
  531. outputs = flow_out_put_detail['Outputs']
  532. for output in outputs:
  533. if output["Producer"] == node_dict['二分类评估-1'] and output["Name"] == "outputMetricTable":
  534. value1 = json.loads(output["Info"]['value'])
  535. table_dict['二分类评估-1'] = value1['location']['table']
  536. if output["Producer"] == node_dict['二分类评估-2'] and output["Name"] == "outputMetricTable":
  537. value2 = json.loads(output["Info"]['value'])
  538. table_dict['二分类评估-2'] = value2['location']['table']
  539. if output["Producer"] == node_dict['预测结果对比'] and output["Name"] == "outputTable":
  540. value3 = json.loads(output["Info"]['value'])
  541. table_dict['预测结果对比'] = value3['location']['table']
  542. num = 10
  543. df = get_data_from_odps('pai_algo', table_dict['预测结果对比'], 10)
  544. old_abs_avg = df['old_error'].abs().sum() / num
  545. new_abs_avg = df['new_error'].abs().sum() / num
  546. new_auc = get_dict_from_odps('pai_algo', table_dict['二分类评估-1'])['AUC']
  547. old_auc = get_dict_from_odps('pai_algo', table_dict['二分类评估-2'])['AUC']
  548. eval_date = get_eval_date()
  549. score_diff = abs(old_abs_avg - new_abs_avg)
  550. msg = ""
  551. result = False
  552. if new_abs_avg > 0.1:
  553. msg += f'{WORKFLOW_NAME}线上模型评估{eval_date}的数据,绝对误差大于0.1,请检查'
  554. level = 'error'
  555. elif score_diff > 0.02 and new_abs_avg - old_abs_avg > 0.02:
  556. msg += f'{WORKFLOW_NAME}两个模型评估{eval_date}的数据,两个模型分数差异为: {score_diff}, 大于0.02, 请检查'
  557. level = 'error'
  558. else:
  559. msg += f'{WORKFLOW_NAME}广告模型更新完成(训练30天/评估1天)'
  560. level = 'info'
  561. result = True
  562. top10_msg = "| CID | 老模型相对真实CTCVR的变化 | 新模型相对真实CTCVR的变化 |"
  563. top10_msg += "\n| ---- | --------- | -------- |"
  564. for index, row in df.iterrows():
  565. cid = row['cid']
  566. old_error = row['old_error']
  567. new_error = row['new_error']
  568. top10_msg += f"\n| {int(cid)} | {old_error} | {new_error} | "
  569. print(top10_msg)
  570. msg += f"\n\t - 老模型AUC: {old_auc}"
  571. msg += f"\n\t - 新模型AUC: {new_auc}"
  572. msg += f"\n\t - 老模型Top10差异平均值: {old_abs_avg}"
  573. msg += f"\n\t - 新模型Top10差异平均值: {new_abs_avg}"
  574. return result, msg, level, top10_msg
  575. except Exception as e:
  576. error_message = f"在执行 validate_model_data_accuracy 函数时出现异常: {str(e)}"
  577. print(error_message)
  578. raise Exception(error_message)
  579. def update_trained_cids_pointer(model_name=None, dt_version=None):
  580. if not model_name and not dt_version:
  581. draft = PAIClient.get_work_flow_draft(EXPERIMENT_ID)
  582. content = draft['Content']
  583. content_json = json.loads(content)
  584. global_params = content_json.get('globalParams', [])
  585. model_name = None
  586. dt_version = None
  587. for param in global_params:
  588. if param.get('name') == 'model_name':
  589. model_name = param.get('value')
  590. if param.get('name') == 'bizdate':
  591. dt_version = param.get('value')
  592. if not model_name or not dt_version:
  593. raise Exception("globalParams 中未找到 model_name 或 bizdate")
  594. elif not (model_name and dt_version):
  595. raise Exception("model_name 和 dt_version 必须同时提供")
  596. model_version = {}
  597. model_version['modelName'] = f"model_name={model_name}"
  598. model_version['dtVersion'] = f"dt_version={dt_version}"
  599. model_version['timestamp'] = int(time.time())
  600. print(json.dumps(model_version, ensure_ascii=False, indent=4).encode('utf-8'))
  601. bucket_name = "art-recommend"
  602. object_key = "fengzhoutian/pai_model_trained_cids/model_version_v5_2.json"
  603. oss_config = oss.config.load_default()
  604. oss_config.credentials_provider = oss.credentials.StaticCredentialsProvider(
  605. access_key_id=ACCESS_KEY_ID, access_key_secret=ACCESS_KEY_SECRET
  606. )
  607. oss_config.region = "cn-hangzhou"
  608. client = oss.Client(oss_config)
  609. ret = client.put_object(oss.PutObjectRequest(
  610. bucket=bucket_name,
  611. key=object_key,
  612. body=json.dumps(model_version, ensure_ascii=False, indent=4).encode('utf-8')
  613. ))
  614. print(f'oss put status code: {ret.status_code},'
  615. f' request id: {ret.request_id},'
  616. f' content md5: {ret.content_md5},'
  617. f' etag: {ret.etag},'
  618. f' hash crc64: {ret.hash_crc64},'
  619. f' version id: {ret.version_id},'
  620. f' content: {model_version}'
  621. )
  622. if __name__ == '__main__':
  623. start_time = int(time.time())
  624. functions = [update_online_flow, shuffle_table, shuffle_train_model, export_model, get_validate_model_data]
  625. function_names = [func.__name__ for func in functions]
  626. start_function = None
  627. if len(sys.argv) > 1:
  628. start_function = sys.argv[1]
  629. if start_function not in function_names:
  630. print(f"指定的起始函数 {start_function} 不存在,请选择以下函数之一:{', '.join(function_names)}")
  631. sys.exit(1)
  632. start_index = 0
  633. if start_function:
  634. start_index = function_names.index(start_function)
  635. for func in functions[start_index:]:
  636. if not func():
  637. print(f"{func.__name__} 执行失败,后续函数不再执行。")
  638. step_end_time = int(time.time())
  639. elapsed = step_end_time - start_time
  640. _monitor('error', f"{WORKFLOW_NAME}模型更新,{func.__name__} 执行失败,后续函数不再执行,请检查", start_time, elapsed, None)
  641. break
  642. else:
  643. print("所有函数都成功执行,可以继续下一步操作。")
  644. result, msg, level, top10_msg = validate_model_data_accuracy()
  645. if result:
  646. update_online_res = update_online_model()
  647. if update_online_res:
  648. update_trained_cids_pointer()
  649. print("success")
  650. step_end_time = int(time.time())
  651. elapsed = step_end_time - start_time
  652. print(level, msg, start_time, elapsed, top10_msg)
  653. _monitor(level, msg, start_time, elapsed, top10_msg)