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