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 34 kB

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