pai_flow_operator2.py 30 KB

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