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