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

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