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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104
  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. var canLogDownload bool
  828. if err != nil {
  829. canLogDownload = false
  830. } else {
  831. canLogDownload = true
  832. }
  833. ctx.JSON(http.StatusOK, map[string]interface{}{
  834. "JobName": job.JobName,
  835. "Content": content,
  836. "CanLogDownload": canLogDownload,
  837. })
  838. return
  839. }
  840. func generateCommand(repoName, processorType, codeRemotePath, dataRemotePath, bootFile, paramSrc, outputRemotePath, datasetName, pretrainModelPath, pretrainModelFileName, modelRemoteObsUrl string) (string, error) {
  841. var command string
  842. //prepare
  843. workDir := grampus.NpuWorkDir
  844. if processorType == grampus.ProcessorTypeNPU {
  845. command += "pwd;cd " + workDir + grampus.CommandPrepareScriptNpu
  846. } else if processorType == grampus.ProcessorTypeGPU {
  847. workDir = grampus.GpuWorkDir
  848. command += "pwd;cd " + workDir + fmt.Sprintf(grampus.CommandPrepareScriptGpu, setting.Grampus.SyncScriptProject, setting.Grampus.SyncScriptProject)
  849. }
  850. //download code & dataset
  851. if processorType == grampus.ProcessorTypeNPU {
  852. //no need to download code & dataset by internet
  853. } else if processorType == grampus.ProcessorTypeGPU {
  854. commandDownload := "./downloader_for_minio " + setting.Grampus.Env + " " + codeRemotePath + " " + grampus.CodeArchiveName + " '" + dataRemotePath + "' '" + datasetName + "'"
  855. commandDownload = processPretrainModelParameter(pretrainModelPath, pretrainModelFileName, commandDownload)
  856. command += commandDownload
  857. }
  858. //unzip code & dataset
  859. if processorType == grampus.ProcessorTypeNPU {
  860. //no need to process
  861. } else if processorType == grampus.ProcessorTypeGPU {
  862. unZipDatasetCommand := cloudbrainTask.GenerateDatasetUnzipCommand(datasetName)
  863. commandUnzip := "cd " + workDir + "code;unzip -q master.zip;rm -f master.zip;echo \"start to unzip dataset\";cd " + workDir + "dataset;" + unZipDatasetCommand
  864. command += commandUnzip
  865. }
  866. command += "echo \"unzip finished;start to exec code;\";"
  867. // set export
  868. var commandExport string
  869. if processorType == grampus.ProcessorTypeNPU {
  870. commandExport = "export bucket=" + setting.Bucket + " && export remote_path=" + outputRemotePath + ";"
  871. } else if processorType == grampus.ProcessorTypeGPU {
  872. commandExport = "export env=" + setting.Grampus.Env + " && export remote_path=" + outputRemotePath + ";"
  873. }
  874. command += commandExport
  875. //exec code
  876. var parameters models.Parameters
  877. var paramCode string
  878. if len(paramSrc) != 0 {
  879. err := json.Unmarshal([]byte(paramSrc), &parameters)
  880. if err != nil {
  881. log.Error("Failed to Unmarshal params: %s (%v)", paramSrc, err)
  882. return command, err
  883. }
  884. for _, parameter := range parameters.Parameter {
  885. paramCode += " --" + parameter.Label + "=" + parameter.Value
  886. }
  887. }
  888. var commandCode string
  889. if processorType == grampus.ProcessorTypeNPU {
  890. paramCode += " --model_url=" + modelRemoteObsUrl
  891. commandCode = "/bin/bash /home/work/run_train_for_openi.sh /home/work/openi.py " + grampus.NpuLocalLogUrl + paramCode + ";"
  892. } else if processorType == grampus.ProcessorTypeGPU {
  893. if pretrainModelFileName != "" {
  894. paramCode += " --ckpt_url" + "=" + workDir + "pretrainmodel/" + pretrainModelFileName
  895. }
  896. commandCode = "cd " + workDir + "code/" + strings.ToLower(repoName) + ";python " + bootFile + paramCode + ";"
  897. }
  898. command += commandCode
  899. //get exec result
  900. commandGetRes := "result=$?;"
  901. command += commandGetRes
  902. //upload models
  903. if processorType == grampus.ProcessorTypeNPU {
  904. // no need to upload
  905. } else if processorType == grampus.ProcessorTypeGPU {
  906. commandUpload := "cd " + workDir + setting.Grampus.SyncScriptProject + "/;./uploader_for_gpu " + setting.Grampus.Env + " " + outputRemotePath + " " + workDir + "output/;"
  907. command += commandUpload
  908. }
  909. //check exec result
  910. commandCheckRes := "bash -c \"[[ $result -eq 0 ]] && exit 0 || exit -1\""
  911. command += commandCheckRes
  912. return command, nil
  913. }
  914. func processPretrainModelParameter(pretrainModelPath string, pretrainModelFileName string, commandDownload string) string {
  915. commandDownloadTemp := commandDownload
  916. if pretrainModelPath != "" {
  917. commandDownloadTemp += " '" + pretrainModelPath + "' '" + pretrainModelFileName + "'"
  918. }
  919. commandDownloadTemp += ";"
  920. return commandDownloadTemp
  921. }
  922. func downloadZipCode(ctx *context.Context, codePath, branchName string) error {
  923. archiveType := git.ZIP
  924. archivePath := codePath
  925. if !com.IsDir(archivePath) {
  926. if err := os.MkdirAll(archivePath, os.ModePerm); err != nil {
  927. log.Error("MkdirAll failed:" + err.Error())
  928. return err
  929. }
  930. }
  931. // Get corresponding commit.
  932. var (
  933. commit *git.Commit
  934. err error
  935. )
  936. gitRepo := ctx.Repo.GitRepo
  937. if err != nil {
  938. log.Error("OpenRepository failed:" + err.Error())
  939. return err
  940. }
  941. if gitRepo.IsBranchExist(branchName) {
  942. commit, err = gitRepo.GetBranchCommit(branchName)
  943. if err != nil {
  944. log.Error("GetBranchCommit failed:" + err.Error())
  945. return err
  946. }
  947. } else {
  948. log.Error("the branch is not exist: " + branchName)
  949. return fmt.Errorf("The branch does not exist.")
  950. }
  951. archivePath = path.Join(archivePath, grampus.CodeArchiveName)
  952. if !com.IsFile(archivePath) {
  953. if err := commit.CreateArchive(archivePath, git.CreateArchiveOpts{
  954. Format: archiveType,
  955. Prefix: setting.Repository.PrefixArchiveFiles,
  956. }); err != nil {
  957. log.Error("CreateArchive failed:" + err.Error())
  958. return err
  959. }
  960. }
  961. return nil
  962. }