You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

aisafety.go 35 kB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. package repo
  2. import (
  3. "bufio"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "os"
  11. "strconv"
  12. "strings"
  13. cloudbrainService "code.gitea.io/gitea/services/cloudbrain"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/aisafety"
  16. "code.gitea.io/gitea/modules/cloudbrain"
  17. "code.gitea.io/gitea/modules/context"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/modelarts"
  21. "code.gitea.io/gitea/modules/setting"
  22. "code.gitea.io/gitea/modules/storage"
  23. "code.gitea.io/gitea/modules/timeutil"
  24. "code.gitea.io/gitea/modules/util"
  25. "code.gitea.io/gitea/services/cloudbrain/resource"
  26. "code.gitea.io/gitea/services/reward/point/account"
  27. )
  28. const (
  29. tplModelSafetyTestCreateGrampusGpu = "repo/modelsafety/newgrampusgpu"
  30. tplModelSafetyTestCreateGrampusNpu = "repo/modelsafety/newgrampusnpu"
  31. tplModelSafetyTestCreateGpu = "repo/modelsafety/newgpu"
  32. tplModelSafetyTestCreateNpu = "repo/modelsafety/newnpu"
  33. tplModelSafetyTestShow = "repo/modelsafety/show"
  34. )
  35. func GetAiSafetyTaskByJob(job *models.Cloudbrain) {
  36. if job == nil {
  37. log.Error("GetCloudbrainByJobID failed")
  38. return
  39. }
  40. syncAiSafetyTaskStatus(job)
  41. }
  42. func GetAiSafetyTaskTmpl(ctx *context.Context) {
  43. ctx.Data["id"] = ctx.Params(":id")
  44. ctx.Data["PageIsCloudBrain"] = true
  45. ctx.HTML(200, tplModelSafetyTestShow)
  46. }
  47. func GetAiSafetyTask(ctx *context.Context) {
  48. var ID = ctx.Params(":id")
  49. job, err := models.GetCloudbrainByIDWithDeleted(ID)
  50. if err != nil {
  51. log.Error("GetCloudbrainByJobID failed:" + err.Error())
  52. return
  53. }
  54. syncAiSafetyTaskStatus(job)
  55. job, err = models.GetCloudbrainByIDWithDeleted(ID)
  56. job.BenchmarkType = "安全评测"
  57. job.BenchmarkTypeName = "Image Classification"
  58. job.CanModify = cloudbrain.CanModifyJob(ctx, job)
  59. job.CanDel = cloudbrain.CanDeleteJob(ctx, job)
  60. if job.Parameters == "{\"parameter\":[]}" {
  61. job.Parameters = ""
  62. }
  63. s, err := resource.GetCloudbrainSpec(job.ID)
  64. if err == nil {
  65. job.Spec = s
  66. }
  67. user, err := models.GetUserByID(job.UserID)
  68. if err == nil {
  69. tmpUser := &models.User{
  70. Name: user.Name,
  71. }
  72. job.User = tmpUser
  73. }
  74. ctx.JSON(200, job)
  75. }
  76. func StopAiSafetyTask(ctx *context.Context) {
  77. log.Info("start to stop the task.")
  78. var ID = ctx.Params(":id")
  79. task, err := models.GetCloudbrainByIDWithDeleted(ID)
  80. result := make(map[string]interface{})
  81. result["result_code"] = "-1"
  82. if err != nil {
  83. log.Info("query task error.err=" + err.Error())
  84. log.Error("GetCloudbrainByJobID failed:" + err.Error())
  85. result["msg"] = "No such task."
  86. ctx.JSON(200, result)
  87. return
  88. }
  89. if isTaskNotFinished(task.Status) {
  90. if task.Type == models.TypeCloudBrainTwo {
  91. log.Info("start to stop model arts task.")
  92. _, err := modelarts.StopTrainJob(task.JobID, strconv.FormatInt(task.VersionID, 10))
  93. if err != nil {
  94. log.Info("stop failed.err=" + err.Error())
  95. }
  96. task.Status = string(models.JobStopped)
  97. if task.EndTime == 0 {
  98. task.EndTime = timeutil.TimeStampNow()
  99. }
  100. task.ComputeAndSetDuration()
  101. err = models.UpdateJob(task)
  102. if err != nil {
  103. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  104. result["msg"] = "cloudbrain.Stopped_success_update_status_fail"
  105. ctx.JSON(200, result)
  106. return
  107. }
  108. //queryTaskStatusFromCloudbrainTwo(job)
  109. } else if task.Type == models.TypeCloudBrainOne {
  110. if task.Status == string(models.JobStopped) || task.Status == string(models.JobFailed) || task.Status == string(models.JobSucceeded) {
  111. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  112. result["msg"] = "cloudbrain.Already_stopped"
  113. ctx.JSON(200, result)
  114. return
  115. }
  116. err := cloudbrain.StopJob(task.JobID)
  117. if err != nil {
  118. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  119. result["msg"] = "cloudbrain.Stopped_failed"
  120. ctx.JSON(200, result)
  121. return
  122. }
  123. task.Status = string(models.JobStopped)
  124. if task.EndTime == 0 {
  125. task.EndTime = timeutil.TimeStampNow()
  126. }
  127. task.ComputeAndSetDuration()
  128. err = models.UpdateJob(task)
  129. if err != nil {
  130. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  131. result["msg"] = "cloudbrain.Stopped_success_update_status_fail"
  132. ctx.JSON(200, result)
  133. return
  134. }
  135. }
  136. } else {
  137. if task.Status == string(models.ModelSafetyTesting) {
  138. //修改为Failed
  139. task.Status = string(models.JobStopped)
  140. if task.EndTime == 0 {
  141. task.EndTime = timeutil.TimeStampNow()
  142. }
  143. task.ComputeAndSetDuration()
  144. err = models.UpdateJob(task)
  145. if err != nil {
  146. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  147. result["msg"] = "cloudbrain.Stopped_success_update_status_fail"
  148. ctx.JSON(200, result)
  149. return
  150. }
  151. } else {
  152. log.Info("The job is finished. status=" + task.Status)
  153. }
  154. }
  155. result["result_code"] = "0"
  156. result["msg"] = "succeed"
  157. ctx.JSON(200, result)
  158. }
  159. func DelAiSafetyTask(ctx *context.Context) {
  160. var ID = ctx.Params(":id")
  161. task, err := models.GetCloudbrainByIDWithDeleted(ID)
  162. if err != nil {
  163. log.Error("GetCloudbrainByJobID failed:" + err.Error())
  164. ctx.ServerError("No such task.", err)
  165. return
  166. }
  167. if task.Status != string(models.JobStopped) && task.Status != string(models.JobFailed) && task.Status != string(models.JobSucceeded) {
  168. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  169. ctx.ServerError("the job("+task.JobName+") has not been stopped", nil)
  170. return
  171. }
  172. if task.Type == models.TypeCloudBrainOne {
  173. DeleteCloudbrainJobStorage(task.JobName, models.TypeCloudBrainOne)
  174. }
  175. err = models.DeleteJob(task)
  176. if err != nil {
  177. ctx.ServerError(err.Error(), err)
  178. return
  179. }
  180. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  181. }
  182. func syncAiSafetyTaskStatus(job *models.Cloudbrain) {
  183. log.Info("start to query safety task status.")
  184. if isTaskNotFinished(job.Status) {
  185. if job.Type == models.TypeCloudBrainTwo {
  186. queryTaskStatusFromCloudbrainTwo(job)
  187. } else if job.Type == models.TypeCloudBrainOne {
  188. queryTaskStatusFromCloudbrain(job)
  189. }
  190. } else {
  191. if job.Status == string(models.ModelSafetyTesting) {
  192. queryTaskStatusFromModelSafetyTestServer(job)
  193. } else {
  194. log.Info("The job is finished. status=" + job.Status)
  195. }
  196. }
  197. }
  198. func TimerHandleModelSafetyTestTask() {
  199. log.Info("start to TimerHandleModelSafetyTestTask")
  200. tasks, err := models.GetModelSafetyTestTask()
  201. if err == nil {
  202. if tasks != nil && len(tasks) > 0 {
  203. for _, job := range tasks {
  204. syncAiSafetyTaskStatus(job)
  205. }
  206. } else {
  207. log.Info("query running model safety test task 0.")
  208. }
  209. } else {
  210. log.Info("query running model safety test task err." + err.Error())
  211. }
  212. }
  213. func queryTaskStatusFromCloudbrainTwo(job *models.Cloudbrain) {
  214. log.Info("The task not finished,name=" + job.DisplayJobName)
  215. result, err := modelarts.GetTrainJob(job.JobID, strconv.FormatInt(job.VersionID, 10))
  216. if err != nil {
  217. log.Info("query train job error." + err.Error())
  218. return
  219. }
  220. job.Status = modelarts.TransTrainJobStatus(result.IntStatus)
  221. job.Duration = result.Duration / 1000
  222. job.TrainJobDuration = result.TrainJobDuration
  223. if job.StartTime == 0 && result.StartTime > 0 {
  224. job.StartTime = timeutil.TimeStamp(result.StartTime / 1000)
  225. }
  226. job.TrainJobDuration = models.ConvertDurationToStr(job.Duration)
  227. if job.EndTime == 0 && models.IsTrainJobTerminal(job.Status) && job.StartTime > 0 {
  228. job.EndTime = job.StartTime.Add(job.Duration)
  229. }
  230. job.CorrectCreateUnix()
  231. if job.Status != string(models.ModelArtsTrainJobCompleted) {
  232. log.Info("CloudbrainTwo task status=" + job.Status)
  233. err = models.UpdateJob(job)
  234. if err != nil {
  235. log.Error("UpdateJob failed:", err)
  236. }
  237. } else {
  238. log.Info("start to deal ModelSafetyTesting, task status=" + job.Status)
  239. job.Status = string(models.ModelSafetyTesting)
  240. err = models.UpdateJob(job)
  241. if err != nil {
  242. log.Error("UpdateJob failed:", err)
  243. }
  244. //send msg to beihang
  245. sendNPUInferenceResultToTest(job)
  246. }
  247. }
  248. func queryTaskStatusFromCloudbrain(job *models.Cloudbrain) {
  249. log.Info("The task not finished,name=" + job.DisplayJobName)
  250. jobResult, err := cloudbrain.GetJob(job.JobID)
  251. result, err := models.ConvertToJobResultPayload(jobResult.Payload)
  252. if err != nil {
  253. log.Error("ConvertToJobResultPayload failed:", err)
  254. return
  255. }
  256. job.Status = result.JobStatus.State
  257. if result.JobStatus.State != string(models.JobWaiting) && result.JobStatus.State != string(models.JobFailed) {
  258. taskRoles := result.TaskRoles
  259. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  260. job.Status = taskRes.TaskStatuses[0].State
  261. }
  262. models.ParseAndSetDurationFromCloudBrainOne(result, job)
  263. //updateCloudBrainOneJobTime(job)
  264. log.Info("cloud brain one job status=" + job.Status)
  265. if result.JobStatus.State != string(models.JobSucceeded) {
  266. err = models.UpdateJob(job)
  267. if err != nil {
  268. log.Error("UpdateJob failed:", err)
  269. }
  270. } else {
  271. //
  272. job.Status = string(models.ModelSafetyTesting)
  273. job.EndTime = 0
  274. err = models.UpdateJob(job)
  275. if err != nil {
  276. log.Error("UpdateJob failed:", err)
  277. }
  278. //send msg to beihang
  279. sendGPUInferenceResultToTest(job)
  280. }
  281. }
  282. func queryTaskStatusFromModelSafetyTestServer(job *models.Cloudbrain) {
  283. result, err := aisafety.GetTaskStatus(job.PreVersionName)
  284. if err == nil {
  285. if result.Code == "0" {
  286. if result.Data.Status == 1 {
  287. log.Info("The task is running....")
  288. } else {
  289. job.EndTime = timeutil.TimeStampNow()
  290. job.Duration = (job.EndTime.AsTime().Unix() - job.StartTime.AsTime().Unix()) / 1000
  291. job.TrainJobDuration = models.ConvertDurationToStr(job.Duration)
  292. if result.Data.Code == 0 {
  293. job.ResultJson = result.Data.StandardJson
  294. job.Status = string(models.JobSucceeded)
  295. err = models.UpdateJob(job)
  296. if err != nil {
  297. log.Error("UpdateJob failed:", err)
  298. }
  299. } else {
  300. job.ResultJson = result.Data.Msg
  301. job.Status = string(models.JobFailed)
  302. err = models.UpdateJob(job)
  303. if err != nil {
  304. log.Error("UpdateJob failed:", err)
  305. }
  306. }
  307. }
  308. } else {
  309. log.Info("The task is failed.")
  310. job.Status = string(models.JobFailed)
  311. err = models.UpdateJob(job)
  312. if err != nil {
  313. log.Error("UpdateJob failed:", err)
  314. }
  315. }
  316. } else {
  317. log.Info("The task not found.....")
  318. }
  319. }
  320. func getAisafetyTaskReq(job *models.Cloudbrain) aisafety.TaskReq {
  321. datasetname := job.DatasetName
  322. datasetnames := strings.Split(datasetname, ";")
  323. indicator := job.LabelName
  324. EvalContent := "test1"
  325. if job.Description != "" {
  326. EvalContent = job.Description
  327. }
  328. req := aisafety.TaskReq{
  329. UnionId: job.JobID,
  330. EvalName: job.DisplayJobName,
  331. EvalContent: EvalContent,
  332. TLPath: "test1",
  333. Indicators: strings.Split(indicator, ";"),
  334. CDName: strings.Split(datasetnames[1], ".")[0],
  335. BDName: strings.Split(datasetnames[0], ".")[0] + "基础数据集",
  336. }
  337. log.Info("CDName=" + req.CDName)
  338. log.Info("BDName=" + req.BDName)
  339. return req
  340. }
  341. func sendGPUInferenceResultToTest(job *models.Cloudbrain) {
  342. log.Info("send sendGPUInferenceResultToTest")
  343. req := getAisafetyTaskReq(job)
  344. resultDir := "/result"
  345. prefix := setting.CBCodePathPrefix + job.JobName + resultDir
  346. files, err := storage.GetOneLevelAllObjectUnderDirMinio(setting.Attachment.Minio.Bucket, prefix, "")
  347. if err != nil {
  348. log.Error("query cloudbrain one model failed: %v", err)
  349. return
  350. }
  351. jsonContent := ""
  352. for _, file := range files {
  353. if strings.HasSuffix(file.FileName, "result.json") {
  354. path := storage.GetMinioPath(job.JobName+resultDir+"/", file.FileName)
  355. log.Info("path=" + path)
  356. reader, err := os.Open(path)
  357. defer reader.Close()
  358. if err == nil {
  359. r := bufio.NewReader(reader)
  360. for {
  361. line, error := r.ReadString('\n')
  362. jsonContent += line
  363. if error == io.EOF {
  364. log.Info("read file completed.")
  365. break
  366. }
  367. if error != nil {
  368. log.Info("read file error." + error.Error())
  369. break
  370. }
  371. }
  372. }
  373. break
  374. }
  375. }
  376. if jsonContent != "" {
  377. sendHttpReqToBeihang(job, jsonContent, req)
  378. } else {
  379. updateJobFailed(job, "推理生成的Json数据为空,无法进行评测。")
  380. }
  381. }
  382. func sendNPUInferenceResultToTest(job *models.Cloudbrain) {
  383. log.Info("start to sendNPUInferenceResultToTest")
  384. req := getAisafetyTaskReq(job)
  385. jsonContent := ""
  386. VersionOutputPath := modelarts.GetOutputPathByCount(modelarts.TotalVersionCount)
  387. resultPath := modelarts.JobPath + job.JobName + modelarts.ResultPath + VersionOutputPath + "/result.json"
  388. resultPath = resultPath[1:]
  389. log.Info("bucket=" + setting.Bucket + " resultPath=" + resultPath)
  390. body, err := storage.ObsDownloadAFile(setting.Bucket, resultPath)
  391. if err != nil {
  392. log.Info("ObsDownloadAFile error." + err.Error() + " resultPath=" + resultPath)
  393. } else {
  394. defer body.Close()
  395. var data []byte
  396. p := make([]byte, 4096)
  397. var readErr error
  398. var readCount int
  399. for {
  400. readCount, readErr = body.Read(p)
  401. if readCount > 0 {
  402. data = append(data, p[:readCount]...)
  403. }
  404. if readErr != nil || readCount == 0 {
  405. break
  406. }
  407. }
  408. jsonContent = string(data)
  409. }
  410. if jsonContent != "" {
  411. sendHttpReqToBeihang(job, jsonContent, req)
  412. } else {
  413. updateJobFailed(job, "推理生成的Json数据为空,无法进行评测。")
  414. }
  415. }
  416. func updateJobFailed(job *models.Cloudbrain, msg string) {
  417. log.Info("The json is null. so set it failed.")
  418. //update task failed.
  419. job.Status = string(models.ModelArtsTrainJobFailed)
  420. job.ResultJson = msg
  421. job.EndTime = timeutil.TimeStampNow()
  422. job.Duration = (job.EndTime.AsTime().Unix() - job.StartTime.AsTime().Unix()) / 1000
  423. job.TrainJobDuration = models.ConvertDurationToStr(job.Duration)
  424. err := models.UpdateJob(job)
  425. if err != nil {
  426. log.Error("UpdateJob failed:", err)
  427. }
  428. }
  429. func sendHttpReqToBeihang(job *models.Cloudbrain, jsonContent string, req aisafety.TaskReq) {
  430. log.Info("start to send beihang ...")
  431. serialNo, err := aisafety.CreateSafetyTask(req, jsonContent)
  432. if err == nil {
  433. //update serial no to db
  434. job.PreVersionName = serialNo
  435. err = models.UpdateJob(job)
  436. if err != nil {
  437. log.Error("UpdateJob failed:", err)
  438. }
  439. }
  440. }
  441. func isTaskNotFinished(status string) bool {
  442. if status == string(models.ModelArtsTrainJobRunning) || status == string(models.ModelArtsTrainJobWaiting) {
  443. return true
  444. }
  445. if status == string(models.JobWaiting) || status == string(models.JobRunning) {
  446. return true
  447. }
  448. if status == string(models.ModelArtsTrainJobUnknown) || status == string(models.ModelArtsTrainJobInit) {
  449. return true
  450. }
  451. if status == string(models.ModelArtsTrainJobImageCreating) || status == string(models.ModelArtsTrainJobSubmitTrying) {
  452. return true
  453. }
  454. return false
  455. }
  456. func AiSafetyCreateForGetGPU(ctx *context.Context) {
  457. ctx.Data["PageIsCloudBrain"] = true
  458. ctx.Data["IsCreate"] = true
  459. ctx.Data["type"] = models.TypeCloudBrainOne
  460. ctx.Data["compute_resource"] = models.GPUResource
  461. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  462. ctx.Data["BaseDataSetName"] = setting.ModelSafetyTest.GPUBaseDataSetName
  463. ctx.Data["BaseDataSetUUID"] = setting.ModelSafetyTest.GPUBaseDataSetUUID
  464. ctx.Data["CombatDataSetName"] = setting.ModelSafetyTest.GPUCombatDataSetName
  465. ctx.Data["CombatDataSetUUID"] = setting.ModelSafetyTest.GPUCombatDataSetUUID
  466. log.Info("GPUBaseDataSetName=" + setting.ModelSafetyTest.GPUBaseDataSetName)
  467. log.Info("GPUBaseDataSetUUID=" + setting.ModelSafetyTest.GPUBaseDataSetUUID)
  468. log.Info("GPUCombatDataSetName=" + setting.ModelSafetyTest.GPUCombatDataSetName)
  469. log.Info("GPUCombatDataSetUUID=" + setting.ModelSafetyTest.GPUCombatDataSetUUID)
  470. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  471. ctx.Data["display_job_name"] = displayJobName
  472. prepareCloudbrainOneSpecs(ctx)
  473. queuesDetail, _ := cloudbrain.GetQueuesDetail()
  474. if queuesDetail != nil {
  475. ctx.Data["QueuesDetail"] = queuesDetail
  476. reqPara, _ := json.Marshal(queuesDetail)
  477. log.Warn("The GPU WaitCount json:", string(reqPara))
  478. } else {
  479. log.Info("The GPU WaitCount not get")
  480. }
  481. NotStopTaskCount, _ := models.GetModelSafetyCountByUserID(ctx.User.ID)
  482. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  483. ctx.HTML(200, tplModelSafetyTestCreateGpu)
  484. }
  485. func AiSafetyCreateForGetNPU(ctx *context.Context) {
  486. ctx.Data["PageIsCloudBrain"] = true
  487. ctx.Data["IsCreate"] = true
  488. ctx.Data["type"] = models.TypeCloudBrainTwo
  489. ctx.Data["compute_resource"] = models.NPUResource
  490. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  491. ctx.Data["display_job_name"] = displayJobName
  492. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  493. ctx.Data["BaseDataSetName"] = setting.ModelSafetyTest.NPUBaseDataSetName
  494. ctx.Data["BaseDataSetUUID"] = setting.ModelSafetyTest.NPUBaseDataSetUUID
  495. ctx.Data["CombatDataSetName"] = setting.ModelSafetyTest.NPUCombatDataSetName
  496. ctx.Data["CombatDataSetUUID"] = setting.ModelSafetyTest.NPUCombatDataSetUUID
  497. log.Info("NPUBaseDataSetName=" + setting.ModelSafetyTest.NPUBaseDataSetName)
  498. log.Info("NPUBaseDataSetUUID=" + setting.ModelSafetyTest.NPUBaseDataSetUUID)
  499. log.Info("NPUCombatDataSetName=" + setting.ModelSafetyTest.NPUCombatDataSetName)
  500. log.Info("NPUCombatDataSetUUID=" + setting.ModelSafetyTest.NPUCombatDataSetUUID)
  501. var resourcePools modelarts.ResourcePool
  502. if err := json.Unmarshal([]byte(setting.ResourcePools), &resourcePools); err != nil {
  503. ctx.ServerError("json.Unmarshal failed:", err)
  504. }
  505. ctx.Data["resource_pools"] = resourcePools.Info
  506. var engines modelarts.Engine
  507. if err := json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  508. ctx.ServerError("json.Unmarshal failed:", err)
  509. }
  510. ctx.Data["engines"] = engines.Info
  511. var versionInfos modelarts.VersionInfo
  512. if err := json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  513. ctx.ServerError("json.Unmarshal failed:", err)
  514. }
  515. ctx.Data["engine_versions"] = versionInfos.Version
  516. prepareCloudbrainTwoInferenceSpecs(ctx)
  517. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  518. ctx.Data["WaitCount"] = waitCount
  519. log.Info("The NPU WaitCount is " + fmt.Sprint(waitCount))
  520. NotStopTaskCount, _ := models.GetModelSafetyCountByUserID(ctx.User.ID)
  521. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  522. ctx.HTML(200, tplModelSafetyTestCreateNpu)
  523. }
  524. func AiSafetyCreateForPost(ctx *context.Context) {
  525. ctx.Data["PageIsCloudBrain"] = true
  526. displayJobName := ctx.Query("display_job_name")
  527. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  528. taskType := ctx.QueryInt("type")
  529. description := ctx.Query("description")
  530. ctx.Data["type"] = taskType
  531. ctx.Data["displayJobName"] = displayJobName
  532. ctx.Data["description"] = description
  533. repo := ctx.Repo.Repository
  534. tpname := tplCloudBrainModelSafetyNewNpu
  535. if taskType == models.TypeCloudBrainOne {
  536. tpname = tplCloudBrainModelSafetyNewGpu
  537. }
  538. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeModelSafety), displayJobName)
  539. if err == nil {
  540. if len(tasks) != 0 {
  541. log.Error("the job name did already exist", ctx.Data["MsgID"])
  542. modelSafetyNewDataPrepare(ctx)
  543. ctx.RenderWithErr("the job name did already exist", tpname, nil)
  544. return
  545. }
  546. } else {
  547. if !models.IsErrJobNotExist(err) {
  548. log.Error("system error, %v", err, ctx.Data["MsgID"])
  549. modelSafetyNewDataPrepare(ctx)
  550. ctx.RenderWithErr("system error", tpname, nil)
  551. return
  552. }
  553. }
  554. if !jobNamePattern.MatchString(jobName) {
  555. modelSafetyNewDataPrepare(ctx)
  556. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpname, nil)
  557. return
  558. }
  559. count, err := models.GetModelSafetyCountByUserID(ctx.User.ID)
  560. if err != nil {
  561. log.Error("GetCloudbrainCountByUserID failed:%v", err, ctx.Data["MsgID"])
  562. modelSafetyNewDataPrepare(ctx)
  563. ctx.RenderWithErr("system error", tpname, nil)
  564. return
  565. } else {
  566. if count >= 1 {
  567. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  568. modelSafetyNewDataPrepare(ctx)
  569. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain.morethanonejob"), tpname, nil)
  570. return
  571. }
  572. }
  573. BootFile := ctx.Query("boot_file")
  574. BootFile = strings.TrimSpace(BootFile)
  575. bootFileExist, err := ctx.Repo.FileExists(BootFile, cloudbrain.DefaultBranchName)
  576. if err != nil || !bootFileExist {
  577. log.Error("Get bootfile error:", err)
  578. modelSafetyNewDataPrepare(ctx)
  579. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpname, nil)
  580. return
  581. }
  582. if taskType == models.TypeCloudBrainTwo {
  583. err = createForNPU(ctx, jobName)
  584. } else if taskType == models.TypeCloudBrainOne {
  585. err = createForGPU(ctx, jobName)
  586. }
  587. if err != nil {
  588. modelSafetyNewDataPrepare(ctx)
  589. ctx.RenderWithErr(err.Error(), tpname, nil)
  590. } else {
  591. log.Info("to redirect...")
  592. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/cloudbrain/benchmark")
  593. }
  594. }
  595. func createForNPU(ctx *context.Context, jobName string) error {
  596. VersionOutputPath := modelarts.GetOutputPathByCount(modelarts.TotalVersionCount)
  597. BootFile := ctx.Query("boot_file")
  598. BootFile = strings.TrimSpace(BootFile)
  599. displayJobName := ctx.Query("display_job_name")
  600. description := ctx.Query("description")
  601. srcDataset := ctx.Query("src_dataset") //uuid
  602. combatDataset := ctx.Query("combat_dataset") //uuid
  603. evaluationIndex := ctx.Query("evaluation_index")
  604. Params := ctx.Query("run_para_list")
  605. specId := ctx.QueryInt64("spec_id")
  606. engineID := ctx.QueryInt("engine_id")
  607. log.Info("engine_id=" + fmt.Sprint(engineID))
  608. poolID := ctx.Query("pool_id")
  609. repo := ctx.Repo.Repository
  610. trainUrl := ctx.Query("train_url")
  611. modelName := ctx.Query("model_name")
  612. modelVersion := ctx.Query("model_version")
  613. ckptName := ctx.Query("ckpt_name")
  614. ckptUrl := "/" + trainUrl + ckptName
  615. log.Info("ckpt url:" + ckptUrl)
  616. FlavorName := ctx.Query("flaver_names")
  617. EngineName := ctx.Query("engine_names")
  618. isLatestVersion := modelarts.IsLatestVersion
  619. VersionCount := modelarts.VersionCountOne
  620. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  621. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.CodePath
  622. resultObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.ResultPath + VersionOutputPath + "/"
  623. logObsPath := "/" + setting.Bucket + modelarts.JobPath + jobName + modelarts.LogPath + VersionOutputPath + "/"
  624. log.Info("ckpt url:" + ckptUrl)
  625. spec, err := resource.GetAndCheckSpec(ctx.User.ID, specId, models.FindSpecsOptions{
  626. JobType: models.JobTypeInference,
  627. ComputeResource: models.NPU,
  628. Cluster: models.OpenICluster,
  629. AiCenterCode: models.AICenterOfCloudBrainTwo})
  630. if err != nil || spec == nil {
  631. //ctx.RenderWithErr("Resource specification not available", tplCloudBrainModelSafetyNewNpu, nil)
  632. return errors.New("Resource specification not available")
  633. }
  634. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  635. log.Error("point balance is not enough,userId=%d specId=%d ", ctx.User.ID, spec.ID)
  636. return errors.New(ctx.Tr("points.insufficient_points_balance"))
  637. }
  638. //todo: del the codeLocalPath
  639. _, err = ioutil.ReadDir(codeLocalPath)
  640. if err == nil {
  641. os.RemoveAll(codeLocalPath)
  642. }
  643. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  644. commitID, _ := gitRepo.GetBranchCommitID(cloudbrain.DefaultBranchName)
  645. if err := downloadCode(repo, codeLocalPath, cloudbrain.DefaultBranchName); err != nil {
  646. log.Error("Create task failed, server timed out: %s (%v)", repo.FullName(), err)
  647. return errors.New(ctx.Tr("cloudbrain.load_code_failed"))
  648. }
  649. //todo: upload code (send to file_server todo this work?)
  650. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.ResultPath + VersionOutputPath + "/"); err != nil {
  651. log.Error("Failed to obsMkdir_result: %s (%v)", repo.FullName(), err)
  652. return errors.New("Failed to obsMkdir_result")
  653. }
  654. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  655. log.Error("Failed to obsMkdir_log: %s (%v)", repo.FullName(), err)
  656. return errors.New("Failed to obsMkdir_log")
  657. }
  658. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  659. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  660. return errors.New(ctx.Tr("cloudbrain.load_code_failed"))
  661. }
  662. var parameters models.Parameters
  663. param := make([]models.Parameter, 0)
  664. param = append(param, models.Parameter{
  665. Label: modelarts.ResultUrl,
  666. Value: "s3:/" + resultObsPath,
  667. }, models.Parameter{
  668. Label: modelarts.CkptUrl,
  669. Value: "s3:/" + ckptUrl,
  670. })
  671. uuid := srcDataset + ";" + combatDataset
  672. datasUrlList, dataUrl, datasetNames, isMultiDataset, err := getDatasUrlListByUUIDS(uuid)
  673. if err != nil {
  674. return err
  675. }
  676. dataPath := dataUrl
  677. jsondatas, err := json.Marshal(datasUrlList)
  678. if err != nil {
  679. log.Error("Failed to Marshal: %v", err)
  680. return err
  681. }
  682. if isMultiDataset {
  683. param = append(param, models.Parameter{
  684. Label: modelarts.MultiDataUrl,
  685. Value: string(jsondatas),
  686. })
  687. }
  688. existDeviceTarget := false
  689. if len(Params) != 0 {
  690. err := json.Unmarshal([]byte(Params), &parameters)
  691. if err != nil {
  692. log.Error("Failed to Unmarshal params: %s (%v)", Params, err)
  693. return errors.New("运行参数错误")
  694. }
  695. for _, parameter := range parameters.Parameter {
  696. if parameter.Label == modelarts.DeviceTarget {
  697. existDeviceTarget = true
  698. }
  699. if parameter.Label != modelarts.TrainUrl && parameter.Label != modelarts.DataUrl {
  700. param = append(param, models.Parameter{
  701. Label: parameter.Label,
  702. Value: parameter.Value,
  703. })
  704. }
  705. }
  706. }
  707. if !existDeviceTarget {
  708. param = append(param, models.Parameter{
  709. Label: modelarts.DeviceTarget,
  710. Value: modelarts.Ascend,
  711. })
  712. }
  713. req := &modelarts.GenerateInferenceJobReq{
  714. JobName: jobName,
  715. DisplayJobName: displayJobName,
  716. DataUrl: dataPath,
  717. Description: description,
  718. CodeObsPath: codeObsPath,
  719. BootFileUrl: codeObsPath + BootFile,
  720. BootFile: BootFile,
  721. TrainUrl: trainUrl,
  722. WorkServerNumber: 1,
  723. EngineID: int64(engineID),
  724. LogUrl: logObsPath,
  725. PoolID: poolID,
  726. Uuid: uuid,
  727. Parameters: param, //modelarts train parameters
  728. CommitID: commitID,
  729. BranchName: cloudbrain.DefaultBranchName,
  730. Params: Params,
  731. FlavorName: FlavorName,
  732. EngineName: EngineName,
  733. LabelName: evaluationIndex,
  734. IsLatestVersion: isLatestVersion,
  735. VersionCount: VersionCount,
  736. TotalVersionCount: modelarts.TotalVersionCount,
  737. ModelName: modelName,
  738. ModelVersion: modelVersion,
  739. CkptName: ckptName,
  740. ResultUrl: resultObsPath,
  741. Spec: spec,
  742. DatasetName: datasetNames,
  743. JobType: string(models.JobTypeModelSafety),
  744. }
  745. _, err = modelarts.GenerateInferenceJob(ctx, req)
  746. if err != nil {
  747. log.Error("GenerateTrainJob failed:%v", err.Error())
  748. return err
  749. }
  750. return nil
  751. }
  752. func createForGPU(ctx *context.Context, jobName string) error {
  753. BootFile := ctx.Query("boot_file")
  754. BootFile = strings.TrimSpace(BootFile)
  755. displayJobName := ctx.Query("display_job_name")
  756. description := ctx.Query("description")
  757. image := strings.TrimSpace(ctx.Query("image"))
  758. srcDataset := ctx.Query("src_dataset") //uuid
  759. combatDataset := ctx.Query("combat_dataset") //uuid
  760. evaluationIndex := ctx.Query("evaluation_index")
  761. Params := ctx.Query("run_para_list")
  762. specId := ctx.QueryInt64("spec_id")
  763. TrainUrl := ctx.Query("train_url")
  764. CkptName := ctx.Query("ckpt_name")
  765. modelName := ctx.Query("model_name")
  766. modelVersion := ctx.Query("model_version")
  767. ckptUrl := setting.Attachment.Minio.RealPath + TrainUrl + CkptName
  768. log.Info("ckpt url:" + ckptUrl)
  769. spec, err := resource.GetAndCheckSpec(ctx.User.ID, specId, models.FindSpecsOptions{
  770. JobType: models.JobTypeBenchmark,
  771. ComputeResource: models.GPU,
  772. Cluster: models.OpenICluster,
  773. AiCenterCode: models.AICenterOfCloudBrainOne})
  774. if err != nil || spec == nil {
  775. return errors.New("Resource specification not available")
  776. }
  777. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  778. log.Error("point balance is not enough,userId=%d specId=%d ", ctx.User.ID, spec.ID)
  779. return errors.New(ctx.Tr("points.insufficient_points_balance"))
  780. }
  781. repo := ctx.Repo.Repository
  782. codePath := setting.JobPath + jobName + cloudbrain.CodeMountPath
  783. os.RemoveAll(codePath)
  784. if err := downloadCode(repo, codePath, cloudbrain.DefaultBranchName); err != nil {
  785. log.Error("downloadCode failed, %v", err, ctx.Data["MsgID"])
  786. return errors.New("system error")
  787. }
  788. err = uploadCodeToMinio(codePath+"/", jobName, cloudbrain.CodeMountPath+"/")
  789. if err != nil {
  790. log.Error("uploadCodeToMinio failed, %v", err, ctx.Data["MsgID"])
  791. return errors.New("system error")
  792. }
  793. uuid := srcDataset + ";" + combatDataset
  794. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid)
  795. log.Info("uuid=" + uuid)
  796. if err != nil {
  797. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  798. return errors.New(ctx.Tr("cloudbrain.error.dataset_select"))
  799. }
  800. command, err := getGpuModelSafetyCommand(BootFile, Params, CkptName, displayJobName)
  801. if err != nil {
  802. log.Error("Get Command failed: %v", err, ctx.Data["MsgID"])
  803. return errors.New(ctx.Tr("cloudbrain.error.dataset_select"))
  804. }
  805. log.Info("Command=" + command)
  806. req := cloudbrain.GenerateCloudBrainTaskReq{
  807. Ctx: ctx,
  808. DisplayJobName: displayJobName,
  809. JobName: jobName,
  810. Image: image,
  811. Command: command,
  812. Uuids: uuid,
  813. DatasetNames: datasetNames,
  814. DatasetInfos: datasetInfos,
  815. CodePath: storage.GetMinioPath(jobName, cloudbrain.CodeMountPath+"/"),
  816. ModelPath: setting.Attachment.Minio.RealPath + TrainUrl,
  817. BenchmarkPath: storage.GetMinioPath(jobName, cloudbrain.BenchMarkMountPath+"/"),
  818. Snn4ImageNetPath: storage.GetMinioPath(jobName, cloudbrain.Snn4imagenetMountPath+"/"),
  819. BrainScorePath: storage.GetMinioPath(jobName, cloudbrain.BrainScoreMountPath+"/"),
  820. JobType: string(models.JobTypeModelSafety),
  821. Description: description,
  822. BranchName: cloudbrain.DefaultBranchName,
  823. BootFile: BootFile,
  824. Params: Params,
  825. CommitID: "",
  826. ModelName: modelName,
  827. ModelVersion: modelVersion,
  828. CkptName: CkptName,
  829. ResultPath: storage.GetMinioPath(jobName, cloudbrain.ResultPath+"/"),
  830. Spec: spec,
  831. LabelName: evaluationIndex,
  832. }
  833. _, err = cloudbrain.GenerateTask(req)
  834. if err != nil {
  835. return err
  836. }
  837. return nil
  838. }
  839. func getGpuModelSafetyCommand(BootFile string, params string, CkptName string, DisplayJobName string) (string, error) {
  840. var command string
  841. bootFile := strings.TrimSpace(BootFile)
  842. if !strings.HasSuffix(bootFile, ".py") {
  843. log.Error("bootFile(%s) format error", bootFile)
  844. return command, errors.New("bootFile format error")
  845. }
  846. var parameters models.Parameters
  847. var param string
  848. if len(params) != 0 {
  849. err := json.Unmarshal([]byte(params), &parameters)
  850. if err != nil {
  851. log.Error("Failed to Unmarshal params: %s (%v)", params, err)
  852. return command, err
  853. }
  854. for _, parameter := range parameters.Parameter {
  855. param += " --" + parameter.Label + "=" + parameter.Value
  856. }
  857. }
  858. param += " --ckpt_url=" + cloudbrain.ModelMountPath + "/" + CkptName
  859. command += "python /code/" + bootFile + param + " > " + cloudbrain.ResultPath + "/" + DisplayJobName + "-" + cloudbrain.LogFile
  860. return command, nil
  861. }
  862. func modelSafetyNewDataPrepare(ctx *context.Context) error {
  863. ctx.Data["PageIsCloudBrain"] = true
  864. ctx.Data["type"] = ctx.QueryInt("type")
  865. ctx.Data["boot_file"] = ctx.Query("boot_file")
  866. ctx.Data["display_job_name"] = ctx.Query("display_job_name")
  867. ctx.Data["description"] = ctx.Query("description")
  868. ctx.Data["image"] = strings.TrimSpace(ctx.Query("image"))
  869. ctx.Data["src_dataset"] = ctx.Query("src_dataset") //uuid
  870. ctx.Data["combat_dataset"] = ctx.Query("combat_dataset") //uuid
  871. ctx.Data["evaluationIndex"] = ctx.Query("evaluation_index")
  872. ctx.Data["run_para_list"] = ctx.Query("run_para_list")
  873. ctx.Data["spec_id"] = ctx.QueryInt64("spec_id")
  874. ctx.Data["train_url"] = ctx.Query("train_url")
  875. ctx.Data["ckpt_name"] = ctx.Query("ckpt_name")
  876. ctx.Data["train_url"] = ctx.Query("train_url")
  877. ctx.Data["ckpt_name"] = ctx.Query("ckpt_name")
  878. ctx.Data["model_name"] = ctx.Query("model_name")
  879. ctx.Data["model_version"] = ctx.Query("model_version")
  880. NotStopTaskCount, _ := models.GetModelSafetyCountByUserID(ctx.User.ID)
  881. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  882. if ctx.QueryInt("type") == models.TypeCloudBrainOne {
  883. ctx.Data["type"] = models.TypeCloudBrainOne
  884. ctx.Data["compute_resource"] = models.GPUResource
  885. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  886. ctx.Data["BaseDataSetName"] = setting.ModelSafetyTest.GPUBaseDataSetName
  887. ctx.Data["BaseDataSetUUID"] = setting.ModelSafetyTest.GPUBaseDataSetUUID
  888. ctx.Data["CombatDataSetName"] = setting.ModelSafetyTest.GPUCombatDataSetName
  889. ctx.Data["CombatDataSetUUID"] = setting.ModelSafetyTest.GPUCombatDataSetUUID
  890. prepareCloudbrainOneSpecs(ctx)
  891. queuesDetail, _ := cloudbrain.GetQueuesDetail()
  892. if queuesDetail != nil {
  893. ctx.Data["QueuesDetail"] = queuesDetail
  894. }
  895. } else {
  896. ctx.Data["engine_id"] = ctx.QueryInt("engine_id")
  897. ctx.Data["pool_id"] = ctx.Query("pool_id")
  898. ctx.Data["type"] = models.TypeCloudBrainTwo
  899. ctx.Data["compute_resource"] = models.NPUResource
  900. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  901. ctx.Data["BaseDataSetName"] = setting.ModelSafetyTest.NPUBaseDataSetName
  902. ctx.Data["BaseDataSetUUID"] = setting.ModelSafetyTest.NPUBaseDataSetUUID
  903. ctx.Data["CombatDataSetName"] = setting.ModelSafetyTest.NPUCombatDataSetName
  904. ctx.Data["CombatDataSetUUID"] = setting.ModelSafetyTest.NPUCombatDataSetUUID
  905. var engines modelarts.Engine
  906. if err := json.Unmarshal([]byte(setting.Engines), &engines); err != nil {
  907. ctx.ServerError("json.Unmarshal failed:", err)
  908. }
  909. ctx.Data["engines"] = engines.Info
  910. var versionInfos modelarts.VersionInfo
  911. if err := json.Unmarshal([]byte(setting.EngineVersions), &versionInfos); err != nil {
  912. ctx.ServerError("json.Unmarshal failed:", err)
  913. }
  914. ctx.Data["engine_versions"] = versionInfos.Version
  915. prepareCloudbrainTwoInferenceSpecs(ctx)
  916. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeCloudBrainTwo, "")
  917. ctx.Data["WaitCount"] = waitCount
  918. }
  919. return nil
  920. }
  921. func getJsonContent(url string) (string, error) {
  922. resp, err := http.Get(url)
  923. if err != nil || resp.StatusCode != 200 {
  924. log.Info("Get organizations url error=" + err.Error())
  925. return "", err
  926. }
  927. bytes, err := ioutil.ReadAll(resp.Body)
  928. resp.Body.Close()
  929. if err != nil {
  930. log.Info("Get organizations url error=" + err.Error())
  931. return "", err
  932. }
  933. str := string(bytes)
  934. //log.Info("json str =" + str)
  935. return str, nil
  936. }