pai_flow_operator_v3.py 33 KB

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