pai_flow_operator.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. # -*- coding: utf-8 -*-
  2. import functools
  3. import os
  4. import re
  5. import sys
  6. import time
  7. import json
  8. import pandas as pd
  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 re
  21. target_names = {
  22. '样本shuffle',
  23. '评估样本重组',
  24. '模型训练-样本shufle',
  25. '模型训练-自定义',
  26. '模型增量训练',
  27. '模型导出-2',
  28. '更新EAS服务(Beta)-1',
  29. '虚拟起始节点',
  30. '二分类评估-1',
  31. '二分类评估-2',
  32. '预测结果对比'
  33. }
  34. experiment_id = "draft-wqgkag89sbh9v1zvut"
  35. MAX_RETRIES = 3
  36. def retry(func):
  37. @functools.wraps(func)
  38. def wrapper(*args, **kwargs):
  39. retries = 0
  40. while retries < MAX_RETRIES:
  41. try:
  42. result = func(*args, **kwargs)
  43. if result is not False:
  44. return result
  45. except Exception as e:
  46. print(f"函数 {func.__name__} 执行时发生异常: {e},重试第 {retries + 1} 次")
  47. retries += 1
  48. print(f"函数 {func.__name__} 重试 {MAX_RETRIES} 次后仍失败。")
  49. return False
  50. return wrapper
  51. def get_odps_instance(project):
  52. odps = ODPS(
  53. access_id='LTAIWYUujJAm7CbH',
  54. secret_access_key='RfSjdiWwED1sGFlsjXv0DlfTnZTG1P',
  55. project=project,
  56. endpoint='http://service.cn.maxcompute.aliyun.com/api',
  57. )
  58. return odps
  59. def get_data_from_odps(project, table, num):
  60. odps = get_odps_instance(project)
  61. try:
  62. # 要查询的 SQL 语句
  63. sql = f'select * from {table} limit {num}'
  64. # 执行 SQL 查询
  65. with odps.execute_sql(sql).open_reader() as reader:
  66. df = reader.to_pandas()
  67. # 查询数量小于目标数量时 返回空
  68. if len(df) < num:
  69. return None
  70. return df
  71. except Exception as e:
  72. print(f"发生错误: {e}")
  73. def get_dict_from_odps(project, table):
  74. odps = get_odps_instance(project)
  75. try:
  76. # 要查询的 SQL 语句
  77. sql = f'select * from {table}'
  78. # 执行 SQL 查询
  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 get_dates_between(start_date_str, end_date_str):
  90. start_date = datetime.strptime(start_date_str, '%Y%m%d')
  91. end_date = datetime.strptime(end_date_str, '%Y%m%d')
  92. dates = []
  93. current_date = start_date
  94. while current_date <= end_date:
  95. dates.append(current_date.strftime('%Y%m%d'))
  96. current_date += timedelta(days=1)
  97. return dates
  98. def read_file_to_list():
  99. try:
  100. current_dir = os.getcwd()
  101. file_path = os.path.join(current_dir, 'ad', 'holidays.txt')
  102. with open(file_path, 'r', encoding='utf-8') as file:
  103. content = file.read()
  104. return content.split('\n')
  105. except FileNotFoundError:
  106. raise Exception(f"错误:未找到 {file_path} 文件。")
  107. except Exception as e:
  108. raise Exception(f"错误:发生了一个未知错误: {e}")
  109. return []
  110. def get_previous_days_date(days):
  111. current_date = datetime.now()
  112. previous_date = current_date - timedelta(days=days)
  113. return previous_date.strftime('%Y%m%d')
  114. def remove_elements(lst1, lst2):
  115. return [element for element in lst1 if element not in lst2]
  116. def process_list(lst, append_str):
  117. # 给列表中每个元素拼接相同的字符串
  118. appended_list = [append_str + element for element in lst]
  119. # 将拼接后的列表元素用逗号拼接成一个字符串
  120. result_str = ','.join(appended_list)
  121. return result_str
  122. def get_train_data_list(date_begin):
  123. end_date = get_previous_days_date(2)
  124. date_list = get_dates_between(date_begin, end_date)
  125. filter_date_list = read_file_to_list()
  126. date_list = remove_elements(date_list, filter_date_list)
  127. return date_list
  128. def update_data_date_range(old_str, date_begin='20250320'):
  129. date_list = get_train_data_list(date_begin)
  130. train_list = ["'" + item + "'" for item in date_list]
  131. result = f"in ({','.join(train_list)})"
  132. pattern = r"in\s*\(\s*'[^']+'\s*(?:,\s*'[^']+'\s*)*\)"
  133. new_value = re.sub(pattern, result, old_str, flags=re.IGNORECASE)
  134. return new_value
  135. def compare_timestamp_with_today_start(time_str):
  136. # 解析时间字符串为 datetime 对象
  137. time_obj = datetime.fromisoformat(time_str)
  138. # 将其转换为时间戳
  139. target_timestamp = time_obj.timestamp()
  140. # 获取今天开始的时间
  141. today_start = datetime.combine(datetime.now().date(), datetime.min.time())
  142. # 将今天开始时间转换为时间戳
  143. today_start_timestamp = today_start.timestamp()
  144. return target_timestamp > today_start_timestamp
  145. def update_train_table(old_str, table):
  146. address = 'odps://pai_algo/tables/'
  147. train_table = address + table
  148. start_index = old_str.find('-Dtrain_tables="')
  149. if start_index != -1:
  150. # 确定等号的位置
  151. equal_sign_index = start_index + len('-Dtrain_tables="')
  152. # 找到下一个双引号的位置
  153. next_quote_index = old_str.find('"', equal_sign_index)
  154. if next_quote_index != -1:
  155. # 进行替换
  156. new_value = old_str[:equal_sign_index] + train_table + old_str[next_quote_index:]
  157. return new_value
  158. return None
  159. class PAIClient:
  160. def __init__(self):
  161. pass
  162. @staticmethod
  163. def create_client() -> PaiStudio20210202Client:
  164. """
  165. 使用AK&SK初始化账号Client
  166. @return: Client
  167. @throws Exception
  168. """
  169. # 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
  170. # 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
  171. config = open_api_models.Config(
  172. access_key_id="LTAI5tFGqgC8f3mh1fRCrAEy",
  173. access_key_secret="XhOjK9XmTYRhVAtf6yii4s4kZwWzvV"
  174. )
  175. # Endpoint 请参考 https://api.aliyun.com/product/PaiStudio
  176. config.endpoint = f'pai.cn-hangzhou.aliyuncs.com'
  177. return PaiStudio20210202Client(config)
  178. @staticmethod
  179. def create_eas_client() -> eas20210701Client:
  180. """
  181. 使用AK&SK初始化账号Client
  182. @return: Client
  183. @throws Exception
  184. """
  185. # 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
  186. # 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
  187. config = open_api_models.Config(
  188. access_key_id="LTAI5tFGqgC8f3mh1fRCrAEy",
  189. access_key_secret="XhOjK9XmTYRhVAtf6yii4s4kZwWzvV"
  190. )
  191. # Endpoint 请参考 https://api.aliyun.com/product/PaiStudio
  192. config.endpoint = f'pai-eas.cn-hangzhou.aliyuncs.com'
  193. return eas20210701Client(config)
  194. @staticmethod
  195. def create_flow_client() -> PAIFlow20210202Client:
  196. """
  197. 使用AK&SK初始化账号Client
  198. @return: Client
  199. @throws Exception
  200. """
  201. # 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
  202. # 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html。
  203. config = open_api_models.Config(
  204. # 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。,
  205. access_key_id="LTAI5tFGqgC8f3mh1fRCrAEy",
  206. # 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。,
  207. access_key_secret="XhOjK9XmTYRhVAtf6yii4s4kZwWzvV"
  208. )
  209. # Endpoint 请参考 https://api.aliyun.com/product/PAIFlow
  210. config.endpoint = f'paiflow.cn-hangzhou.aliyuncs.com'
  211. return PAIFlow20210202Client(config)
  212. @staticmethod
  213. def get_work_flow_draft_list(workspace_id: str):
  214. client = PAIClient.create_client()
  215. list_experiments_request = pai_studio_20210202_models.ListExperimentsRequest(
  216. workspace_id=workspace_id
  217. )
  218. runtime = util_models.RuntimeOptions()
  219. headers = {}
  220. try:
  221. resp = client.list_experiments_with_options(list_experiments_request, headers, runtime)
  222. return resp.body.to_map()
  223. except Exception as error:
  224. raise Exception(f"get_work_flow_draft_list error {error}")
  225. @staticmethod
  226. def get_work_flow_draft(experiment_id: str):
  227. client = PAIClient.create_client()
  228. runtime = util_models.RuntimeOptions()
  229. headers = {}
  230. try:
  231. # 复制代码运行请自行打印 API 的返回值
  232. resp = client.get_experiment_with_options(experiment_id, headers, runtime)
  233. return resp.body.to_map()
  234. except Exception as error:
  235. raise Exception(f"get_work_flow_draft error {error}")
  236. @staticmethod
  237. def get_describe_service(service_name: str):
  238. client = PAIClient.create_eas_client()
  239. runtime = util_models.RuntimeOptions()
  240. headers = {}
  241. try:
  242. # 复制代码运行请自行打印 API 的返回值
  243. resp = client.describe_service_with_options('cn-hangzhou', service_name, headers, runtime)
  244. return resp.body.to_map()
  245. except Exception as error:
  246. raise Exception(f"get_describe_service error {error}")
  247. @staticmethod
  248. def update_experiment_content(experiment_id: str, content: str, version: int):
  249. client = PAIClient.create_client()
  250. update_experiment_content_request = pai_studio_20210202_models.UpdateExperimentContentRequest(content=content,
  251. version=version)
  252. runtime = util_models.RuntimeOptions()
  253. headers = {}
  254. try:
  255. # 复制代码运行请自行打印 API 的返回值
  256. resp = client.update_experiment_content_with_options(experiment_id, update_experiment_content_request,
  257. headers, runtime)
  258. print(resp.body.to_map())
  259. except Exception as error:
  260. raise Exception(f"update_experiment_content error {error}")
  261. @staticmethod
  262. def create_job(experiment_id: str, node_id: str, execute_type: str):
  263. client = PAIClient.create_client()
  264. create_job_request = pai_studio_20210202_models.CreateJobRequest()
  265. create_job_request.experiment_id = experiment_id
  266. create_job_request.node_id = node_id
  267. create_job_request.execute_type = execute_type
  268. runtime = util_models.RuntimeOptions()
  269. headers = {}
  270. try:
  271. # 复制代码运行请自行打印 API 的返回值
  272. resp = client.create_job_with_options(create_job_request, headers, runtime)
  273. return resp.body.to_map()
  274. except Exception as error:
  275. raise Exception(f"create_job error {error}")
  276. @staticmethod
  277. def get_jobs_list(experiment_id: str, order='DESC'):
  278. client = PAIClient.create_client()
  279. list_jobs_request = pai_studio_20210202_models.ListJobsRequest(
  280. experiment_id=experiment_id,
  281. order=order
  282. )
  283. runtime = util_models.RuntimeOptions()
  284. headers = {}
  285. try:
  286. # 复制代码运行请自行打印 API 的返回值
  287. resp = client.list_jobs_with_options(list_jobs_request, headers, runtime)
  288. return resp.body.to_map()
  289. except Exception as error:
  290. raise Exception(f"get_jobs_list error {error}")
  291. @staticmethod
  292. def get_job_detail(job_id: str, verbose=False):
  293. client = PAIClient.create_client()
  294. get_job_request = pai_studio_20210202_models.GetJobRequest(
  295. verbose=verbose
  296. )
  297. runtime = util_models.RuntimeOptions()
  298. headers = {}
  299. try:
  300. # 复制代码运行请自行打印 API 的返回值
  301. resp = client.get_job_with_options(job_id, get_job_request, headers, runtime)
  302. return resp.body.to_map()
  303. except Exception as error:
  304. # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  305. # 错误 message
  306. print(error.message)
  307. # 诊断地址
  308. print(error.data.get("Recommend"))
  309. UtilClient.assert_as_string(error.message)
  310. @staticmethod
  311. def get_flow_out_put(pipeline_run_id: str, node_id: str, depth: int):
  312. client = PAIClient.create_flow_client()
  313. list_pipeline_run_node_outputs_request = paiflow_20210202_models.ListPipelineRunNodeOutputsRequest(
  314. depth=depth
  315. )
  316. runtime = util_models.RuntimeOptions()
  317. headers = {}
  318. try:
  319. # 复制代码运行请自行打印 API 的返回值
  320. resp = client.list_pipeline_run_node_outputs_with_options(pipeline_run_id, node_id,
  321. list_pipeline_run_node_outputs_request, headers,
  322. runtime)
  323. return resp.body.to_map()
  324. except Exception as error:
  325. # 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
  326. # 错误 message
  327. print(error.message)
  328. # 诊断地址
  329. print(error.data.get("Recommend"))
  330. UtilClient.assert_as_string(error.message)
  331. def extract_date_yyyymmdd(input_string):
  332. pattern = r'\d{8}'
  333. matches = re.findall(pattern, input_string)
  334. if matches:
  335. return matches[0]
  336. return None
  337. def get_online_model_config(service_name: str):
  338. model_config = {}
  339. model_detail = PAIClient.get_describe_service(service_name)
  340. service_config_str = model_detail['ServiceConfig']
  341. service_config = json.loads(service_config_str)
  342. model_path = service_config['model_path']
  343. model_config['model_path'] = model_path
  344. online_date = extract_date_yyyymmdd(model_path)
  345. model_config['online_date'] = online_date
  346. return model_config
  347. def update_shuffle_flow(table):
  348. draft = PAIClient.get_work_flow_draft(experiment_id)
  349. print(json.dumps(draft, ensure_ascii=False))
  350. content = draft['Content']
  351. version = draft['Version']
  352. content_json = json.loads(content)
  353. nodes = content_json.get('nodes')
  354. for node in nodes:
  355. name = node['name']
  356. if name == '模型训练-样本shufle':
  357. properties = node['properties']
  358. for property in properties:
  359. if property['name'] == 'sql':
  360. value = property['value']
  361. new_value = update_train_table(value, table)
  362. if new_value is None:
  363. print("error")
  364. property['value'] = new_value
  365. new_content = json.dumps(content_json, ensure_ascii=False)
  366. PAIClient.update_experiment_content(experiment_id, new_content, version)
  367. def update_shuffle_flow_1():
  368. draft = PAIClient.get_work_flow_draft(experiment_id)
  369. print(json.dumps(draft, ensure_ascii=False))
  370. content = draft['Content']
  371. version = draft['Version']
  372. print(content)
  373. content_json = json.loads(content)
  374. nodes = content_json.get('nodes')
  375. for node in nodes:
  376. name = node['name']
  377. if name == '模型训练-样本shufle':
  378. properties = node['properties']
  379. for property in properties:
  380. if property['name'] == 'sql':
  381. value = property['value']
  382. new_value = update_data_date_range(value)
  383. if new_value is None:
  384. print("error")
  385. property['value'] = new_value
  386. new_content = json.dumps(content_json, ensure_ascii=False)
  387. PAIClient.update_experiment_content(experiment_id, new_content, version)
  388. def wait_job_end(job_id: str, check_interval=300):
  389. while True:
  390. job_detail = PAIClient.get_job_detail(job_id)
  391. print(job_detail)
  392. statue = job_detail['Status']
  393. # Initialized: 初始化完成 Starting:开始 WorkflowServiceStarting:准备提交 Running:运行中 ReadyToSchedule:准备运行(前序节点未完成导致)
  394. if (statue == 'Initialized' or statue == 'Starting' or statue == 'WorkflowServiceStarting'
  395. or statue == 'Running' or statue == 'ReadyToSchedule'):
  396. time.sleep(check_interval)
  397. continue
  398. # Failed:运行失败 Terminating:终止中 Terminated:已终止 Unknown:未知 Skipped:跳过(前序节点失败导致) Succeeded:运行成功
  399. if statue == 'Failed' or statue == 'Terminating' or statue == 'Unknown' or statue == 'Skipped' or statue == 'Succeeded':
  400. return job_detail
  401. def get_node_dict():
  402. draft = PAIClient.get_work_flow_draft(experiment_id)
  403. content = draft['Content']
  404. content_json = json.loads(content)
  405. nodes = content_json.get('nodes')
  406. node_dict = {}
  407. for node in nodes:
  408. name = node['name']
  409. # 检查名称是否在目标名称集合中
  410. if name in target_names:
  411. node_dict[name] = node['id']
  412. return node_dict
  413. def get_job_dict():
  414. job_dict = {}
  415. jobs_list = PAIClient.get_jobs_list(experiment_id)
  416. for job in jobs_list['Jobs']:
  417. # 解析时间字符串为 datetime 对象
  418. if not compare_timestamp_with_today_start(job['GmtCreateTime']):
  419. break
  420. job_id = job['JobId']
  421. job_detail = PAIClient.get_job_detail(job_id, verbose=True)
  422. for name in target_names:
  423. if job_detail['Status'] != 'Succeeded':
  424. continue
  425. if name in job_dict:
  426. continue
  427. if name in job_detail['RunInfo']:
  428. job_dict[name] = job_detail['JobId']
  429. return job_dict
  430. @retry
  431. def update_online_flow():
  432. try:
  433. online_model_config = get_online_model_config('ad_rank_dnn_v11_easyrec')
  434. draft = PAIClient.get_work_flow_draft(experiment_id)
  435. print(json.dumps(draft, ensure_ascii=False))
  436. content = draft['Content']
  437. version = draft['Version']
  438. print(content)
  439. content_json = json.loads(content)
  440. nodes = content_json.get('nodes')
  441. global_params = content_json.get('globalParams')
  442. bizdate = get_previous_days_date(1)
  443. for global_param in global_params:
  444. try:
  445. if global_param['name'] == 'bizdate':
  446. global_param['value'] = bizdate
  447. if global_param['name'] == 'online_version_dt':
  448. global_param['value'] = online_model_config['online_date']
  449. if global_param['name'] == 'eval_date':
  450. global_param['value'] = bizdate
  451. if global_param['name'] == 'online_model_path':
  452. global_param['value'] = online_model_config['model_path']
  453. except KeyError:
  454. raise Exception("在处理全局参数时,字典中缺少必要的键")
  455. for node in nodes:
  456. try:
  457. name = node['name']
  458. if name in ('样本shuffle', '评估样本重组'):
  459. date_begin = '20250320' if name == '样本shuffle' else get_previous_days_date(10)
  460. properties = node['properties']
  461. for property in properties:
  462. if property['name'] == 'sql':
  463. value = property['value']
  464. new_value = update_data_date_range(value, date_begin)
  465. if new_value is None:
  466. print("error")
  467. property['value'] = new_value
  468. except KeyError:
  469. raise Exception("在处理节点属性时,字典中缺少必要的键")
  470. new_content = json.dumps(content_json, ensure_ascii=False)
  471. PAIClient.update_experiment_content(experiment_id, new_content, version)
  472. return True
  473. except json.JSONDecodeError:
  474. raise Exception("JSON 解析错误,可能是草稿内容格式不正确")
  475. except Exception as e:
  476. raise Exception(f"发生未知错误: {e}")
  477. def update_global_param(params):
  478. try:
  479. draft = PAIClient.get_work_flow_draft(experiment_id)
  480. content = draft['Content']
  481. version = draft['Version']
  482. content_json = json.loads(content)
  483. nodes = content_json.get('nodes')
  484. global_params = content_json.get('globalParams')
  485. for global_param in global_params:
  486. if global_param['name'] in params:
  487. value = params[global_param['name']]
  488. print(f"update global param {global_param['name']}: {value}")
  489. global_param['value'] = value
  490. new_content = json.dumps(content_json, ensure_ascii=False)
  491. PAIClient.update_experiment_content(experiment_id, new_content, version)
  492. return True
  493. except json.JSONDecodeError:
  494. raise Exception("JSON 解析错误,可能是草稿内容格式不正确")
  495. except Exception as e:
  496. raise Exception(f"发生未知错误: {e}")
  497. @retry
  498. def shuffle_table():
  499. try:
  500. node_dict = get_node_dict()
  501. train_node_id = node_dict['样本shuffle']
  502. execute_type = 'EXECUTE_FROM_HERE'
  503. validate_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  504. validate_job_id = validate_res['JobId']
  505. validate_job_detail = wait_job_end(validate_job_id, 10)
  506. if validate_job_detail['Status'] == 'Succeeded':
  507. return True
  508. return False
  509. except Exception as e:
  510. error_message = f"在执行 shuffle_table 函数时发生异常: {str(e)}"
  511. print(error_message)
  512. raise Exception(error_message)
  513. @retry
  514. def shuffle_train_model():
  515. try:
  516. node_dict = get_node_dict()
  517. job_dict = get_job_dict()
  518. job_id = job_dict['样本shuffle']
  519. validate_job_detail = wait_job_end(job_id)
  520. if validate_job_detail['Status'] == 'Succeeded':
  521. pipeline_run_id = validate_job_detail['RunId']
  522. node_id = validate_job_detail['PaiflowNodeId']
  523. flow_out_put_detail = PAIClient.get_flow_out_put(pipeline_run_id, node_id, 2)
  524. outputs = flow_out_put_detail['Outputs']
  525. table = None
  526. for output in outputs:
  527. if output["Producer"] == node_dict['样本shuffle'] and output["Name"] == "outputTable":
  528. value1 = json.loads(output["Info"]['value'])
  529. table = value1['location']['table']
  530. if table is not None:
  531. update_shuffle_flow(table)
  532. node_dict = get_node_dict()
  533. train_node_id = node_dict['模型训练-样本shufle']
  534. execute_type = 'EXECUTE_ONE'
  535. train_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  536. train_job_id = train_res['JobId']
  537. train_job_detail = wait_job_end(train_job_id)
  538. if train_job_detail['Status'] == 'Succeeded':
  539. return True
  540. return False
  541. except Exception as e:
  542. error_message = f"在执行 shuffle_train_model 函数时发生异常: {str(e)}"
  543. print(error_message)
  544. raise Exception(error_message)
  545. @retry
  546. def export_model():
  547. try:
  548. node_dict = get_node_dict()
  549. export_node_id = node_dict['模型导出-2']
  550. execute_type = 'EXECUTE_ONE'
  551. export_res = PAIClient.create_job(experiment_id, export_node_id, execute_type)
  552. export_job_id = export_res['JobId']
  553. export_job_detail = wait_job_end(export_job_id)
  554. if export_job_detail['Status'] == 'Succeeded':
  555. return True
  556. return False
  557. except Exception as e:
  558. error_message = f"在执行 export_model 函数时发生异常: {str(e)}"
  559. print(error_message)
  560. raise Exception(error_message)
  561. def update_online_model():
  562. try:
  563. node_dict = get_node_dict()
  564. train_node_id = node_dict['更新EAS服务(Beta)-1']
  565. execute_type = 'EXECUTE_ONE'
  566. train_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  567. train_job_id = train_res['JobId']
  568. train_job_detail = wait_job_end(train_job_id)
  569. if train_job_detail['Status'] == 'Succeeded':
  570. return True
  571. return False
  572. except Exception as e:
  573. error_message = f"在执行 update_online_model 函数时发生异常: {str(e)}"
  574. print(error_message)
  575. raise Exception(error_message)
  576. def update_validation_config():
  577. try:
  578. job_dict = get_job_dict()
  579. node_dict = get_node_dict()
  580. print(node_dict)
  581. job_id = job_dict['样本shuffle']
  582. validate_job_detail = wait_job_end(job_id)
  583. table = None
  584. if validate_job_detail['Status'] == 'Succeeded':
  585. pipeline_run_id = validate_job_detail['RunId']
  586. node_id = validate_job_detail['PaiflowNodeId']
  587. flow_out_put_detail = PAIClient.get_flow_out_put(pipeline_run_id, node_id, 2)
  588. outputs = flow_out_put_detail['Outputs']
  589. for output in outputs:
  590. if output["Producer"] == node_dict['评估样本重组'] and output["Name"] == "outputTable":
  591. value1 = json.loads(output["Info"]['value'])
  592. table = value1['location']['table']
  593. if not table:
  594. raise Exception("table not available")
  595. update_global_param({'eval_table_name': table})
  596. except Exception as e:
  597. error_message = f"在执行 update_validation_config 函数时发生异常: {str(e)}"
  598. print(error_message)
  599. raise Exception(error_message)
  600. @retry
  601. def get_validate_model_data():
  602. update_validation_config()
  603. try:
  604. node_dict = get_node_dict()
  605. train_node_id = node_dict['虚拟起始节点']
  606. execute_type = 'EXECUTE_FROM_HERE'
  607. validate_res = PAIClient.create_job(experiment_id, train_node_id, execute_type)
  608. validate_job_id = validate_res['JobId']
  609. validate_job_detail = wait_job_end(validate_job_id)
  610. if validate_job_detail['Status'] == 'Succeeded':
  611. return True
  612. return False
  613. except Exception as e:
  614. error_message = f"在执行 get_validate_model_data 函数时出现异常: {e}"
  615. print(error_message)
  616. raise Exception(error_message)
  617. def validate_model_data_accuracy():
  618. try:
  619. table_dict = {}
  620. node_dict = get_node_dict()
  621. job_dict = get_job_dict()
  622. job_id = job_dict['虚拟起始节点']
  623. validate_job_detail = wait_job_end(job_id)
  624. if validate_job_detail['Status'] == 'Succeeded':
  625. pipeline_run_id = validate_job_detail['RunId']
  626. node_id = validate_job_detail['PaiflowNodeId']
  627. flow_out_put_detail = PAIClient.get_flow_out_put(pipeline_run_id, node_id, 3)
  628. print(flow_out_put_detail)
  629. outputs = flow_out_put_detail['Outputs']
  630. for output in outputs:
  631. if output["Producer"] == node_dict['二分类评估-1'] and output["Name"] == "outputMetricTable":
  632. value1 = json.loads(output["Info"]['value'])
  633. table_dict['二分类评估-1'] = value1['location']['table']
  634. if output["Producer"] == node_dict['二分类评估-2'] and output["Name"] == "outputMetricTable":
  635. value2 = json.loads(output["Info"]['value'])
  636. table_dict['二分类评估-2'] = value2['location']['table']
  637. if output["Producer"] == node_dict['预测结果对比'] and output["Name"] == "outputTable":
  638. value3 = json.loads(output["Info"]['value'])
  639. table_dict['预测结果对比'] = value3['location']['table']
  640. num = 10
  641. df = get_data_from_odps('pai_algo', table_dict['预测结果对比'], 10)
  642. # 对指定列取绝对值再求和
  643. old_abs_avg = df['old_error'].abs().sum() / num
  644. new_abs_avg = df['new_error'].abs().sum() / num
  645. new_auc = get_dict_from_odps('pai_algo', table_dict['二分类评估-1'])['AUC']
  646. old_auc = get_dict_from_odps('pai_algo', table_dict['二分类评估-2'])['AUC']
  647. bizdate = get_previous_days_date(1)
  648. score_diff = abs(old_abs_avg - new_abs_avg)
  649. msg = ""
  650. result = False
  651. if new_abs_avg > 0.1:
  652. msg += f'线上模型评估{bizdate}的数据,绝对误差大于0.1,请检查'
  653. level = 'error'
  654. elif score_diff > 0.05:
  655. msg += f'两个模型评估${bizdate}的数据,两个模型分数差异为: ${score_diff}, 大于0.05, 请检查'
  656. level = 'error'
  657. else:
  658. msg += 'DNN广告模型更新完成'
  659. level = 'info'
  660. result = True
  661. # 初始化表格头部
  662. top10_msg = "| CID | 老模型相对真实CTCVR的变化 | 新模型相对真实CTCVR的变化 |"
  663. top10_msg += "\n| ---- | --------- | -------- |"
  664. for index, row in df.iterrows():
  665. # 获取指定列的元素
  666. cid = row['cid']
  667. old_error = row['old_error']
  668. new_error = row['new_error']
  669. top10_msg += f"\n| {int(cid)} | {old_error} | {new_error} | "
  670. print(top10_msg)
  671. msg += f"\n\t - 老模型AUC: {old_auc}"
  672. msg += f"\n\t - 新模型AUC: {new_auc}"
  673. msg += f"\n\t - 老模型Top10差异平均值: {old_abs_avg}"
  674. msg += f"\n\t - 新模型Top10差异平均值: {new_abs_avg}"
  675. return result, msg, level, top10_msg
  676. except Exception as e:
  677. error_message = f"在执行 validate_model_data_accuracy 函数时出现异常: {str(e)}"
  678. print(error_message)
  679. raise Exception(error_message)
  680. if __name__ == '__main__':
  681. start_time = int(time.time())
  682. functions = [update_online_flow, shuffle_table, shuffle_train_model, export_model, get_validate_model_data]
  683. function_names = [func.__name__ for func in functions]
  684. start_function = None
  685. if len(sys.argv) > 1:
  686. start_function = sys.argv[1]
  687. if start_function not in function_names:
  688. print(f"指定的起始函数 {start_function} 不存在,请选择以下函数之一:{', '.join(function_names)}")
  689. sys.exit(1)
  690. start_index = 0
  691. if start_function:
  692. start_index = function_names.index(start_function)
  693. for func in functions[start_index:]:
  694. if not func():
  695. print(f"{func.__name__} 执行失败,后续函数不再执行。")
  696. step_end_time = int(time.time())
  697. elapsed = step_end_time - start_time
  698. _monitor('error', f"DNN模型更新,{func.__name__} 执行失败,后续函数不再执行,请检查", start_time, elapsed, None)
  699. break
  700. else:
  701. print("所有函数都成功执行,可以继续下一步操作。")
  702. result, msg, level, top10_msg = validate_model_data_accuracy()
  703. if result:
  704. # update_online_model()
  705. print("success")
  706. step_end_time = int(time.time())
  707. elapsed = step_end_time - start_time
  708. print(level, msg, start_time, elapsed, top10_msg)
  709. _monitor(level, msg, start_time, elapsed, top10_msg)