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.

ai_model_convert.go 21 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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. "strings"
  12. "code.gitea.io/gitea/models"
  13. "code.gitea.io/gitea/modules/cloudbrain"
  14. "code.gitea.io/gitea/modules/context"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/modelarts"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/storage"
  20. "code.gitea.io/gitea/modules/timeutil"
  21. uuid "github.com/satori/go.uuid"
  22. )
  23. const (
  24. tplModelManageConvertIndex = "repo/modelmanage/convertIndex"
  25. tplModelConvertInfo = "repo/modelmanage/convertshowinfo"
  26. PYTORCH_ENGINE = 0
  27. TENSORFLOW_ENGINE = 1
  28. MINDSPORE_ENGIN = 2
  29. ModelMountPath = "/model"
  30. CodeMountPath = "/code"
  31. DataSetMountPath = "/dataset"
  32. LogFile = "log.txt"
  33. DefaultBranchName = "master"
  34. SubTaskName = "task1"
  35. GpuQueue = "openidgx"
  36. Success = "S000"
  37. GPU_PYTORCH_IMAGE = "dockerhub.pcl.ac.cn:5000/user-images/openi:tensorRT_7_zouap"
  38. GPU_TENSORFLOW_IMAGE = "dockerhub.pcl.ac.cn:5000/user-images/openi:tf2onnx"
  39. PytorchOnnxBootFile = "convert_pytorch.py"
  40. PytorchTrTBootFile = "convert_pytorch_tensorrt.py"
  41. MindsporeBootFile = "convert_mindspore.py"
  42. TensorFlowNpuBootFile = "convert_tensorflow.py"
  43. TensorFlowGpuBootFile = "convert_tensorflow_gpu.py"
  44. ConvertRepoPath = "https://git.openi.org.cn/zouap/npu_test"
  45. REPO_ID = 33267
  46. CONVERT_FORMAT_ONNX = 0
  47. CONVERT_FORMAT_TRT = 1
  48. NetOutputFormat_FP32 = 0
  49. NetOutputFormat_FP16 = 1
  50. NPU_MINDSPORE_IMAGE_ID = 35
  51. NPU_TENSORFLOW_IMAGE_ID = 121
  52. GPU_Resource_Specs_ID = 1 //cpu 1, gpu 1
  53. NPU_FlavorCode = "modelarts.bm.910.arm.public.1"
  54. NPU_PoolID = "pool7908321a"
  55. )
  56. var (
  57. TrainResourceSpecs *models.ResourceSpecs
  58. )
  59. func SaveModelConvert(ctx *context.Context) {
  60. log.Info("save model convert start.")
  61. if !ctx.Repo.CanWrite(models.UnitTypeModelManage) {
  62. ctx.JSON(403, ctx.Tr("repo.model_noright"))
  63. return
  64. }
  65. name := ctx.Query("name")
  66. desc := ctx.Query("desc")
  67. modelId := ctx.Query("modelId")
  68. modelPath := ctx.Query("ModelFile")
  69. SrcEngine := ctx.QueryInt("SrcEngine")
  70. InputShape := ctx.Query("inputshape")
  71. InputDataFormat := ctx.Query("inputdataformat")
  72. DestFormat := ctx.QueryInt("DestFormat")
  73. NetOutputFormat := ctx.QueryInt("NetOutputFormat")
  74. task, err := models.QueryModelById(modelId)
  75. if err != nil {
  76. log.Error("no such model!", err.Error())
  77. ctx.ServerError("no such model:", err)
  78. return
  79. }
  80. uuid := uuid.NewV4()
  81. id := uuid.String()
  82. modelConvert := &models.AiModelConvert{
  83. ID: id,
  84. Name: name,
  85. Description: desc,
  86. Status: string(models.JobWaiting),
  87. SrcEngine: SrcEngine,
  88. RepoId: ctx.Repo.Repository.ID,
  89. ModelName: task.Name,
  90. ModelVersion: task.Version,
  91. ModelId: modelId,
  92. ModelPath: modelPath,
  93. DestFormat: DestFormat,
  94. NetOutputFormat: NetOutputFormat,
  95. InputShape: InputShape,
  96. InputDataFormat: InputDataFormat,
  97. UserId: ctx.User.ID,
  98. }
  99. models.SaveModelConvert(modelConvert)
  100. go goCreateTask(modelConvert, ctx, task)
  101. ctx.JSON(200, map[string]string{
  102. "result_code": "0",
  103. })
  104. }
  105. func goCreateTask(modelConvert *models.AiModelConvert, ctx *context.Context, task *models.AiModelManage) error {
  106. if modelConvert.IsGpuTrainTask() {
  107. log.Info("create gpu train job.")
  108. return createGpuTrainJob(modelConvert, ctx, task)
  109. } else {
  110. //create npu job
  111. log.Info("create npu train job.")
  112. return createNpuTrainJob(modelConvert, ctx, task.Path)
  113. }
  114. }
  115. func createNpuTrainJob(modelConvert *models.AiModelConvert, ctx *context.Context, modelRelativePath string) error {
  116. VersionOutputPath := "V0001"
  117. codeLocalPath := setting.JobPath + modelConvert.ID + modelarts.CodePath
  118. codeObsPath := "/" + setting.Bucket + modelarts.JobPath + modelConvert.ID + modelarts.CodePath
  119. outputObsPath := "/" + setting.Bucket + modelarts.JobPath + modelConvert.ID + modelarts.OutputPath + VersionOutputPath + "/"
  120. logObsPath := "/" + setting.Bucket + modelarts.JobPath + modelConvert.ID + modelarts.LogPath + VersionOutputPath + "/"
  121. dataPath := "/" + modelRelativePath
  122. _, err := ioutil.ReadDir(codeLocalPath)
  123. if err == nil {
  124. os.RemoveAll(codeLocalPath)
  125. }
  126. if err := downloadConvertCode(ConvertRepoPath, codeLocalPath, DefaultBranchName); err != nil {
  127. log.Error("downloadCode failed, server timed out: %s (%v)", ConvertRepoPath, err)
  128. return err
  129. }
  130. if err := obsMkdir(setting.CodePathPrefix + modelConvert.ID + modelarts.OutputPath + VersionOutputPath + "/"); err != nil {
  131. log.Error("Failed to obsMkdir_output: %s (%v)", modelConvert.ID+modelarts.OutputPath, err)
  132. return err
  133. }
  134. if err := obsMkdir(setting.CodePathPrefix + modelConvert.ID + modelarts.LogPath + VersionOutputPath + "/"); err != nil {
  135. log.Error("Failed to obsMkdir_log: %s (%v)", modelConvert.ID+modelarts.LogPath, err)
  136. return err
  137. }
  138. if err := uploadCodeToObs(codeLocalPath, modelConvert.ID, ""); err != nil {
  139. log.Error("Failed to uploadCodeToObs: %s (%v)", modelConvert.ID, err)
  140. return err
  141. }
  142. intputshape := strings.Split(modelConvert.InputShape, ",")
  143. n := "256"
  144. c := "1"
  145. h := "28"
  146. w := "28"
  147. if len(intputshape) == 4 {
  148. n = intputshape[0]
  149. c = intputshape[1]
  150. h = intputshape[2]
  151. w = intputshape[3]
  152. }
  153. param := make([]models.Parameter, 0)
  154. modelPara := models.Parameter{
  155. Label: "model",
  156. Value: modelConvert.ModelPath,
  157. }
  158. param = append(param, modelPara)
  159. batchSizePara := models.Parameter{
  160. Label: "n",
  161. Value: fmt.Sprint(n),
  162. }
  163. param = append(param, batchSizePara)
  164. channelSizePara := models.Parameter{
  165. Label: "c",
  166. Value: fmt.Sprint(c),
  167. }
  168. param = append(param, channelSizePara)
  169. heightPara := models.Parameter{
  170. Label: "h",
  171. Value: fmt.Sprint(h),
  172. }
  173. param = append(param, heightPara)
  174. widthPara := models.Parameter{
  175. Label: "w",
  176. Value: fmt.Sprint(w),
  177. }
  178. param = append(param, widthPara)
  179. var engineId int64
  180. engineId = int64(NPU_MINDSPORE_IMAGE_ID)
  181. bootfile := MindsporeBootFile
  182. if modelConvert.SrcEngine == TENSORFLOW_ENGINE {
  183. engineId = int64(NPU_TENSORFLOW_IMAGE_ID)
  184. bootfile = TensorFlowNpuBootFile
  185. }
  186. req := &modelarts.GenerateTrainJobReq{
  187. JobName: modelConvert.ID,
  188. DisplayJobName: modelConvert.Name,
  189. DataUrl: dataPath,
  190. Description: modelConvert.Description,
  191. CodeObsPath: codeObsPath,
  192. BootFileUrl: codeObsPath + bootfile,
  193. BootFile: bootfile,
  194. TrainUrl: outputObsPath,
  195. FlavorCode: NPU_FlavorCode,
  196. WorkServerNumber: 1,
  197. IsLatestVersion: modelarts.IsLatestVersion,
  198. EngineID: engineId,
  199. LogUrl: logObsPath,
  200. PoolID: NPU_PoolID,
  201. Parameters: param,
  202. BranchName: DefaultBranchName,
  203. }
  204. result, err := modelarts.GenerateModelConvertTrainJob(req)
  205. if err == nil {
  206. log.Info("jobId=" + fmt.Sprint(result.JobID) + " versionid=" + fmt.Sprint(result.VersionID))
  207. models.UpdateModelConvertModelArts(modelConvert.ID, fmt.Sprint(result.JobID), fmt.Sprint(result.VersionID))
  208. }
  209. return err
  210. }
  211. func downloadConvertCode(repopath string, codePath, branchName string) error {
  212. //add "file:///" prefix to make the depth valid
  213. if err := git.Clone(repopath, codePath, git.CloneRepoOptions{Branch: branchName, Depth: 1}); err != nil {
  214. log.Error("Failed to clone repository: %s (%v)", repopath, err)
  215. return err
  216. }
  217. log.Info("srcPath=" + repopath + " codePath=" + codePath)
  218. configFile, err := os.OpenFile(codePath+"/.git/config", os.O_RDWR, 0666)
  219. if err != nil {
  220. log.Error("open file(%s) failed:%v", codePath+"/,git/config", err)
  221. return err
  222. }
  223. defer configFile.Close()
  224. pos := int64(0)
  225. reader := bufio.NewReader(configFile)
  226. for {
  227. line, err := reader.ReadString('\n')
  228. if err != nil {
  229. if err == io.EOF {
  230. log.Error("not find the remote-url")
  231. return nil
  232. } else {
  233. log.Error("read error: %v", err)
  234. return err
  235. }
  236. }
  237. if strings.Contains(line, "url") && strings.Contains(line, ".git") {
  238. originUrl := "\turl = " + repopath + "\n"
  239. if len(line) > len(originUrl) {
  240. originUrl += strings.Repeat(" ", len(line)-len(originUrl))
  241. }
  242. bytes := []byte(originUrl)
  243. _, err := configFile.WriteAt(bytes, pos)
  244. if err != nil {
  245. log.Error("WriteAt failed:%v", err)
  246. return err
  247. }
  248. break
  249. }
  250. pos += int64(len(line))
  251. }
  252. return nil
  253. }
  254. func downloadFromObsToLocal(task *models.AiModelManage, localPath string) error {
  255. path := Model_prefix + models.AttachmentRelativePath(task.ID) + "/"
  256. allFile, err := storage.GetAllObjectByBucketAndPrefix(setting.Bucket, path)
  257. if err == nil {
  258. _, errState := os.Stat(localPath)
  259. if errState != nil {
  260. if err = os.MkdirAll(localPath, os.ModePerm); err != nil {
  261. return err
  262. }
  263. }
  264. for _, oneFile := range allFile {
  265. if oneFile.IsDir {
  266. log.Info(" dir name:" + oneFile.FileName)
  267. } else {
  268. allFileName := localPath + "/" + oneFile.FileName
  269. index := strings.LastIndex(allFileName, "/")
  270. if index != -1 {
  271. parentDir := allFileName[0:index]
  272. if err = os.MkdirAll(parentDir, os.ModePerm); err != nil {
  273. log.Info("make dir may be error," + err.Error())
  274. }
  275. }
  276. fDest, err := os.Create(allFileName)
  277. if err != nil {
  278. log.Info("create file error, download file failed: %s\n", err.Error())
  279. return err
  280. }
  281. body, err := storage.ObsDownloadAFile(setting.Bucket, path+oneFile.FileName)
  282. if err != nil {
  283. log.Info("download file failed: %s\n", err.Error())
  284. return err
  285. } else {
  286. defer body.Close()
  287. p := make([]byte, 1024)
  288. var readErr error
  289. var readCount int
  290. // 读取对象内容
  291. for {
  292. readCount, readErr = body.Read(p)
  293. if readCount > 0 {
  294. fDest.Write(p[:readCount])
  295. }
  296. if readErr != nil {
  297. break
  298. }
  299. }
  300. }
  301. }
  302. }
  303. } else {
  304. log.Info("error,msg=" + err.Error())
  305. return err
  306. }
  307. return nil
  308. }
  309. func createGpuTrainJob(modelConvert *models.AiModelConvert, ctx *context.Context, model *models.AiModelManage) error {
  310. modelRelativePath := model.Path
  311. command := ""
  312. IMAGE_URL := GPU_PYTORCH_IMAGE
  313. dataActualPath := setting.Attachment.Minio.RealPath + modelRelativePath
  314. if modelConvert.SrcEngine == PYTORCH_ENGINE {
  315. if modelConvert.DestFormat == CONVERT_FORMAT_ONNX {
  316. command = getGpuModelConvertCommand(modelConvert.ID, modelConvert.ModelPath, modelConvert, PytorchOnnxBootFile)
  317. } else if modelConvert.DestFormat == CONVERT_FORMAT_TRT {
  318. command = getGpuModelConvertCommand(modelConvert.ID, modelConvert.ModelPath, modelConvert, PytorchTrTBootFile)
  319. } else {
  320. return errors.New("Not support the format.")
  321. }
  322. } else if modelConvert.SrcEngine == TENSORFLOW_ENGINE {
  323. IMAGE_URL = GPU_TENSORFLOW_IMAGE
  324. if modelConvert.DestFormat == CONVERT_FORMAT_ONNX {
  325. command = getGpuModelConvertCommand(modelConvert.ID, modelConvert.ModelPath, modelConvert, TensorFlowGpuBootFile)
  326. } else {
  327. return errors.New("Not support the format.")
  328. }
  329. //如果模型在OBS上,需要下载到本地,并上传到minio中
  330. if model.Type == models.TypeCloudBrainTwo {
  331. relatetiveModelPath := setting.JobPath + modelConvert.ID + "/dataset"
  332. log.Info("local dataset path:" + relatetiveModelPath)
  333. downloadFromObsToLocal(model, relatetiveModelPath)
  334. uploadCodeToMinio(relatetiveModelPath+"/", modelConvert.ID, "/dataset/")
  335. dataActualPath = setting.Attachment.Minio.RealPath + setting.Attachment.Minio.Bucket + "/" + setting.CBCodePathPrefix + modelConvert.ID + "/dataset"
  336. }
  337. }
  338. log.Info("dataActualPath=" + dataActualPath)
  339. log.Info("command=" + command)
  340. codePath := setting.JobPath + modelConvert.ID + CodeMountPath
  341. downloadConvertCode(ConvertRepoPath, codePath, DefaultBranchName)
  342. uploadCodeToMinio(codePath+"/", modelConvert.ID, CodeMountPath+"/")
  343. minioCodePath := setting.Attachment.Minio.RealPath + setting.Attachment.Minio.Bucket + "/" + setting.CBCodePathPrefix + modelConvert.ID + "/code"
  344. log.Info("minio codePath=" + minioCodePath)
  345. modelPath := setting.JobPath + modelConvert.ID + ModelMountPath + "/"
  346. log.Info("local modelPath=" + modelPath)
  347. mkModelPath(modelPath)
  348. uploadCodeToMinio(modelPath, modelConvert.ID, ModelMountPath+"/")
  349. minioModelPath := setting.Attachment.Minio.RealPath + setting.Attachment.Minio.Bucket + "/" + setting.CBCodePathPrefix + modelConvert.ID + "/model"
  350. log.Info("minio model path=" + minioModelPath)
  351. if TrainResourceSpecs == nil {
  352. json.Unmarshal([]byte(setting.TrainResourceSpecs), &TrainResourceSpecs)
  353. }
  354. resourceSpec := TrainResourceSpecs.ResourceSpec[GPU_Resource_Specs_ID]
  355. jobResult, err := cloudbrain.CreateJob(modelConvert.ID, models.CreateJobParams{
  356. JobName: modelConvert.ID,
  357. RetryCount: 1,
  358. GpuType: GpuQueue,
  359. Image: IMAGE_URL,
  360. TaskRoles: []models.TaskRole{
  361. {
  362. Name: SubTaskName,
  363. TaskNumber: 1,
  364. MinSucceededTaskCount: 1,
  365. MinFailedTaskCount: 1,
  366. CPUNumber: resourceSpec.CpuNum,
  367. GPUNumber: resourceSpec.GpuNum,
  368. MemoryMB: resourceSpec.MemMiB,
  369. ShmMB: resourceSpec.ShareMemMiB,
  370. Command: command,
  371. NeedIBDevice: false,
  372. IsMainRole: false,
  373. UseNNI: false,
  374. },
  375. },
  376. Volumes: []models.Volume{
  377. {
  378. HostPath: models.StHostPath{
  379. Path: minioCodePath,
  380. MountPath: CodeMountPath,
  381. ReadOnly: false,
  382. },
  383. },
  384. {
  385. HostPath: models.StHostPath{
  386. Path: dataActualPath,
  387. MountPath: DataSetMountPath,
  388. ReadOnly: true,
  389. },
  390. },
  391. {
  392. HostPath: models.StHostPath{
  393. Path: minioModelPath,
  394. MountPath: ModelMountPath,
  395. ReadOnly: false,
  396. },
  397. },
  398. },
  399. })
  400. if err != nil {
  401. log.Error("CreateJob failed:", err.Error(), ctx.Data["MsgID"])
  402. return err
  403. }
  404. if jobResult.Code != Success {
  405. log.Error("CreateJob(%s) failed:%s", modelConvert.ID, jobResult.Msg, ctx.Data["MsgID"])
  406. return errors.New(jobResult.Msg)
  407. }
  408. var jobID = jobResult.Payload["jobId"].(string)
  409. log.Info("jobId=" + jobID)
  410. models.UpdateModelConvertCBTI(modelConvert.ID, jobID)
  411. return nil
  412. }
  413. func getGpuModelConvertCommand(name string, modelFile string, modelConvert *models.AiModelConvert, bootfile string) string {
  414. var command string
  415. intputshape := strings.Split(modelConvert.InputShape, ",")
  416. n := "256"
  417. c := "1"
  418. h := "28"
  419. w := "28"
  420. if len(intputshape) == 4 {
  421. n = intputshape[0]
  422. c = intputshape[1]
  423. h = intputshape[2]
  424. w = intputshape[3]
  425. }
  426. command += "python3 /code/" + bootfile + " --model " + modelFile + " --n " + n + " --c " + c + " --h " + h + " --w " + w
  427. if modelConvert.DestFormat == CONVERT_FORMAT_TRT {
  428. if modelConvert.NetOutputFormat == NetOutputFormat_FP16 {
  429. command += " --fp16 True"
  430. } else {
  431. command += " --fp16 False"
  432. }
  433. }
  434. command += " > " + ModelMountPath + "/" + name + "-" + LogFile
  435. return command
  436. }
  437. func DeleteModelConvert(ctx *context.Context) {
  438. log.Info("delete model convert start.")
  439. id := ctx.Params(":id")
  440. err := models.DeleteModelConvertById(id)
  441. if err != nil {
  442. ctx.JSON(500, err.Error())
  443. } else {
  444. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelmanage/convert_model")
  445. }
  446. }
  447. func StopModelConvert(ctx *context.Context) {
  448. id := ctx.Params(":id")
  449. log.Info("stop model convert start.id=" + id)
  450. job, err := models.QueryModelConvertById(id)
  451. if err != nil {
  452. ctx.ServerError("Not found task.", err)
  453. return
  454. }
  455. if job.IsGpuTrainTask() {
  456. err = cloudbrain.StopJob(job.CloudBrainTaskId)
  457. if err != nil {
  458. log.Error("Stop cloudbrain Job(%s) failed:%v", job.CloudBrainTaskId, err)
  459. }
  460. } else {
  461. _, err = modelarts.StopTrainJob(job.CloudBrainTaskId, job.ModelArtsVersionId)
  462. if err != nil {
  463. log.Error("Stop modelarts Job(%s) failed:%v", job.CloudBrainTaskId, err)
  464. }
  465. }
  466. job.Status = string(models.JobStopped)
  467. if job.EndTime == 0 {
  468. job.EndTime = timeutil.TimeStampNow()
  469. }
  470. models.ModelConvertSetDuration(job)
  471. err = models.UpdateModelConvert(job)
  472. if err != nil {
  473. log.Error("UpdateModelConvert failed:", err)
  474. }
  475. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelmanage/convert_model")
  476. }
  477. func ShowModelConvertInfo(ctx *context.Context) {
  478. ctx.Data["ID"] = ctx.Query("ID")
  479. ctx.Data["isModelManage"] = true
  480. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  481. job, err := models.QueryModelConvertById(ctx.Query("ID"))
  482. if err == nil {
  483. ctx.Data["task"] = job
  484. } else {
  485. ctx.ServerError("Not found task.", err)
  486. return
  487. }
  488. ctx.Data["Name"] = job.Name
  489. ctx.Data["canDownload"] = isOper(ctx, job.UserId)
  490. user, err := models.GetUserByID(job.UserId)
  491. if err == nil {
  492. job.UserName = user.Name
  493. job.UserRelAvatarLink = user.RelAvatarLink()
  494. }
  495. if job.IsGpuTrainTask() {
  496. ctx.Data["npu_display"] = "none"
  497. ctx.Data["gpu_display"] = "block"
  498. result, err := cloudbrain.GetJob(job.CloudBrainTaskId)
  499. if err != nil {
  500. log.Info("error:" + err.Error())
  501. ctx.Data["error"] = err.Error()
  502. return
  503. }
  504. if result != nil {
  505. jobRes, _ := models.ConvertToJobResultPayload(result.Payload)
  506. ctx.Data["result"] = jobRes
  507. taskRoles := jobRes.TaskRoles
  508. taskRes, _ := models.ConvertToTaskPod(taskRoles[cloudbrain.SubTaskName].(map[string]interface{}))
  509. ctx.Data["taskRes"] = taskRes
  510. ctx.Data["ExitDiagnostics"] = taskRes.TaskStatuses[0].ExitDiagnostics
  511. ctx.Data["AppExitDiagnostics"] = jobRes.JobStatus.AppExitDiagnostics
  512. job.Status = jobRes.JobStatus.State
  513. if jobRes.JobStatus.State != string(models.JobWaiting) && jobRes.JobStatus.State != string(models.JobFailed) {
  514. job.ContainerIp = taskRes.TaskStatuses[0].ContainerIP
  515. job.ContainerID = taskRes.TaskStatuses[0].ContainerID
  516. job.Status = taskRes.TaskStatuses[0].State
  517. }
  518. if jobRes.JobStatus.State != string(models.JobWaiting) {
  519. models.ModelComputeAndSetDuration(job, jobRes)
  520. err = models.UpdateModelConvert(job)
  521. if err != nil {
  522. log.Error("UpdateModelConvert failed:", err)
  523. }
  524. }
  525. }
  526. } else {
  527. ctx.Data["npu_display"] = "block"
  528. ctx.Data["gpu_display"] = "none"
  529. ctx.Data["ExitDiagnostics"] = ""
  530. ctx.Data["AppExitDiagnostics"] = ""
  531. }
  532. ctx.HTML(200, tplModelConvertInfo)
  533. }
  534. func ConvertModelTemplate(ctx *context.Context) {
  535. ctx.Data["isModelManage"] = true
  536. ctx.Data["MODEL_COUNT"] = 0
  537. ctx.Data["ModelManageAccess"] = ctx.Repo.CanWrite(models.UnitTypeModelManage)
  538. ctx.Data["TRAIN_COUNT"] = 0
  539. ShowModelConvertPageInfo(ctx)
  540. ctx.HTML(200, tplModelManageConvertIndex)
  541. }
  542. func ShowModelConvertPageInfo(ctx *context.Context) {
  543. log.Info("ShowModelConvertInfo start.")
  544. if !isQueryRight(ctx) {
  545. log.Info("no right.")
  546. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  547. return
  548. }
  549. page := ctx.QueryInt("page")
  550. if page <= 0 {
  551. page = 1
  552. }
  553. pageSize := ctx.QueryInt("pageSize")
  554. if pageSize <= 0 {
  555. pageSize = setting.UI.IssuePagingNum
  556. }
  557. repoId := ctx.Repo.Repository.ID
  558. modelResult, count, err := models.QueryModelConvert(&models.AiModelQueryOptions{
  559. ListOptions: models.ListOptions{
  560. Page: page,
  561. PageSize: pageSize,
  562. },
  563. RepoID: repoId,
  564. })
  565. if err != nil {
  566. log.Info("query db error." + err.Error())
  567. ctx.ServerError("Cloudbrain", err)
  568. return
  569. }
  570. userIds := make([]int64, len(modelResult))
  571. for i, model := range modelResult {
  572. model.IsCanOper = isOper(ctx, model.UserId)
  573. model.IsCanDelete = isCanDelete(ctx, model.UserId)
  574. userIds[i] = model.UserId
  575. }
  576. userNameMap := queryUserName(userIds)
  577. for _, model := range modelResult {
  578. value := userNameMap[model.UserId]
  579. if value != nil {
  580. model.UserName = value.Name
  581. model.UserRelAvatarLink = value.RelAvatarLink()
  582. }
  583. }
  584. pager := context.NewPagination(int(count), page, pageSize, 5)
  585. ctx.Data["Page"] = pager
  586. ctx.Data["Tasks"] = modelResult
  587. }
  588. func ModelConvertDownloadModel(ctx *context.Context) {
  589. log.Info("enter here......")
  590. id := ctx.Params(":id")
  591. job, err := models.QueryModelConvertById(id)
  592. if err != nil {
  593. ctx.ServerError("Not found task.", err)
  594. return
  595. }
  596. AllDownload := ctx.QueryBool("AllDownload")
  597. if AllDownload {
  598. if job.IsGpuTrainTask() {
  599. path := setting.CBCodePathPrefix + job.ID + "/model/"
  600. allFile, err := storage.GetAllObjectByBucketAndPrefixMinio(setting.Attachment.Minio.Bucket, path)
  601. if err == nil {
  602. returnFileName := job.Name + ".zip"
  603. MinioDownloadManyFile(path, ctx, returnFileName, allFile)
  604. } else {
  605. log.Info("error,msg=" + err.Error())
  606. ctx.ServerError("no file to download.", err)
  607. }
  608. } else {
  609. }
  610. } else {
  611. if job.IsGpuTrainTask() {
  612. parentDir := ctx.Query("parentDir")
  613. fileName := ctx.Query("fileName")
  614. jobName := ctx.Query("jobName")
  615. filePath := "jobs/" + jobName + "/model/" + parentDir
  616. url, err := storage.Attachments.PresignedGetURL(filePath, fileName)
  617. if err != nil {
  618. log.Error("PresignedGetURL failed: %v", err.Error(), ctx.Data["msgID"])
  619. ctx.ServerError("PresignedGetURL", err)
  620. return
  621. }
  622. //ctx.JSON(200, url)
  623. http.Redirect(ctx.Resp, ctx.Req.Request, url, http.StatusTemporaryRedirect)
  624. } else {
  625. }
  626. }
  627. }