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.

grampus.go 38 kB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102
  1. package repo
  2. import (
  3. "code.gitea.io/gitea/modules/urfs_client/urchin"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "os"
  10. "path"
  11. "strconv"
  12. "strings"
  13. "code.gitea.io/gitea/services/cloudbrain/cloudbrainTask"
  14. "code.gitea.io/gitea/modules/dataset"
  15. "code.gitea.io/gitea/services/cloudbrain/resource"
  16. "code.gitea.io/gitea/services/reward/point/account"
  17. "code.gitea.io/gitea/modules/auth"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/grampus"
  20. "code.gitea.io/gitea/modules/modelarts"
  21. "code.gitea.io/gitea/modules/notification"
  22. "code.gitea.io/gitea/modules/redis/redis_key"
  23. "code.gitea.io/gitea/modules/redis/redis_lock"
  24. "code.gitea.io/gitea/modules/timeutil"
  25. "code.gitea.io/gitea/modules/util"
  26. "github.com/unknwon/com"
  27. "code.gitea.io/gitea/models"
  28. "code.gitea.io/gitea/modules/base"
  29. "code.gitea.io/gitea/modules/cloudbrain"
  30. "code.gitea.io/gitea/modules/context"
  31. "code.gitea.io/gitea/modules/log"
  32. "code.gitea.io/gitea/modules/setting"
  33. cloudbrainService "code.gitea.io/gitea/services/cloudbrain"
  34. )
  35. const (
  36. tplGrampusTrainJobShow base.TplName = "repo/grampus/trainjob/show"
  37. //GPU
  38. tplGrampusTrainJobGPUNew base.TplName = "repo/grampus/trainjob/gpu/new"
  39. //NPU
  40. tplGrampusTrainJobNPUNew base.TplName = "repo/grampus/trainjob/npu/new"
  41. )
  42. func GrampusTrainJobGPUNew(ctx *context.Context) {
  43. ctx.Data["IsCreate"] = true
  44. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  45. if err != nil {
  46. ctx.ServerError("get new train-job info failed", err)
  47. return
  48. }
  49. ctx.HTML(http.StatusOK, tplGrampusTrainJobGPUNew)
  50. }
  51. func GrampusTrainJobNPUNew(ctx *context.Context) {
  52. ctx.Data["IsCreate"] = true
  53. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  54. if err != nil {
  55. ctx.ServerError("get new train-job info failed", err)
  56. return
  57. }
  58. ctx.HTML(200, tplGrampusTrainJobNPUNew)
  59. }
  60. func grampusTrainJobNewDataPrepare(ctx *context.Context, processType string) error {
  61. ctx.Data["PageIsCloudBrain"] = true
  62. var displayJobName = cloudbrainService.GetDisplayJobName(ctx.User.Name)
  63. ctx.Data["display_job_name"] = displayJobName
  64. //get valid images
  65. images, err := grampus.GetImages(processType)
  66. if err != nil {
  67. log.Error("GetImages failed:", err.Error())
  68. } else {
  69. ctx.Data["images"] = images.Infos
  70. }
  71. grampus.InitSpecialPool()
  72. ctx.Data["GPUEnabled"] = true
  73. ctx.Data["NPUEnabled"] = true
  74. includeCenters := make(map[string]struct{})
  75. excludeCenters := make(map[string]struct{})
  76. if grampus.SpecialPools != nil {
  77. for _, pool := range grampus.SpecialPools.Pools {
  78. if pool.IsExclusive {
  79. if !IsUserInOrgPool(ctx.User.ID, pool) {
  80. ctx.Data[pool.Type+"Enabled"] = false
  81. }
  82. } else {
  83. if strings.Contains(strings.ToLower(processType), strings.ToLower(pool.Type)) {
  84. if IsUserInOrgPool(ctx.User.ID, pool) {
  85. for _, center := range pool.Pool {
  86. includeCenters[center.Queue] = struct{}{}
  87. }
  88. } else {
  89. for _, center := range pool.Pool {
  90. excludeCenters[center.Queue] = struct{}{}
  91. }
  92. }
  93. }
  94. }
  95. }
  96. }
  97. //prepare available specs
  98. if processType == grampus.ProcessorTypeNPU {
  99. prepareGrampusTrainSpecs(ctx, models.NPU)
  100. } else if processType == grampus.ProcessorTypeGPU {
  101. prepareGrampusTrainSpecs(ctx, models.GPU)
  102. }
  103. //get branches
  104. branches, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  105. if err != nil {
  106. log.Error("GetBranches error:", err.Error())
  107. } else {
  108. ctx.Data["branches"] = branches
  109. }
  110. ctx.Data["branchName"] = ctx.Repo.BranchName
  111. if processType == grampus.ProcessorTypeGPU {
  112. ctx.Data["datasetType"] = models.TypeCloudBrainOne
  113. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, models.GPUResource, models.JobTypeTrain)
  114. ctx.Data["WaitCount"] = waitCount
  115. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.GPUResource)
  116. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  117. } else if processType == grampus.ProcessorTypeNPU {
  118. ctx.Data["datasetType"] = models.TypeCloudBrainTwo
  119. waitCount := cloudbrain.GetWaitingCloudbrainCount(models.TypeC2Net, models.NPUResource, models.JobTypeTrain)
  120. ctx.Data["WaitCount"] = waitCount
  121. NotStopTaskCount, _ := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.NPUResource)
  122. ctx.Data["NotStopTaskCount"] = NotStopTaskCount
  123. }
  124. if ctx.Cloudbrain != nil {
  125. uuids, datasetNames := dataset.GetFilterDeletedAttachments(ctx.Cloudbrain.Uuid)
  126. ctx.Data["attachment"] = uuids
  127. ctx.Data["boot_file"] = ctx.Cloudbrain.BootFile
  128. ctx.Data["image_id"] = ctx.Cloudbrain.ImageID
  129. ctx.Data["run_para_list"] = ctx.Cloudbrain.Parameters
  130. ctx.Data["description"] = ctx.Cloudbrain.Description
  131. ctx.Data["branch_name"] = ctx.Cloudbrain.BranchName
  132. ctx.Data["engine_name"] = ctx.Cloudbrain.EngineName
  133. ctx.Data["work_server_number"] = ctx.Cloudbrain.WorkServerNumber
  134. if ctx.Cloudbrain.Image != "" {
  135. ctx.Data["image"] = ctx.Cloudbrain.Image
  136. } else {
  137. ctx.Data["image"] = ctx.Cloudbrain.EngineName
  138. }
  139. ctx.Data["dataset_name"] = datasetNames
  140. ctx.Data["model_name"] = ctx.Cloudbrain.ModelName
  141. ctx.Data["model_version"] = ctx.Cloudbrain.ModelVersion
  142. ctx.Data["ckpt_name"] = ctx.Cloudbrain.CkptName
  143. ctx.Data["label_names"] = ctx.Cloudbrain.LabelName
  144. ctx.Data["pre_train_model_url"] = ctx.Cloudbrain.PreTrainModelUrl
  145. spec, _ := resource.GetCloudbrainSpec(ctx.Cloudbrain.ID)
  146. if spec != nil {
  147. ctx.Data["spec_id"] = spec.ID
  148. }
  149. }
  150. return nil
  151. }
  152. func GrampusTrainJobVersionNew(ctx *context.Context) {
  153. task := ctx.Cloudbrain
  154. ctx.Data["IsCreate"] = false
  155. if task.ComputeResource == models.GPUResource {
  156. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  157. if err != nil {
  158. ctx.ServerError("get new train-job version info failed", err)
  159. return
  160. }
  161. ctx.HTML(http.StatusOK, tplGrampusTrainJobGPUNew)
  162. } else if task.ComputeResource == models.NPUResource {
  163. err := grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  164. if err != nil {
  165. ctx.ServerError("get new train-job version info failed", err)
  166. return
  167. }
  168. ctx.HTML(200, tplGrampusTrainJobNPUNew)
  169. }
  170. }
  171. func prepareGrampusTrainSpecs(ctx *context.Context, computeResource string) {
  172. noteBookSpecs, _ := resource.FindAvailableSpecs(ctx.User.ID, models.FindSpecsOptions{
  173. JobType: models.JobTypeTrain,
  174. ComputeResource: computeResource,
  175. Cluster: models.C2NetCluster,
  176. })
  177. ctx.Data["Specs"] = noteBookSpecs
  178. }
  179. func getFilterSpecBySpecialPool(specs *models.GetGrampusResourceSpecsResult, includeCenters map[string]struct{}, excludeCenters map[string]struct{}) []models.GrampusSpec {
  180. if len(includeCenters) == 0 && len(excludeCenters) == 0 {
  181. return specs.Infos
  182. }
  183. var grampusSpecs []models.GrampusSpec
  184. for _, info := range specs.Infos {
  185. if isInIncludeCenters(info, includeCenters) || (len(excludeCenters) != 0 && isNotAllInExcludeCenters(info, excludeCenters)) {
  186. grampusSpecs = append(grampusSpecs, info)
  187. }
  188. }
  189. return grampusSpecs
  190. }
  191. func isInIncludeCenters(grampusSpec models.GrampusSpec, centers map[string]struct{}) bool {
  192. for _, center := range grampusSpec.Centers {
  193. if _, ok := centers[center.ID]; ok {
  194. return true
  195. }
  196. }
  197. return false
  198. }
  199. func isNotAllInExcludeCenters(grampusSpec models.GrampusSpec, centers map[string]struct{}) bool {
  200. for _, center := range grampusSpec.Centers {
  201. if _, ok := centers[center.ID]; !ok {
  202. return true
  203. }
  204. }
  205. return false
  206. }
  207. func IsUserInOrgPool(userId int64, pool *models.SpecialPool) bool {
  208. org, _ := models.GetOrgByName(pool.Org)
  209. if org != nil {
  210. isOrgMember, _ := models.IsOrganizationMember(org.ID, userId)
  211. return isOrgMember
  212. }
  213. return false
  214. }
  215. func grampusParamCheckCreateTrainJob(form auth.CreateGrampusTrainJobForm) error {
  216. if !strings.HasSuffix(strings.TrimSpace(form.BootFile), ".py") {
  217. log.Error("the boot file(%s) must be a python file", form.BootFile)
  218. return errors.New("启动文件必须是python文件")
  219. }
  220. if form.BranchName == "" {
  221. log.Error("the branch must not be null!", form.BranchName)
  222. return errors.New("代码分支不能为空!")
  223. }
  224. return nil
  225. }
  226. func GrampusTrainJobGpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  227. ctx.Data["IsCreate"] = true
  228. grampusTrainJobGpuCreate(ctx, form)
  229. }
  230. func grampusTrainJobGpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  231. displayJobName := form.DisplayJobName
  232. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  233. uuid := form.Attachment
  234. description := form.Description
  235. bootFile := strings.TrimSpace(form.BootFile)
  236. params := form.Params
  237. repo := ctx.Repo.Repository
  238. codeLocalPath := setting.JobPath + jobName + cloudbrain.CodeMountPath + "/"
  239. codeMinioPath := setting.CBCodePathPrefix + jobName + cloudbrain.CodeMountPath + "/"
  240. branchName := form.BranchName
  241. image := strings.TrimSpace(form.Image)
  242. tpl := tplGrampusTrainJobGPUNew
  243. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName))
  244. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  245. if !isOk {
  246. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  247. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  248. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplGrampusTrainJobGPUNew, &form)
  249. return
  250. }
  251. defer lock.UnLock()
  252. if !jobNamePattern.MatchString(displayJobName) {
  253. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  254. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  255. return
  256. }
  257. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  258. if err != nil || !bootFileExist {
  259. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  260. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  261. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpl, &form)
  262. return
  263. }
  264. //check count limit
  265. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.GPUResource)
  266. if err != nil {
  267. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  268. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  269. ctx.RenderWithErr("system error", tpl, &form)
  270. return
  271. } else {
  272. if count >= 1 {
  273. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  274. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  275. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  276. return
  277. }
  278. }
  279. //check param
  280. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  281. log.Error("paramCheckCreateTrainJob failed:(%v)", err, ctx.Data["MsgID"])
  282. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  283. ctx.RenderWithErr(err.Error(), tpl, &form)
  284. return
  285. }
  286. //check whether the task name in the project is duplicated
  287. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  288. if err == nil {
  289. if len(tasks) != 0 {
  290. log.Error("the job name did already exist", ctx.Data["MsgID"])
  291. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  292. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  293. return
  294. }
  295. } else {
  296. if !models.IsErrJobNotExist(err) {
  297. log.Error("system error, %v", err, ctx.Data["MsgID"])
  298. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  299. ctx.RenderWithErr("system error", tpl, &form)
  300. return
  301. }
  302. }
  303. //check specification
  304. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  305. JobType: models.JobTypeTrain,
  306. ComputeResource: models.GPU,
  307. Cluster: models.C2NetCluster,
  308. })
  309. if err != nil || spec == nil {
  310. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  311. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  312. return
  313. }
  314. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  315. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  316. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  317. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplGrampusTrainJobGPUNew, &form)
  318. return
  319. }
  320. //check dataset
  321. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid, models.GPU)
  322. if err != nil {
  323. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  324. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  325. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  326. return
  327. }
  328. //prepare code and out path
  329. _, err = ioutil.ReadDir(codeLocalPath)
  330. if err == nil {
  331. os.RemoveAll(codeLocalPath)
  332. }
  333. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  334. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  335. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  336. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  337. return
  338. }
  339. //todo: upload code (send to file_server todo this work?)
  340. //upload code
  341. if err := uploadCodeToMinio(codeLocalPath+"/", jobName, cloudbrain.CodeMountPath+"/"); err != nil {
  342. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  343. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  344. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  345. return
  346. }
  347. modelPath := setting.JobPath + jobName + cloudbrain.ModelMountPath + "/"
  348. if err := mkModelPath(modelPath); err != nil {
  349. log.Error("Failed to mkModelPath: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  350. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  351. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  352. return
  353. }
  354. //init model readme
  355. if err := uploadCodeToMinio(modelPath, jobName, cloudbrain.ModelMountPath+"/"); err != nil {
  356. log.Error("Failed to uploadCodeToMinio: %s (%v)", repo.FullName(), err, ctx.Data["MsgID"])
  357. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  358. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  359. return
  360. }
  361. var datasetRemotePath, allFileName string
  362. for _, datasetInfo := range datasetInfos {
  363. if datasetRemotePath == "" {
  364. datasetRemotePath = datasetInfo.DataLocalPath
  365. allFileName = datasetInfo.FullName
  366. } else {
  367. datasetRemotePath = datasetRemotePath + ";" + datasetInfo.DataLocalPath
  368. allFileName = allFileName + ";" + datasetInfo.FullName
  369. }
  370. }
  371. //prepare command
  372. preTrainModelPath := getPreTrainModelPath(form.PreTrainModelUrl, form.CkptName)
  373. command, err := generateCommand(repo.Name, grampus.ProcessorTypeGPU, codeMinioPath+cloudbrain.DefaultBranchName+".zip", datasetRemotePath, bootFile, params, setting.CBCodePathPrefix+jobName+cloudbrain.ModelMountPath+"/", allFileName, preTrainModelPath, form.CkptName, "")
  374. if err != nil {
  375. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  376. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  377. ctx.RenderWithErr("Create task failed, internal error", tpl, &form)
  378. return
  379. }
  380. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  381. req := &grampus.GenerateTrainJobReq{
  382. JobName: jobName,
  383. DisplayJobName: displayJobName,
  384. ComputeResource: models.GPUResource,
  385. ProcessType: grampus.ProcessorTypeGPU,
  386. Command: command,
  387. ImageUrl: image,
  388. Description: description,
  389. BootFile: bootFile,
  390. Uuid: uuid,
  391. CommitID: commitID,
  392. BranchName: branchName,
  393. Params: form.Params,
  394. EngineName: image,
  395. DatasetNames: datasetNames,
  396. DatasetInfos: datasetInfos,
  397. IsLatestVersion: modelarts.IsLatestVersion,
  398. VersionCount: modelarts.VersionCountOne,
  399. WorkServerNumber: 1,
  400. Spec: spec,
  401. }
  402. if form.ModelName != "" { //使用预训练模型训练
  403. req.ModelName = form.ModelName
  404. req.LabelName = form.LabelName
  405. req.CkptName = form.CkptName
  406. req.ModelVersion = form.ModelVersion
  407. req.PreTrainModelUrl = form.PreTrainModelUrl
  408. }
  409. _, err = grampus.GenerateTrainJob(ctx, req)
  410. if err != nil {
  411. log.Error("GenerateTrainJob failed:%v", err.Error(), ctx.Data["MsgID"])
  412. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeGPU)
  413. ctx.RenderWithErr(err.Error(), tpl, &form)
  414. return
  415. }
  416. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  417. }
  418. func getPreTrainModelPath(pretrainModelDir string, fileName string) string {
  419. index := strings.Index(pretrainModelDir, "/")
  420. if index > 0 {
  421. filterBucket := pretrainModelDir[index+1:]
  422. return filterBucket + fileName
  423. } else {
  424. return ""
  425. }
  426. }
  427. func GrampusTrainJobVersionCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  428. ctx.Data["IsCreate"] = false
  429. computeResource := ctx.Query("compute_resource")
  430. if computeResource == models.GPUResource {
  431. grampusTrainJobGpuCreate(ctx, form)
  432. } else if computeResource == models.NPUResource {
  433. grampusTrainJobNpuCreate(ctx, form)
  434. } else {
  435. ctx.ServerError("resource error", errors.New("compute resource is not support"))
  436. return
  437. }
  438. }
  439. func GrampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  440. ctx.Data["IsCreate"] = true
  441. grampusTrainJobNpuCreate(ctx, form)
  442. }
  443. func grampusTrainJobNpuCreate(ctx *context.Context, form auth.CreateGrampusTrainJobForm) {
  444. displayJobName := form.DisplayJobName
  445. jobName := util.ConvertDisplayJobNameToJobName(displayJobName)
  446. uuid := form.Attachment
  447. description := form.Description
  448. bootFile := strings.TrimSpace(form.BootFile)
  449. params := form.Params
  450. repo := ctx.Repo.Repository
  451. codeLocalPath := setting.JobPath + jobName + modelarts.CodePath
  452. codeObsPath := grampus.JobPath + jobName + modelarts.CodePath
  453. //dataObsPath := setting.BasePath + path.Join(uuid[0:1], uuid[1:2]) + "/" + uuid + "/"
  454. branchName := form.BranchName
  455. isLatestVersion := modelarts.IsLatestVersion
  456. versionCount := modelarts.VersionCountOne
  457. engineName := form.EngineName
  458. tpl := tplGrampusTrainJobNPUNew
  459. lock := redis_lock.NewDistributeLock(redis_key.CloudbrainBindingJobNameKey(fmt.Sprint(repo.ID), string(models.JobTypeTrain), displayJobName))
  460. isOk, err := lock.Lock(models.CloudbrainKeyDuration)
  461. if !isOk {
  462. log.Error("lock processed failed:%v", err, ctx.Data["MsgID"])
  463. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  464. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_samejob_err"), tplGrampusTrainJobNPUNew, &form)
  465. return
  466. }
  467. defer lock.UnLock()
  468. if !jobNamePattern.MatchString(displayJobName) {
  469. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  470. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_jobname_err"), tpl, &form)
  471. return
  472. }
  473. bootFileExist, err := ctx.Repo.FileExists(bootFile, branchName)
  474. if err != nil || !bootFileExist {
  475. log.Error("Get bootfile error:", err, ctx.Data["MsgID"])
  476. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  477. ctx.RenderWithErr(ctx.Tr("repo.cloudbrain_bootfile_err"), tpl, &form)
  478. return
  479. }
  480. //check count limit
  481. count, err := cloudbrainTask.GetNotFinalStatusTaskCount(ctx.User.ID, models.TypeC2Net, string(models.JobTypeTrain), models.NPUResource)
  482. if err != nil {
  483. log.Error("GetGrampusCountByUserID failed:%v", err, ctx.Data["MsgID"])
  484. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  485. ctx.RenderWithErr("system error", tpl, &form)
  486. return
  487. } else {
  488. if count >= 1 {
  489. log.Error("the user already has running or waiting task", ctx.Data["MsgID"])
  490. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  491. ctx.RenderWithErr("you have already a running or waiting task, can not create more", tpl, &form)
  492. return
  493. }
  494. }
  495. //check param
  496. if err := grampusParamCheckCreateTrainJob(form); err != nil {
  497. log.Error("paramCheckCreateTrainJob failed:(%v)", err)
  498. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  499. ctx.RenderWithErr(err.Error(), tpl, &form)
  500. return
  501. }
  502. //check whether the task name in the project is duplicated
  503. tasks, err := models.GetCloudbrainsByDisplayJobName(repo.ID, string(models.JobTypeTrain), displayJobName)
  504. if err == nil {
  505. if len(tasks) != 0 {
  506. log.Error("the job name did already exist", ctx.Data["MsgID"])
  507. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  508. ctx.RenderWithErr("the job name did already exist", tpl, &form)
  509. return
  510. }
  511. } else {
  512. if !models.IsErrJobNotExist(err) {
  513. log.Error("system error, %v", err, ctx.Data["MsgID"])
  514. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  515. ctx.RenderWithErr("system error", tpl, &form)
  516. return
  517. }
  518. }
  519. //check specification
  520. spec, err := resource.GetAndCheckSpec(ctx.User.ID, form.SpecId, models.FindSpecsOptions{
  521. JobType: models.JobTypeTrain,
  522. ComputeResource: models.NPU,
  523. Cluster: models.C2NetCluster,
  524. })
  525. if err != nil || spec == nil {
  526. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  527. ctx.RenderWithErr("Resource specification not available", tpl, &form)
  528. return
  529. }
  530. if !account.IsPointBalanceEnough(ctx.User.ID, spec.UnitPrice) {
  531. log.Error("point balance is not enough,userId=%d specId=%d", ctx.User.ID, spec.ID)
  532. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  533. ctx.RenderWithErr(ctx.Tr("points.insufficient_points_balance"), tplGrampusTrainJobNPUNew, &form)
  534. return
  535. }
  536. //check dataset
  537. datasetInfos, datasetNames, err := models.GetDatasetInfo(uuid, models.NPU)
  538. if err != nil {
  539. log.Error("GetDatasetInfo failed: %v", err, ctx.Data["MsgID"])
  540. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  541. ctx.RenderWithErr(ctx.Tr("cloudbrain.error.dataset_select"), tpl, &form)
  542. return
  543. }
  544. //prepare code and out path
  545. _, err = ioutil.ReadDir(codeLocalPath)
  546. if err == nil {
  547. os.RemoveAll(codeLocalPath)
  548. }
  549. if err := downloadZipCode(ctx, codeLocalPath, branchName); err != nil {
  550. log.Error("downloadZipCode failed, server timed out: %s (%v)", repo.FullName(), err)
  551. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  552. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  553. return
  554. }
  555. //todo: upload code (send to file_server todo this work?)
  556. if err := obsMkdir(setting.CodePathPrefix + jobName + modelarts.OutputPath); err != nil {
  557. log.Error("Failed to obsMkdir_output: %s (%v)", repo.FullName(), err)
  558. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  559. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  560. return
  561. }
  562. if err := uploadCodeToObs(codeLocalPath, jobName, ""); err != nil {
  563. log.Error("Failed to uploadCodeToObs: %s (%v)", repo.FullName(), err)
  564. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  565. ctx.RenderWithErr(ctx.Tr("cloudbrain.load_code_failed"), tpl, &form)
  566. return
  567. }
  568. var datasetRemotePath, allFileName string
  569. for _, datasetInfo := range datasetInfos {
  570. if datasetRemotePath == "" {
  571. datasetRemotePath = datasetInfo.DataLocalPath + "'" + datasetInfo.FullName + "'"
  572. allFileName = datasetInfo.FullName
  573. } else {
  574. datasetRemotePath = datasetRemotePath + ";" + datasetInfo.DataLocalPath + "'" + datasetInfo.FullName + "'"
  575. allFileName = allFileName + ";" + datasetInfo.FullName
  576. }
  577. }
  578. //prepare command
  579. preTrainModelPath := getPreTrainModelPath(form.PreTrainModelUrl, form.CkptName)
  580. command, err := generateCommand(repo.Name, grampus.ProcessorTypeNPU, codeObsPath+cloudbrain.DefaultBranchName+".zip", datasetRemotePath, bootFile, params, setting.CodePathPrefix+jobName+modelarts.OutputPath, allFileName, preTrainModelPath, form.CkptName, grampus.GetNpuModelRemoteObsUrl(jobName))
  581. if err != nil {
  582. log.Error("Failed to generateCommand: %s (%v)", displayJobName, err, ctx.Data["MsgID"])
  583. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  584. ctx.RenderWithErr("Create task failed, internal error", tpl, &form)
  585. return
  586. }
  587. commitID, _ := ctx.Repo.GitRepo.GetBranchCommitID(branchName)
  588. req := &grampus.GenerateTrainJobReq{
  589. JobName: jobName,
  590. DisplayJobName: displayJobName,
  591. ComputeResource: models.NPUResource,
  592. ProcessType: grampus.ProcessorTypeNPU,
  593. Command: command,
  594. ImageId: form.ImageID,
  595. Description: description,
  596. CodeObsPath: codeObsPath,
  597. BootFileUrl: codeObsPath + bootFile,
  598. BootFile: bootFile,
  599. WorkServerNumber: form.WorkServerNumber,
  600. Uuid: uuid,
  601. CommitID: commitID,
  602. IsLatestVersion: isLatestVersion,
  603. BranchName: branchName,
  604. Params: form.Params,
  605. EngineName: engineName,
  606. VersionCount: versionCount,
  607. TotalVersionCount: modelarts.TotalVersionCount,
  608. DatasetNames: datasetNames,
  609. DatasetInfos: datasetInfos,
  610. Spec: spec,
  611. CodeName: strings.ToLower(repo.Name),
  612. }
  613. if form.ModelName != "" { //使用预训练模型训练
  614. req.ModelName = form.ModelName
  615. req.LabelName = form.LabelName
  616. req.CkptName = form.CkptName
  617. req.ModelVersion = form.ModelVersion
  618. req.PreTrainModelUrl = form.PreTrainModelUrl
  619. req.PreTrainModelPath = preTrainModelPath
  620. }
  621. _, err = grampus.GenerateTrainJob(ctx, req)
  622. if err != nil {
  623. log.Error("GenerateTrainJob failed:%v", err.Error())
  624. grampusTrainJobNewDataPrepare(ctx, grampus.ProcessorTypeNPU)
  625. ctx.RenderWithErr(err.Error(), tpl, &form)
  626. return
  627. }
  628. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job")
  629. }
  630. func GrampusStopJob(ctx *context.Context) {
  631. var ID = ctx.Params(":jobid")
  632. var resultCode = "0"
  633. var errorMsg = ""
  634. var status = ""
  635. task := ctx.Cloudbrain
  636. for {
  637. if task.Status == string(models.GrampusStatusStopped) || task.Status == string(models.GrampusStatusFailed) || task.Status == string(models.GrampusStatusSucceeded) {
  638. log.Error("the job(%s) has been stopped", task.JobName, ctx.Data["msgID"])
  639. resultCode = "-1"
  640. errorMsg = "system error"
  641. break
  642. }
  643. res, err := grampus.StopJob(task.JobID)
  644. if err != nil {
  645. log.Error("StopJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  646. resultCode = strconv.Itoa(res.ErrorCode)
  647. errorMsg = res.ErrorMsg
  648. break
  649. }
  650. oldStatus := task.Status
  651. task.Status = string(models.GrampusStatusStopped)
  652. if task.EndTime == 0 {
  653. task.EndTime = timeutil.TimeStampNow()
  654. }
  655. task.ComputeAndSetDuration()
  656. if oldStatus != task.Status {
  657. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  658. }
  659. err = models.UpdateJob(task)
  660. if err != nil {
  661. log.Error("UpdateJob(%s) failed:%v", task.JobName, err, ctx.Data["msgID"])
  662. resultCode = "-1"
  663. errorMsg = "system error"
  664. break
  665. }
  666. status = task.Status
  667. break
  668. }
  669. ctx.JSON(200, map[string]interface{}{
  670. "result_code": resultCode,
  671. "error_msg": errorMsg,
  672. "status": status,
  673. "id": ID,
  674. "StatusOK": 0,
  675. })
  676. }
  677. func GrampusTrainJobDel(ctx *context.Context) {
  678. var listType = ctx.Query("listType")
  679. if err := deleteGrampusJob(ctx); err != nil {
  680. log.Error("deleteGrampusJob failed: %v", err, ctx.Data["msgID"])
  681. ctx.ServerError(err.Error(), err)
  682. return
  683. }
  684. var isAdminPage = ctx.Query("isadminpage")
  685. var isHomePage = ctx.Query("ishomepage")
  686. if ctx.IsUserSiteAdmin() && isAdminPage == "true" {
  687. ctx.Redirect(setting.AppSubURL + "/admin" + "/cloudbrains")
  688. } else if isHomePage == "true" {
  689. ctx.Redirect(setting.AppSubURL + "/cloudbrains")
  690. } else {
  691. ctx.Redirect(setting.AppSubURL + ctx.Repo.RepoLink + "/modelarts/train-job?listType=" + listType)
  692. }
  693. }
  694. func deleteGrampusJob(ctx *context.Context) error {
  695. task := ctx.Cloudbrain
  696. if task.Status != string(models.GrampusStatusStopped) && task.Status != string(models.GrampusStatusSucceeded) && task.Status != string(models.GrampusStatusFailed) {
  697. log.Error("the job(%s) has not been stopped", task.JobName, ctx.Data["msgID"])
  698. return errors.New("the job has not been stopped")
  699. }
  700. err := models.DeleteJob(task)
  701. if err != nil {
  702. log.Error("DeleteJob failed: %v", err, ctx.Data["msgID"])
  703. return err
  704. }
  705. storageType := models.TypeCloudBrainOne
  706. if task.ComputeResource == models.NPUResource {
  707. storageType = models.TypeCloudBrainTwo
  708. }
  709. DeleteCloudbrainJobStorage(task.JobName, storageType)
  710. return nil
  711. }
  712. func GrampusTrainJobShow(ctx *context.Context) {
  713. ctx.Data["PageIsCloudBrain"] = true
  714. var task *models.Cloudbrain
  715. task, err := models.GetCloudbrainByJobIDWithDeleted(ctx.Params(":jobid"))
  716. if err != nil {
  717. log.Error("GetCloudbrainByJobID failed:" + err.Error())
  718. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  719. return
  720. }
  721. task.ContainerIp = ""
  722. if task.DeletedAt.IsZero() { //normal record
  723. result, err := grampus.GetJob(task.JobID)
  724. if err != nil {
  725. log.Error("GetJob failed:" + err.Error())
  726. ctx.NotFound(ctx.Req.URL.RequestURI(), nil)
  727. return
  728. }
  729. if result != nil {
  730. if len(result.JobInfo.Tasks[0].CenterID) == 1 && len(result.JobInfo.Tasks[0].CenterName) == 1 {
  731. task.AiCenter = result.JobInfo.Tasks[0].CenterID[0] + "+" + result.JobInfo.Tasks[0].CenterName[0]
  732. }
  733. oldStatus := task.Status
  734. task.Status = grampus.TransTrainJobStatus(result.JobInfo.Status)
  735. if task.Status != oldStatus || task.Status == models.GrampusStatusRunning {
  736. task.Duration = result.JobInfo.RunSec
  737. if task.Duration < 0 {
  738. task.Duration = 0
  739. }
  740. task.TrainJobDuration = models.ConvertDurationToStr(task.Duration)
  741. if task.StartTime == 0 && result.JobInfo.StartedAt > 0 {
  742. task.StartTime = timeutil.TimeStamp(result.JobInfo.StartedAt)
  743. }
  744. if task.EndTime == 0 && models.IsTrainJobTerminal(task.Status) && task.StartTime > 0 {
  745. task.EndTime = task.StartTime.Add(task.Duration)
  746. }
  747. task.CorrectCreateUnix()
  748. if oldStatus != task.Status {
  749. notification.NotifyChangeCloudbrainStatus(task, oldStatus)
  750. if models.IsTrainJobTerminal(task.Status) && task.ComputeResource == models.NPUResource {
  751. if len(result.JobInfo.Tasks[0].CenterID) == 1 {
  752. urchin.GetBackNpuModel(task.ID, grampus.GetRemoteEndPoint(result.JobInfo.Tasks[0].CenterID[0]), grampus.BucketRemote, grampus.GetNpuModelObjectKey(task.JobName), grampus.GetCenterProxy(setting.Grampus.LocalCenterID))
  753. }
  754. }
  755. }
  756. err = models.UpdateJob(task)
  757. if err != nil {
  758. log.Error("UpdateJob failed:" + err.Error())
  759. }
  760. }
  761. }
  762. }
  763. if len(task.Parameters) > 0 {
  764. var parameters models.Parameters
  765. err := json.Unmarshal([]byte(task.Parameters), &parameters)
  766. if err != nil {
  767. log.Error("Failed to Unmarshal Parameters: %s (%v)", task.Parameters, err)
  768. ctx.ServerError("system error", err)
  769. return
  770. }
  771. if len(parameters.Parameter) > 0 {
  772. paramTemp := ""
  773. for _, Parameter := range parameters.Parameter {
  774. param := Parameter.Label + " = " + Parameter.Value + "; "
  775. paramTemp = paramTemp + param
  776. }
  777. task.Parameters = paramTemp[:len(paramTemp)-2]
  778. } else {
  779. task.Parameters = ""
  780. }
  781. }
  782. taskList := make([]*models.Cloudbrain, 0)
  783. taskList = append(taskList, task)
  784. prepareSpec4Show(ctx, task)
  785. ctx.Data["version_list_task"] = taskList
  786. ctx.Data["datasetDownload"] = GetCloudBrainDataSetInfo(task.Uuid, task.DatasetName, false)
  787. ctx.Data["canDownload"] = cloudbrain.CanModifyJob(ctx, task)
  788. ctx.Data["displayJobName"] = task.DisplayJobName
  789. ctx.Data["ai_center"] = cloudbrainService.GetAiCenterShow(task.AiCenter, ctx)
  790. ctx.HTML(http.StatusOK, tplGrampusTrainJobShow)
  791. }
  792. func GrampusDownloadLog(ctx *context.Context) {
  793. jobID := ctx.Params(":jobid")
  794. job, err := models.GetCloudbrainByJobID(jobID)
  795. if err != nil {
  796. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  797. ctx.ServerError(err.Error(), err)
  798. return
  799. }
  800. content, err := grampus.GetTrainJobLog(job.JobID)
  801. if err != nil {
  802. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  803. content = ""
  804. }
  805. fileName := job.JobName + "-log.txt"
  806. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+fileName)
  807. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  808. var b []byte = []byte(content)
  809. ctx.Resp.Write(b)
  810. }
  811. func GrampusGetLog(ctx *context.Context) {
  812. jobID := ctx.Params(":jobid")
  813. job, err := models.GetCloudbrainByJobID(jobID)
  814. if err != nil {
  815. log.Error("GetCloudbrainByJobID failed: %v", err, ctx.Data["MsgID"])
  816. ctx.ServerError(err.Error(), err)
  817. return
  818. }
  819. content, err := grampus.GetTrainJobLog(job.JobID)
  820. if err != nil {
  821. log.Error("GetTrainJobLog failed: %v", err, ctx.Data["MsgID"])
  822. ctx.ServerError(err.Error(), err)
  823. return
  824. }
  825. var canLogDownload bool
  826. if err != nil {
  827. canLogDownload = false
  828. } else {
  829. canLogDownload = true
  830. }
  831. ctx.JSON(http.StatusOK, map[string]interface{}{
  832. "JobName": job.JobName,
  833. "Content": content,
  834. "CanLogDownload": canLogDownload,
  835. })
  836. return
  837. }
  838. func generateCommand(repoName, processorType, codeRemotePath, dataRemotePath, bootFile, paramSrc, outputRemotePath, datasetName, pretrainModelPath, pretrainModelFileName, modelRemoteObsUrl string) (string, error) {
  839. var command string
  840. //prepare
  841. workDir := grampus.NpuWorkDir
  842. if processorType == grampus.ProcessorTypeNPU {
  843. command += "pwd;cd " + workDir + grampus.CommandPrepareScriptNpu
  844. } else if processorType == grampus.ProcessorTypeGPU {
  845. workDir = grampus.GpuWorkDir
  846. command += "pwd;cd " + workDir + fmt.Sprintf(grampus.CommandPrepareScriptGpu, setting.Grampus.SyncScriptProject, setting.Grampus.SyncScriptProject)
  847. }
  848. //download code & dataset
  849. if processorType == grampus.ProcessorTypeNPU {
  850. //no need to download code & dataset by internet
  851. } else if processorType == grampus.ProcessorTypeGPU {
  852. commandDownload := "./downloader_for_minio " + setting.Grampus.Env + " " + codeRemotePath + " " + grampus.CodeArchiveName + " '" + dataRemotePath + "' '" + datasetName + "'"
  853. commandDownload = processPretrainModelParameter(pretrainModelPath, pretrainModelFileName, commandDownload)
  854. command += commandDownload
  855. }
  856. //unzip code & dataset
  857. if processorType == grampus.ProcessorTypeNPU {
  858. //no need to process
  859. } else if processorType == grampus.ProcessorTypeGPU {
  860. unZipDatasetCommand := cloudbrainTask.GenerateDatasetUnzipCommand(datasetName)
  861. commandUnzip := "cd " + workDir + "code;unzip -q master.zip;rm -f master.zip;echo \"start to unzip dataset\";cd " + workDir + "dataset;" + unZipDatasetCommand
  862. command += commandUnzip
  863. }
  864. command += "echo \"unzip finished;start to exec code;\";"
  865. // set export
  866. var commandExport string
  867. if processorType == grampus.ProcessorTypeNPU {
  868. commandExport = "export bucket=" + setting.Bucket + " && export remote_path=" + outputRemotePath + ";"
  869. } else if processorType == grampus.ProcessorTypeGPU {
  870. commandExport = "export env=" + setting.Grampus.Env + " && export remote_path=" + outputRemotePath + ";"
  871. }
  872. command += commandExport
  873. //exec code
  874. var parameters models.Parameters
  875. var paramCode string
  876. if len(paramSrc) != 0 {
  877. err := json.Unmarshal([]byte(paramSrc), &parameters)
  878. if err != nil {
  879. log.Error("Failed to Unmarshal params: %s (%v)", paramSrc, err)
  880. return command, err
  881. }
  882. for _, parameter := range parameters.Parameter {
  883. paramCode += " --" + parameter.Label + "=" + parameter.Value
  884. }
  885. }
  886. var commandCode string
  887. if processorType == grampus.ProcessorTypeNPU {
  888. paramCode += " --model_url=" + modelRemoteObsUrl
  889. commandCode = "/bin/bash /home/work/run_train_for_openi.sh /home/work/openi.py " + grampus.NpuLocalLogUrl + paramCode + ";"
  890. } else if processorType == grampus.ProcessorTypeGPU {
  891. if pretrainModelFileName != "" {
  892. paramCode += " --ckpt_url" + "=" + workDir + "pretrainmodel/" + pretrainModelFileName
  893. }
  894. commandCode = "cd " + workDir + "code/" + strings.ToLower(repoName) + ";python " + bootFile + paramCode + ";"
  895. }
  896. command += commandCode
  897. //get exec result
  898. commandGetRes := "result=$?;"
  899. command += commandGetRes
  900. //upload models
  901. if processorType == grampus.ProcessorTypeNPU {
  902. // no need to upload
  903. } else if processorType == grampus.ProcessorTypeGPU {
  904. commandUpload := "cd " + workDir + setting.Grampus.SyncScriptProject + "/;./uploader_for_gpu " + setting.Grampus.Env + " " + outputRemotePath + " " + workDir + "output/;"
  905. command += commandUpload
  906. }
  907. //check exec result
  908. commandCheckRes := "bash -c \"[[ $result -eq 0 ]] && exit 0 || exit -1\""
  909. command += commandCheckRes
  910. return command, nil
  911. }
  912. func processPretrainModelParameter(pretrainModelPath string, pretrainModelFileName string, commandDownload string) string {
  913. commandDownloadTemp := commandDownload
  914. if pretrainModelPath != "" {
  915. commandDownloadTemp += " '" + pretrainModelPath + "' '" + pretrainModelFileName + "'"
  916. }
  917. commandDownloadTemp += ";"
  918. return commandDownloadTemp
  919. }
  920. func downloadZipCode(ctx *context.Context, codePath, branchName string) error {
  921. archiveType := git.ZIP
  922. archivePath := codePath
  923. if !com.IsDir(archivePath) {
  924. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  925. log.Error("MkdirAll failed:" + err.Error())
  926. return err
  927. }
  928. }
  929. // Get corresponding commit.
  930. var (
  931. commit *git.Commit
  932. err error
  933. )
  934. gitRepo := ctx.Repo.GitRepo
  935. if err != nil {
  936. log.Error("OpenRepository failed:" + err.Error())
  937. return err
  938. }
  939. if gitRepo.IsBranchExist(branchName) {
  940. commit, err = gitRepo.GetBranchCommit(branchName)
  941. if err != nil {
  942. log.Error("GetBranchCommit failed:" + err.Error())
  943. return err
  944. }
  945. } else {
  946. log.Error("the branch is not exist: " + branchName)
  947. return fmt.Errorf("The branch does not exist.")
  948. }
  949. archivePath = path.Join(archivePath, grampus.CodeArchiveName)
  950. if !com.IsFile(archivePath) {
  951. if err := commit.CreateArchive(archivePath, git.CreateArchiveOpts{
  952. Format: archiveType,
  953. Prefix: setting.Repository.PrefixArchiveFiles,
  954. }); err != nil {
  955. log.Error("CreateArchive failed:" + err.Error())
  956. return err
  957. }
  958. }
  959. return nil
  960. }